Challenge - 5 Problems
GPIO Cleanup Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
What is the output when GPIO cleanup is called?
Consider this Python code running on a Raspberry Pi using the RPi.GPIO library. What will be printed when the program exits?
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) try: GPIO.output(18, GPIO.HIGH) print("LED ON") time.sleep(1) finally: GPIO.cleanup() print("GPIO cleaned up")
Attempts:
2 left
💡 Hint
Look at what happens in the finally block after the try block.
✗ Incorrect
The try block prints 'LED ON'. The finally block always runs and calls GPIO.cleanup(), then prints 'GPIO cleaned up'. So both lines print in order.
❓ Predict Output
intermediate1:00remaining
What happens if GPIO.cleanup() is omitted?
What is the likely effect if a Raspberry Pi Python script using GPIO pins does NOT call GPIO.cleanup() before exiting?
Attempts:
2 left
💡 Hint
Think about what happens to GPIO pin states after the program ends.
✗ Incorrect
Without cleanup, pins stay configured and may cause warnings or unexpected behavior next time GPIO is used.
🔧 Debug
advanced2:00remaining
Identify the error preventing GPIO cleanup on exit
This code aims to clean up GPIO pins on program exit but fails to do so. What is the error?
Raspberry Pi
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) try: GPIO.output(17, GPIO.HIGH) time.sleep(2) except KeyboardInterrupt: print("Interrupted") finally: GPIO.cleanup() print("Cleanup done")
Attempts:
2 left
💡 Hint
Check how functions are called in Python.
✗ Incorrect
GPIO.cleanup is a function and must be called with parentheses: GPIO.cleanup()
🧠 Conceptual
advanced1:30remaining
Why use try-finally for GPIO cleanup?
Why is it recommended to use a try-finally block when working with GPIO pins in Python on Raspberry Pi?
Attempts:
2 left
💡 Hint
Think about what finally blocks guarantee in Python.
✗ Incorrect
The finally block always runs, so cleanup happens even if the program crashes or is interrupted.
❓ Predict Output
expert2:30remaining
What is the output of this GPIO cleanup signal handler code?
This Python code sets a signal handler to clean up GPIO on Ctrl+C. What will be printed when the user presses Ctrl+C?
Raspberry Pi
import RPi.GPIO as GPIO import signal import sys GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.OUT) GPIO.output(22, GPIO.HIGH) print("LED ON") def cleanup_handler(sig, frame): GPIO.cleanup() print("Cleaned up and exiting") sys.exit(0) signal.signal(signal.SIGINT, cleanup_handler) print("Press Ctrl+C to exit") while True: pass
Attempts:
2 left
💡 Hint
Consider the order of print statements and when the signal handler runs.
✗ Incorrect
The program prints 'LED ON' then 'Press Ctrl+C to exit'. When Ctrl+C is pressed, the handler prints 'Cleaned up and exiting' before exiting.