Consider this Raspberry Pi Python code controlling an LED connected to GPIO pin 18.
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) state = GPIO.input(18) print(state)
What will be printed?
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) state = GPIO.input(18) print(state)
GPIO.HIGH sets the pin to ON, so reading it back returns 1.
Setting GPIO.output(18, GPIO.HIGH) turns the pin ON. Reading it with GPIO.input(18) returns 1, which is printed.
You have an LED connected to GPIO pin 23. Which command will turn the LED OFF?
LOW means OFF, HIGH means ON.
GPIO.LOW sets the pin voltage to 0V, turning the LED OFF. GPIO.HIGH or 1 or True sets it ON.
Look at this code snippet:
import RPi.GPIO as GPIO GPIO.output(17, GPIO.HIGH)
When run, it raises a RuntimeError: 'You must setup() the GPIO channel first'. Why?
import RPi.GPIO as GPIO GPIO.output(17, GPIO.HIGH)
You must prepare the pin as output before setting its value.
GPIO.setup(pin, GPIO.OUT) configures the pin as output. Without it, output() raises RuntimeError.
Identify the code snippet that will cause a syntax error when trying to set GPIO pin 5 to LOW.
Check for missing commas or parentheses.
Option B misses a comma between arguments, causing a syntax error.
Given this code to blink an LED connected to GPIO pin 12:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
for i in range(5):
GPIO.output(12, GPIO.HIGH)
time.sleep(0.2)
GPIO.output(12, GPIO.LOW)
time.sleep(0.2)
GPIO.cleanup()How many times does the LED turn ON (blink) before the program ends?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.OUT) for i in range(5): GPIO.output(12, GPIO.HIGH) time.sleep(0.2) GPIO.output(12, GPIO.LOW) time.sleep(0.2) GPIO.cleanup()
Each loop cycle turns the LED ON once.
The loop runs 5 times, each time turning the LED ON once, so 5 blinks total.