Consider this Raspberry Pi Python code using GPIO interrupts. What will be printed when the button connected to GPIO pin 17 is pressed?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) def button_pressed(channel): print("Button pressed!") GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed, bouncetime=200) try: while True: time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
Think about what GPIO.add_event_detect does when the button is pressed.
The button_pressed function is called only when the button press triggers a falling edge on pin 17. So it prints "Button pressed!" once per press.
What error will this code produce when the button is pressed?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def button_pressed():
print("Pressed")
GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed)
Callback functions for GPIO interrupts receive the channel number as an argument.
The callback function must accept one argument (the channel). Here it has none, so Python raises a TypeError when called.
This code prints "Pressed" multiple times for a single button press. What is the likely cause?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def button_pressed(channel):
print("Pressed")
GPIO.add_event_detect(17, GPIO.FALLING, callback=button_pressed)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()Mechanical buttons can cause multiple signals quickly when pressed.
Without debounce (bouncetime), the button press causes multiple falling edges due to mechanical bounce, triggering the callback multiple times.
Choose the correct code snippet that sets up a button interrupt on GPIO 17 with a 300ms debounce time.
Check the parameter name and syntax for debounce in add_event_detect.
The correct parameter is bouncetime with an integer value. Option D uses correct syntax and parameter name.
You wrote a program using GPIO.add_event_detect for a button. What is the best way to ensure GPIO pins are cleaned up properly when the program ends?
Think about program termination and resource cleanup.
Using try-except with KeyboardInterrupt and calling GPIO.cleanup() in finally ensures pins are reset even if the program is stopped by Ctrl+C.