0
0
Raspberry Piprogramming~5 mins

GPIO cleanup on exit in Raspberry Pi

Choose your learning style9 modes available
Introduction

Cleaning up GPIO pins when your program ends helps avoid errors and keeps the pins ready for the next use.

When your Raspberry Pi program uses GPIO pins to control LEDs or buttons.
Before you stop or restart your program that controls hardware pins.
To prevent warnings or errors if you run your GPIO program multiple times.
When you want to make sure pins are set back to a safe state after your program finishes.
Syntax
Raspberry Pi
import RPi.GPIO as GPIO

# Setup pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Your code here

# Cleanup pins when done
GPIO.cleanup()

GPIO.cleanup() resets all used GPIO pins to input mode.

Call GPIO.cleanup() at the end of your program or when exiting.

Examples
Turn on an LED connected to pin 18, then clean up the pins after.
Raspberry Pi
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

GPIO.output(18, GPIO.HIGH)

GPIO.cleanup()
Turn on pin 23 for 2 seconds, then always clean up even if interrupted.
Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)

try:
    GPIO.output(23, GPIO.HIGH)
    time.sleep(2)
finally:
    GPIO.cleanup()
Sample Program

This program turns on an LED on pin 24 for 3 seconds, then turns it off and cleans up the GPIO pins safely.

Raspberry Pi
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.OUT)

try:
    print('LED on pin 24 is ON')
    GPIO.output(24, GPIO.HIGH)
    time.sleep(3)
    print('LED on pin 24 is OFF')
    GPIO.output(24, GPIO.LOW)
finally:
    GPIO.cleanup()
    print('GPIO cleanup done')
OutputSuccess
Important Notes

Always use try...finally or similar to ensure GPIO.cleanup() runs even if your program crashes.

Cleaning up prevents warnings like "This channel is already in use" when you rerun your program.

Summary

Use GPIO.cleanup() to reset pins when your program ends.

Call cleanup inside finally to run it no matter what.

This keeps your Raspberry Pi GPIO pins safe and ready for next use.