What will be the output of this Raspberry Pi Python code when the button connected to GPIO pin 17 is pressed?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: while True: if GPIO.input(17) == GPIO.LOW: print("Button pressed") break time.sleep(0.1) finally: GPIO.cleanup()
Remember that the button is connected with a pull-up resistor, so pressing it pulls the pin LOW.
The code sets up GPIO 17 as input with an internal pull-up resistor. When the button is pressed, the input reads LOW, triggering the print statement and breaking the loop.
What will this code print when the button connected to GPIO pin 22 is released after being pressed?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) try: while True: if GPIO.input(22) == GPIO.HIGH: print("Button released") break time.sleep(0.1) finally: GPIO.cleanup()
Check the pull-down resistor and what HIGH means for the button state.
The button is set with a pull-down resistor, so when released, the input reads HIGH, triggering the print statement.
Consider this code snippet intended to detect a button press on GPIO pin 5. Why does it never print "Pressed"?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.IN) while True: if GPIO.input(5) == GPIO.LOW: print("Pressed") break time.sleep(0.1)
Think about what happens if the input pin is not stabilized with a resistor.
Without a pull-up or pull-down resistor, the input pin floats and may never read LOW reliably, so the condition never triggers.
Which option correctly fixes the syntax error in this Raspberry Pi button detection code?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) if GPIO.input(18) == GPIO.LOW print("Button pressed")
Check the syntax of the if statement in Python.
Python requires a colon at the end of the if statement line to mark the start of the block.
This code detects button presses on GPIO pin 23 and prints "Pressed" each time the input reads LOW. The button is known to bounce (rapidly change state) when pressed. How many times will "Pressed" print if the button is pressed once?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) for _ in range(10): if GPIO.input(23) == GPIO.LOW: print("Pressed") time.sleep(0.01)
Think about how button bouncing affects the input signal during rapid reads.
Button bouncing causes the input to rapidly switch between LOW and HIGH, so the code may print "Pressed" multiple times during the loop.