Bird
0
0

You wrote this code to read a button press on GPIO pin 5:

medium📝 Debug Q14 of 15
Raspberry Pi - GPIO Basics with Python
You wrote this code to read a button press on GPIO pin 5:
GPIO.setup(5, GPIO.IN)
if GPIO.input(5) == 1:
    print("Button pressed")
else:
    print("Button not pressed")
But the output is random even when the button is not pressed. What is the likely problem?
AYou forgot to enable a pull-up or pull-down resistor on pin 5
BYou set the pin mode to output instead of input
CYou used the wrong pin number
DYou need to call GPIO.cleanup() before reading input
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of random input readings

    Without pull-up or pull-down resistors, input pins can float and read random values.
  2. Step 2: Fix by enabling internal resistor

    Use GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP) or PUD_DOWN to stabilize input.
  3. Final Answer:

    You forgot to enable a pull-up or pull-down resistor on pin 5 -> Option A
  4. Quick Check:

    Floating input needs pull resistor = B [OK]
Quick Trick: Always enable pull resistor for input pins reading buttons [OK]
Common Mistakes:
  • Not setting pin as input
  • Assuming cleanup affects input reading
  • Changing pin number without hardware change

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes