Tutorial 20: GPIO How to Use a Push Button

We have covered simple digital outputs with a LED. Now let's take a look at simple digital inputs using a push button connected to the Raspberry Pi's GPIO header. In this tutorial I show you how, in Python 3, you can read a signal input from a push button on a breadboard.

Although not covered in the video tutorial, I recommend you attach a 10kohm pull up resistor on the pin used to take a reading. When this is done you guarantee a 'high' reading when you are not pressing the button, vs. reading a floating pin. A floating pin is generally not recommended as it subjects your circuit to potential misreadings due to electrical noise and electrical interference.

This tutorial is a little older (published in 2015!). The main principles are still relevant, so I haven't needed to update this lesson.


DIFFICULTY
EASY
LINUX UNDERSTANDING
NONE
CIRCUITRY FAMILIARITY
LITTLE
PYTHON PROGRAMMING
SOME
ABOUT
0
MINUTES
  • How to build a simple circuit to receive an input from a push button
  • How to use Python 3 to identify GPIO changes on a Raspberry Pi
  • How to create an output using the GPIO header
You can copy / paste the code below if you’re having issues with typos or want a shortcut. However I recommend that you follow along in the tutorial to understand what is going on!


import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

blinkCount = 3
count = 0
LEDPin = 22
buttonPin = 5

# Setup the pin the LED is connected to
GPIO.setup(LEDPin, GPIO.OUT)
# Setup the button
GPIO.setup(buttonPin, GPIO.IN, pull_up_down = GPIO.PUD_UP)

buttonPress = True
ledState = False

try:
    while count < blinkCount:
        print("Come on man, press the button!")
        buttonPress = GPIO.input(buttonPin)
        if buttonPress == False and ledState == False:
            GPIO.output(LEDPin, True)
            print("LED ON")
            ledState = True
            sleep(3)
        elif buttonPress == False and ledState == True:
            GPIO.output(LEDPin, False)
            print("LED OFF")
            ledState = False
            count += 1
            sleep(0.5)
        sleep(0.1)
finally:
    # Reset the GPIO Pins to a safe state
    GPIO.output(LEDPin, False)
    GPIO.cleanup()


>

You shouldn’t need any additional materials to help you through this tutorial.