22

When running a program in Python, why would I want the cleanup command when using the GPIO's?

WineSoaked
  • 350
  • 2
  • 10
Human
  • 1,208
  • 4
  • 16
  • 35

3 Answers3

23

As mentioned in this article RPi.GPIO basics 3 – How to Exit GPIO programs cleanly, avoid warnings and protect your Pi, correct use of GPIO.cleanup(),

Correct use of GPIO.cleanup()

RPi.GPIO provides a built-in function GPIO.cleanup() to clean up all the ports you’ve used. But be very clear what this does. It only affects any ports you have set in the current program. It resets any ports you have used in this program back to input mode. This prevents damage from, say, a situation where you have a port set HIGH as an output and you accidentally connect it to GND (LOW), which would short-circuit the port and possibly fry it. Inputs can handle either 0V (LOW) or 3.3V (HIGH), so it’s safer to leave ports as inputs.

Hope it clears your doubt.

dhruvvyas90
  • 2,883
  • 3
  • 21
  • 33
5

You do not have to use the cleanup method.

As far as I am aware only the RPi.GPIO and RPIO.GPIO Python modules have a cleanup method. The cleanup method sets all the gpios you have used to be inputs and disables the internal pull-ups/downs for those gpios.

My pigpio Python module does not have a cleanup method, neither does the wiringPi2 Python module as far as I am aware.

joan
  • 71,852
  • 5
  • 76
  • 108
3

I have encountered a few problems using GPIO, mainly relating to trying to change modes and pin directions that have already been set in a previous session. For example, sometimes if I run a program that sets pins to output, and then I run a program that sets the same pins to input without restarting the pi, I get a bunch of warnings (such as "RunTimeWarning: This channel is already in use"). This is especially problematic when calling various GPIO related functions from a single program, as sometimes the program crashes.

Using the cleanup command either before or after changing GPIO settings gets rid of the warnings and allows code to run smoothly without any GPIO-settings warnings occurring.

Dave
  • 31
  • 1