Consider this Python code controlling an LED connected to GPIO pin 17 on a Raspberry Pi. What will be the LED's behavior?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) for _ in range(3): GPIO.output(17, GPIO.HIGH) time.sleep(0.5) GPIO.output(17, GPIO.LOW) time.sleep(0.5) GPIO.cleanup()
Look at the loop and the sleep durations to understand how many times the LED changes state.
The loop runs 3 times. Each iteration turns the LED on for 0.5 seconds, then off for 0.5 seconds, resulting in 3 blinks.
This code controls two LEDs connected to GPIO pins 17 and 27. What is the resulting LED pattern?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) for _ in range(2): GPIO.output(17, GPIO.HIGH) GPIO.output(27, GPIO.LOW) time.sleep(1) GPIO.output(17, GPIO.LOW) GPIO.output(27, GPIO.HIGH) time.sleep(1) GPIO.cleanup()
Check which LED is on and off in each step inside the loop.
The code turns on LED 17 while LED 27 is off for 1 second, then switches states for 1 second, repeating twice.
Examine this code snippet intended to blink an LED connected to GPIO pin 22. Why does it raise an error?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.OUT) for i in range(3): GPIO.output(22, GPIO.HIGH) time.sleep(0.3) GPIO.output(22, GPIO.LOW) time.sleep(0.3) GPIO.cleanup()
Check the for loop syntax carefully.
The for loop line is missing a colon at the end, causing a SyntaxError.
This code runs a pattern on an LED connected to GPIO pin 5. How many times does the LED blink (turn on then off) before the program ends?
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(5, GPIO.OUT) for i in range(2): for j in range(3): GPIO.output(5, GPIO.HIGH) time.sleep(0.2) GPIO.output(5, GPIO.LOW) time.sleep(0.2) time.sleep(0.5) GPIO.cleanup()
Count the inner loop blinks and multiply by the outer loop iterations.
The inner loop blinks 3 times per outer loop iteration. The outer loop runs twice, so total blinks = 3 * 2 = 6.
Pulse Width Modulation (PWM) is often used to control LED brightness. What is the key advantage of using PWM instead of just turning the LED on and off quickly?
Think about how brightness changes without damaging the LED or wasting energy.
PWM changes the fraction of time the LED is on, controlling brightness smoothly without increasing voltage or current, which saves power and reduces heat.