📖 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
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
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
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
Hint
Use print("GPIO cleanup done") to show the message after cleanup.
Practice
(1/5)
1. Why is it important to call GPIO.cleanup() at the end of a Raspberry Pi GPIO program?
easy
A. It resets the GPIO pins to a safe state for future use.
B. It speeds up the program execution.
C. It increases the voltage output of the pins.
D. It disables the Raspberry Pi's network connection.
Solution
Step 1: Understand GPIO pin states
GPIO pins can remain set as input or output after a program ends, which may cause issues.
Step 2: Purpose of GPIO.cleanup()
Calling GPIO.cleanup() resets all pins to their default safe state, preventing conflicts in future programs.
Final Answer:
It resets the GPIO pins to a safe state for future use. -> Option A
Quick Check:
GPIO.cleanup() resets pins = B [OK]
Hint: Always reset pins with GPIO.cleanup() after use [OK]
Common Mistakes:
Thinking cleanup speeds up code
Believing cleanup changes voltage
Confusing cleanup with network settings
2. Which of the following is the correct way to ensure GPIO.cleanup() runs even if your program encounters an error?
easy
A. Place GPIO.cleanup() inside a try block only.
B. Place GPIO.cleanup() inside a finally block.
C. Call GPIO.cleanup() before setting up pins.
D. Call GPIO.cleanup() only if no errors occur.
Solution
Step 1: Understand try-finally structure
The finally block runs no matter what, even if errors happen.
Step 2: Place cleanup in finally
Putting GPIO.cleanup() in finally ensures pins reset even on exceptions.
Final Answer:
Place GPIO.cleanup() inside a finally block. -> Option B
Quick Check:
Cleanup in finally = A [OK]
Hint: Use finally block to always run cleanup [OK]
Common Mistakes:
Putting cleanup only in try block
Calling cleanup before setup
Skipping cleanup on errors
3. What will be the output of this code snippet if an error occurs during the loop?
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
try:
for i in range(3):
if i == 1:
raise Exception('Error!')
GPIO.output(18, GPIO.HIGH)
finally:
GPIO.cleanup()
print('Program ended')
medium
A. Program ended
B. GPIO pins remain set high
C. No output, program hangs
D. Exception: Error!
Solution
Step 1: Analyze try block with error
The loop raises an exception at i=1, but the finally block still runs.
Step 2: Effect of finally block
GPIO.cleanup() runs regardless, resetting pins, but since there is no except block, the exception propagates after finally, so print('Program ended') does not execute. The output is the exception message.
Final Answer:
Exception: Error! -> Option D
Quick Check:
finally runs cleanup, exception prints = B [OK]
Hint: finally block runs even on errors [OK]
Common Mistakes:
Thinking 'Program ended' prints on error
Thinking pins stay set after error
Ignoring finally block execution
4. Identify the error in this code that prevents GPIO pins from being cleaned up properly:
A. Missing parentheses after GPIO.cleanup in finally block.
B. GPIO.setup should be called after GPIO.cleanup.
C. GPIO.output should be inside except block.
D. No try-except block needed for GPIO.
Solution
Step 1: Check finally block syntax
The code uses GPIO.cleanup without parentheses, so cleanup is not called.
Step 2: Effect of missing parentheses
Without parentheses, cleanup is a reference, not a function call, so pins are not reset.
Final Answer:
Missing parentheses after GPIO.cleanup in finally block. -> Option A
Quick Check:
Call cleanup with () = D [OK]
Hint: Always add () to call GPIO.cleanup() [OK]
Common Mistakes:
Forgetting parentheses on cleanup
Calling setup after cleanup
Misplacing GPIO.output inside except
5. You wrote a program controlling multiple GPIO pins with different modes. How should you structure your code to ensure all pins reset properly even if your program crashes unexpectedly?
hard
A. Use GPIO.cleanup() inside except block only.
B. Call GPIO.cleanup() only at the very start of the program.
C. Place all GPIO setup and output calls inside a try block, and call GPIO.cleanup() in a finally block.
D. Do not use GPIO.cleanup() to avoid resetting pins.
Solution
Step 1: Organize GPIO code with try-finally
Put all GPIO setup and control inside try to catch errors and ensure cleanup.
Step 2: Use finally block for cleanup
Call GPIO.cleanup() in finally so it runs no matter what, resetting all pins safely.
Final Answer:
Place all GPIO setup and output calls inside a try block, and call GPIO.cleanup() in a finally block. -> Option C
Quick Check:
try-finally with cleanup = C [OK]
Hint: Use try-finally to guarantee cleanup on exit [OK]
Common Mistakes:
Calling cleanup only at start
Skipping cleanup on errors
Avoiding cleanup to keep pins set
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.