Bird
0
0

Identify the error in this Raspberry Pi button press detection code:

medium📝 Debug Q14 of 15
Raspberry Pi - LED and Button Projects
Identify the error in this Raspberry Pi button press detection code:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    if GPIO.input(23) == GPIO.HIGH:
        print("Button Pressed")
    time.sleep(0.1)
Atime.sleep(0.1) should be before the if statement.
BThe pull_up_down parameter is missing in GPIO.setup.
CThe code should check for GPIO.LOW to detect button press.
DGPIO.setmode(GPIO.BCM) is incorrect and should be GPIO.BOARD.
Step-by-Step Solution
Solution:
  1. Step 1: Review button wiring and logic

    With pull-up resistor, button press pulls pin LOW, not HIGH.
  2. Step 2: Check condition in if statement

    Code incorrectly checks for GPIO.HIGH to detect press; should check GPIO.LOW.
  3. Final Answer:

    The code should check for GPIO.LOW to detect button press. -> Option C
  4. Quick Check:

    Pull-up input reads LOW when pressed, so check GPIO.LOW [OK]
Quick Trick: Pressed button reads LOW on pull-up input pin [OK]
Common Mistakes:
  • Checking for HIGH instead of LOW on button press
  • Forgetting pull_up_down parameter
  • Misplacing sleep causing missed presses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes