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:
hello-button.py# External module importsimport RPi.GPIO as GPIOimport timeprint("Hello Button")buttonPin = 9prevButtonState = TruebuttonState = Trueprint("Setting Broadcom Mode")# Pin Setup:GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering schemeGPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)time.sleep(0.5)#print initial settingsbuttonState = GPIO.input(buttonPin);print "Initial state is "if buttonState'pressesd'else'released';try:while 1:buttonState = GPIO.input(buttonPin);if prevButtonState != buttonState:print "Button is "if buttonState'pressed'else'released'# save last stateprevButtonState = buttonState;time.sleep(0.1)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-iotpi@raspberrypi ~ $ sudo python hello-button.pyHello ButtonSetting Broadcom ModeInitial state is releasedButton is releasedButton is pressedButton is releasedButton 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.