Bird
0
0

What will be the output behavior of this code snippet controlling an LED and button on Raspberry Pi?

medium📝 Predict Output Q4 of 15
Raspberry Pi - LED and Button Projects
What will be the output behavior of this code snippet controlling an LED and button on Raspberry Pi? import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: if GPIO.input(20) == GPIO.LOW: GPIO.output(21, not GPIO.input(21)) time.sleep(0.3)
ALED stays ON permanently after first press
BLED toggles ON and OFF each time button is pressed
CLED never turns ON
DCode causes runtime error due to wrong GPIO input
Step-by-Step Solution
Solution:
  1. Step 1: Analyze button input and LED output setup

    Button is input with pull-up resistor; LED is output on pin 21.
  2. Step 2: Understand the toggle logic inside the loop

    When button pressed (input LOW), LED output is set to opposite of current state, toggling it.
  3. Final Answer:

    LED toggles ON and OFF each time button is pressed -> Option B
  4. Quick Check:

    Button press toggles LED = B [OK]
Quick Trick: Toggle LED by setting output to opposite of current state [OK]
Common Mistakes:
  • Assuming LED stays ON
  • Thinking LED never turns ON
  • Believing code causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes