Recall & Review
beginner
What is the purpose of calling
GPIO.cleanup() in a Raspberry Pi program?It resets all the GPIO pins used by the program back to their default state, preventing warnings or errors in future runs and avoiding unintended behavior.
Click to reveal answer
beginner
When should you call
GPIO.cleanup() in your Raspberry Pi script?You should call it at the end of your program or when your program exits, including when interrupted by the user, to ensure pins are properly reset.
Click to reveal answer
intermediate
How can you ensure
GPIO.cleanup() runs even if the program is stopped with Ctrl+C?Use a try-except block to catch
KeyboardInterrupt and call GPIO.cleanup() in the except block or use a finally block to always run cleanup.Click to reveal answer
beginner
What happens if you don't call
GPIO.cleanup() before your program exits?GPIO pins may remain set as inputs or outputs, causing warnings on next run or unexpected hardware behavior, like LEDs staying on or motors running.
Click to reveal answer
beginner
Show a simple Python code snippet that safely cleans up GPIO pins on program exit.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
try:
GPIO.output(18, GPIO.HIGH)
time.sleep(2)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()Click to reveal answer
Why is it important to call
GPIO.cleanup() in a Raspberry Pi program?✗ Incorrect
Calling GPIO.cleanup() resets the pins to avoid warnings and unintended behavior.
Which Python statement ensures
GPIO.cleanup() runs even if the program is interrupted by Ctrl+C?✗ Incorrect
A try-except block catching KeyboardInterrupt allows cleanup code to run on interruption.
What could happen if you forget to call
GPIO.cleanup() before your program exits?✗ Incorrect
Pins may remain set, causing warnings or hardware to stay powered.
Where is the best place to put
GPIO.cleanup() in your code?✗ Incorrect
A finally block runs no matter what, ensuring cleanup always happens.
What does
GPIO.cleanup() do to the pins?✗ Incorrect
Cleanup resets pins to input mode and releases resources.
Explain why and how you should use GPIO.cleanup() in a Raspberry Pi program.
Think about what happens to pins after your program stops.
You got /4 concepts.
Describe a simple Python code structure that ensures GPIO pins are cleaned up even if the user stops the program with Ctrl+C.
Use try, except, and finally keywords.
You got /4 concepts.