Program to read from push button
In Chapter 4, Controlling LED Using a Push Button, we did a push button press detection exercise. Let's do the same in Python. Connect a push button as shown in Chapter 4. Type the following program in Cloud9, save it as push_button.py
and run. You should get Button is pressed
as the output when you press the button. When the button is not pressed, you get Button is released
printed as the output:
#!/usr/bin/python import Adafruit_BBIO.GPIO as GPIO from time import sleep button = 'P8_16' GPIO.setup(button,GPIO.IN) while True: if GPIO.input(button) == True: # Checks if the pin is HIGH print("Button is pressed") else: print("Button is released") sleep(1)
Explanation
In the preceding code, we chose pin P8_16
to connect to the push button. The push button is a component of input type. So, we set the direction as input using the GPIO.setup()
function. Now, we can read the state of the GPIO
pin. As this is a digital component, the state...