Reading GPIO inputs

In the previous step, we controlled an LED as output. Here we see if we can read the input state of a button.

In this step, we would read the input value of a button in a tight loop and print it on the console, every time we detect a change.

We will use Python code again for this step, which looks as follows:
# 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)
#print initial settings
buttonState = GPIO.input(buttonPin);
print "Initial state is "
if buttonState
while 1:
buttonState = GPIO.input(buttonPin);
if prevButtonState != buttonState:
print "Button is "
if buttonState
# save last state
prevButtonState = buttonState;
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly:
GPIO.cleanup() # cleanup all GPIO

Run this file just like last time. If you modify the state of Pin 9 in the web view, you would see the program responds to the new state and prints the output as follows.

pi@raspberrypi ~ $ cd hello-iot
pi@raspberrypi ~ $ sudo python
Hello Button
Setting Broadcom Mode
Initial state is released
Button is released
Button is pressed
Button is released
Button is pressed

Congratulations! It completes your input/output programming practice.


Reading in a while (1) tight loop is generally not a good programming practice. It is used here only for the demonstration.