Use a Push Button with Raspberry Pi


Push buttons are an essential component in many Raspberry Pi projects and have many uses. 

In this guide, we will connect a momentary push button to a Raspberry Pi and program it using the GPIO Zero library. Upon button press, it will print out the words, "Button has been pressed!"

After completing this guide, you will have gained a basic understanding of how to wire up and program push buttons with the Raspberry Pi.

Step 1  Insert Push Button

  • Insert the Push Button so that it's legs are in Tie Points G36, G38, D36 and D38.

Step 2  Connect Ground to Push Button

  • Connect the Push Button to Ground with a Black Jumper between tie points B38 and A20.

Step 3  Connect GPIO17 to Push Button

  • Connect the Push Button to GPIO with a Red Jumper between tie points B36 and A6.

Step 4  Installing GPIO Zero

Now that we have the Raspberry Pi connected to the push button, we will need to program it. 

To do so, we will install GPIO Zero, a Python library which builds upon existing GPIO libraries such as RPI.GPIO, rPIO, and pigpio. It will simplify the process by reducing boilerplate code. 

After opening a terminal window, enter the following: 

sudo apt-get update 

sudo apt-get install python3-gpiozero

Step 5  Create file

  1. Click on the Raspberry Pi icon on the top left hand corner to access the main menu. 
  2. Click on Programming > Python 3 (IDLE). 
  3. Create a new file by clicking File > New File. 
  4. Next, save the file by clicking File > Save
  5. Name the file

Step 6  The code

              from gpiozero import Button
btn = Button(4)
while not btn.is_pressed:
print("Button was pushed!")

First, we will import the Button class from gpiozero library.

from gpiozero import Button

Then we will assign the variable btn to GPIO4:

btn = Button(4)

A never-ending while loop is required here:

while not btn.is_pressed:

When the button is pushed, the message "Button was pushed" will be printed:

print("Button was pushed!")