Bird
0
0

Consider this code snippet:

medium📝 Predict Output Q13 of 15
Raspberry Pi - LED and Button Projects

Consider this code snippet:

import RPi.GPIO as GPIO
import time

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

button_pressed = False

def button_callback(channel):
    global button_pressed
    button_pressed = True

GPIO.add_event_detect(18, GPIO.FALLING, callback=button_callback, bouncetime=200)

print("Waiting for button press...")

while not button_pressed:
    time.sleep(0.1)

print("Button was pressed!")
GPIO.cleanup()

What will be printed when the button connected to pin 18 is pressed?

AWaiting for button press...
BButton was pressed!\nWaiting for button press...
CWaiting for button press...\nButton was pressed!
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Understand program flow before button press

    The program prints "Waiting for button press..." and then waits in a loop until button_pressed becomes True.
  2. Step 2: Effect of button press and callback

    When the button is pressed, the callback sets button_pressed = True, breaking the loop and printing "Button was pressed!" before cleanup.
  3. Final Answer:

    Waiting for button press... Button was pressed! -> Option C
  4. Quick Check:

    Prints before and after button press [OK]
Quick Trick: Callback sets flag; loop waits; prints before and after press [OK]
Common Mistakes:
  • Thinking callback prints directly
  • Ignoring the loop waiting for flag
  • Assuming no output before press

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes