Bird
0
0

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?

hard📝 Application Q15 of 15
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)
AThis code never prints anything because pressed is always True.
BThis code prints "Pressed" once per press and avoids repeats while held.
CThis code prints "Pressed" continuously while button is held down.
DThis code causes a syntax error due to missing colon.
Step-by-Step Solution
Solution:
  1. Step 1: Understand the pressed flag usage

    The variable 'pressed' tracks if the button press was already detected to avoid repeats.
  2. Step 2: Analyze the if-elif logic

    When button is LOW and not pressed, it prints once and sets pressed True; when released (HIGH), resets pressed to False.
  3. Final Answer:

    This code prints "Pressed" once per press and avoids repeats while held. -> Option B
  4. Quick Check:

    pressed flag prevents multiple prints during hold [OK]
Quick Trick: Use a flag variable to print once per press [OK]
Common Mistakes:
  • Printing inside loop without flag causes repeated prints
  • Not resetting flag on button release
  • Syntax errors from missing colons or indentation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes