You want to write a Python program on Raspberry Pi that turns an LED on for 1 second, off for 1 second, and repeats this 5 times. Which code snippet correctly implements this behavior?
hard📝 Application Q15 of 15
Raspberry Pi - LED and Button Projects
You want to write a Python program on Raspberry Pi that turns an LED on for 1 second, off for 1 second, and repeats this 5 times. Which code snippet correctly implements this behavior?
Aimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.OUT)\nGPIO.output(21, GPIO.HIGH)\ntime.sleep(5)\nGPIO.output(21, GPIO.LOW)\nGPIO.cleanup()
Bimport RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.OUT)\nfor i in range(5):\n GPIO.output(21, GPIO.HIGH)\n time.sleep(1)\n GPIO.output(21, GPIO.LOW)\n time.sleep(1)\nGPIO.cleanup()
Cimport RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.OUT)\nfor i in range(5):\n GPIO.output(21, GPIO.LOW)\n time.sleep(1)\n GPIO.output(21, GPIO.HIGH)\n time.sleep(1)\nGPIO.cleanup()
Dimport RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(21, GPIO.OUT)\nGPIO.output(21, GPIO.HIGH)\ntime.sleep(1)\nGPIO.output(21, GPIO.LOW)\ntime.sleep(1)
Step-by-Step Solution
Solution:
Step 1: Understand the loop for repetition
The code uses for i in range(5): to repeat the on/off cycle 5 times.
Step 2: Correct on/off timing inside loop
Inside the loop, the LED is turned on (GPIO.HIGH) for 1 second, then off (GPIO.LOW) for 1 second.
Final Answer:
Code snippet C correctly repeats LED on/off 5 times with 1 second intervals -> Option B
Quick Check:
Loop with GPIO.HIGH then GPIO.LOW and sleep [OK]
Quick Trick:Use a loop with GPIO.HIGH, sleep, GPIO.LOW, sleep [OK]
Common Mistakes:
Swapping HIGH and LOW timing order
Missing import of time module
Not using a loop for repetition
Master "LED and Button Projects" in Raspberry Pi
9 interactive learning modes - each teaches the same concept differently