Bird
0
0

What is wrong with this code snippet that tries to detect a button press on GPIO pin 22?

medium📝 Debug Q14 of 15
Raspberry Pi - LED and Button Projects

What is wrong with this code snippet that tries to detect a button press on GPIO pin 22?

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN)

def on_press(channel):
    print("Button pressed")

GPIO.add_event_detect(22, GPIO.RISING, callback=on_press)

while True:
    pass

GPIO.cleanup()
AMissing pull-up or pull-down resistor setup on pin 22
BCallback function should return a value
CGPIO.cleanup() is called before the loop ends
DUsing GPIO.RISING instead of GPIO.FALLING is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Check pin setup for input

    The code sets pin 22 as input but does not specify pull-up or pull-down resistors, which can cause floating input and unreliable detection.
  2. Step 2: Review other options

    Callback functions do not need to return values. The cleanup call is unreachable but not an error. Both RISING and FALLING edges are valid depending on wiring.
  3. Final Answer:

    Missing pull-up or pull-down resistor setup on pin 22 -> Option A
  4. Quick Check:

    Input pins need pull resistors to avoid floating [OK]
Quick Trick: Always set pull-up/down resistors for input pins [OK]
Common Mistakes:
  • Ignoring pull-up/down resistor setup
  • Expecting callback to return a value
  • Misunderstanding edge types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes