Raspberry Pi - LED and Button Projects
You want to detect a button press on GPIO 21 and print "Pressed" only once per press, avoiding multiple prints while the button is held down. Which code snippet correctly implements this behavior?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
pressed = False
while True:
if GPIO.input(21) == GPIO.LOW and not pressed:
print("Pressed")
pressed = True
elif GPIO.input(21) == GPIO.HIGH:
pressed = False
time.sleep(0.05)
