Reading GPIO inputs

In the previous example, we controlled an LED as an output device. In this example, we will read the state of a button in a loop and print it in the terminal, every time we detect a change.

Start by creating a file named hello-button.py and add the following python code inside it.

hello-button.py
# External module imports
import RPi.GPIO as GPIO
import time

print("Hello Button")
buttonPin = 9
prevButtonState = True
buttonState = True

print("Setting Broadcom Mode")
# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
time.sleep(0.5) 

#print initial settings
buttonState = GPIO.input(buttonPin)
print "Initial state is", 'pressed' if buttonState else 'released'
try:
    while 1:
        buttonState = GPIO.input(buttonPin)
        if prevButtonState != buttonState:
            print "Button is", 'pressed' if buttonState else 'released'
        # save last state
        prevButtonState = buttonState;    
        time.sleep(0.1) 
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
    GPIO.cleanup() # cleanup all GPIO

To run the program, go to the terminal and write:

python hello-button.py

Now, if you modify the state of Pin 9, you will see the program respond to the new state and print the output in the terminal.

To stop the program press Ctrl+C.

Congratulations! We now know how to read from the GPIO inputs.

Reading from a while (1) loop is generally not a good programming practice and is used here only for demonstration purposes.

Last updated