0
0
Raspberry Piprogramming~5 mins

GPIO cleanup on exit in Raspberry Pi - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ATo increase CPU usage
BTo speed up the program
CTo reset GPIO pins to a safe state
DTo install new libraries
Which Python statement ensures GPIO.cleanup() runs even if the program is interrupted by Ctrl+C?
AUsing a while loop
BUsing a try-except block catching KeyboardInterrupt
CUsing an if statement
DUsing a print statement
What could happen if you forget to call GPIO.cleanup() before your program exits?
AGPIO pins may stay active causing hardware issues
BThe program will run faster next time
CThe Raspberry Pi will shut down
DNothing happens
Where is the best place to put GPIO.cleanup() in your code?
AAt the start of the program
BIn a comment
CInside a print statement
DIn a finally block
What does GPIO.cleanup() do to the pins?
AResets them to input mode and frees resources
BTurns them all on
CChanges their voltage to 5V
DDisables the Raspberry Pi
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.