0
0
Raspberry Piprogramming~30 mins

GPIO cleanup on exit in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
GPIO Cleanup on Exit
📖 Scenario: You are working on a Raspberry Pi project that controls an LED light using GPIO pins. To keep your Raspberry Pi safe and avoid warnings, you need to clean up the GPIO settings when your program finishes or is stopped.
🎯 Goal: Build a simple Python program that sets up a GPIO pin to control an LED, waits for a short time, and then cleans up the GPIO settings properly when the program exits.
📋 What You'll Learn
Create a GPIO setup for pin 18 as output
Add a delay to keep the LED on for 3 seconds
Use a try-finally block to ensure GPIO cleanup happens on exit
Print a message confirming cleanup
💡 Why This Matters
🌍 Real World
Cleaning up GPIO pins is important to avoid warnings and conflicts when running multiple Raspberry Pi programs that use GPIO.
💼 Career
Understanding GPIO cleanup is essential for hardware projects, embedded systems, and IoT jobs where safe resource management is critical.
Progress0 / 4 steps
1
Set up GPIO pin 18 as output
Import the RPi.GPIO module as GPIO. Set the GPIO mode to GPIO.BCM. Then create a variable called pin and set it to 18. Finally, set up pin as an output pin using GPIO.setup(pin, GPIO.OUT).
Raspberry Pi
Need a hint?

Remember to import the GPIO library and set the mode before setting up the pin.

2
Turn on the LED and wait 3 seconds
Use GPIO.output(pin, GPIO.HIGH) to turn on the LED connected to pin. Then import the time module and use time.sleep(3) to wait for 3 seconds.
Raspberry Pi
Need a hint?

Use GPIO.output to turn on the LED and time.sleep to pause the program.

3
Add try-finally block to clean up GPIO
Wrap the code that turns on the LED and waits inside a try block. Then add a finally block that calls GPIO.cleanup() to reset the GPIO pins.
Raspberry Pi
Need a hint?

The finally block runs no matter what, so it's perfect for cleanup.

4
Print confirmation after cleanup
After the GPIO.cleanup() call inside the finally block, add a print statement that outputs "GPIO cleanup done".
Raspberry Pi
Need a hint?

Use print("GPIO cleanup done") to show the message after cleanup.