Bird
0
0

You want to run a GPIO program that blinks an LED and always cleans up pins on exit, even on errors. Which code snippet correctly achieves this?

hard📝 Application Q8 of 15
Raspberry Pi - GPIO Basics with Python
You want to run a GPIO program that blinks an LED and always cleans up pins on exit, even on errors. Which code snippet correctly achieves this?
Aimport RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(21, GPIO.OUT) for _ in range(5): GPIO.output(21, True) time.sleep(0.5) GPIO.output(21, False) time.sleep(0.5) GPIO.cleanup()
Bimport RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) try: GPIO.setup(21, GPIO.OUT) for _ in range(5): GPIO.output(21, True) time.sleep(0.5) GPIO.output(21, False) time.sleep(0.5) finally: GPIO.cleanup()
Cimport RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) try: GPIO.setup(21, GPIO.OUT) while True: GPIO.output(21, True) time.sleep(0.5) GPIO.output(21, False) time.sleep(0.5) except: GPIO.cleanup()
Dimport RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) try: GPIO.setup(21, GPIO.OUT) for _ in range(5): GPIO.output(21, True) time.sleep(0.5) GPIO.output(21, False) time.sleep(0.5)
Step-by-Step Solution
Solution:
  1. Step 1: Check for cleanup in finally block

    import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) try: GPIO.setup(21, GPIO.OUT) for _ in range(5): GPIO.output(21, True) time.sleep(0.5) GPIO.output(21, False) time.sleep(0.5) finally: GPIO.cleanup() calls GPIO.cleanup() in finally, ensuring it runs always.
  2. Step 2: Verify blinking logic and error handling

    Loop runs 5 times blinking LED; cleanup runs even if error occurs.
  3. Final Answer:

    Code with try-finally and cleanup in finally -> Option B
  4. Quick Check:

    try-finally with cleanup = safe GPIO program [OK]
Quick Trick: Use try-finally with cleanup for safe GPIO programs [OK]
Common Mistakes:
  • Omitting cleanup in finally
  • Using except without finally
  • Not handling errors properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Raspberry Pi Quizzes