In this course, we’ll look at how to read the value of a pushbutton on the Raspberry Pi. This can be very useful for interacting with the user.
Here’s the diagram to connect the push button to the Raspberry Pi:
We’ve added a pull-down resistor so that when the push-button is not pressed, the board reads a low state and there are no undefined states.
Programming
Here is the program to read the values coming from the push button:
importRPi.GPIOasGPIOimport time
# Pin configuration
button_pin =17
# InitialGPIO configuration
GPIO.setmode(GPIO.BCM)GPIO.setup(button_pin,GPIO.IN, pull_up_down=GPIO.PUD_UP)try:print(“Wait until the button is pressed...”)whileTrue:ifGPIO.input(button_pin)==GPIO.LOW:print(“Button pressed!”)
time.sleep(0.2) # Debouncing, wait a short time to avoid button bouncing
whileGPIO.input(button_pin)==GPIO.LOW:
time.sleep(0.1) # Waitfor button to be released
time.sleep(0.1)
except KeyboardInterrupt:
pass
finally:
# CleanGPIO resources
GPIO.cleanup()
Thank you for trusting us.You'll receive the extract in your mailbox as soon as it's finished!