21

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

WineSoaked
  • 350
  • 2
  • 10
Human
  • 1,198
  • 4
  • 15
  • 35
  • As a side note, the wiringPi library used with C programs does not have a Cleanup() function. it appears that the GPIO.cleanup() is available because the python functionality keeps a log of changes in order to clean up those changes. See https://raspberrypi.stackexchange.com/questions/44807/wiringpi-cleanup-command – Richard Chambers Nov 24 '17 at 05:13

3 Answers3

22

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,853
  • 3
  • 19
  • 32
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,024
  • 5
  • 73
  • 106
  • What is the purpose of the cleanup command then? – Human Aug 13 '15 at 03:10
  • 1
    @Human I don't think there is much of a purpose, I'd have added such a method if I thought it was needed. dastaan in his answer has pointed to the reasoning used by the RPi.GPIO author. It may be more of a philisophical bent, I assume users have a reason for doing what they do or don't do. If they want to leave a gpio as an input after the program finishes they should set it as an input. – joan Aug 13 '15 at 07:39
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