Im using the Pi to control some relays, that in turn switch some light bulbs.

some code for clarification:

def do_work(job):
        duration = int(job.Duration)
        gpioPort = int(job.Port)
        logger.debug(f'Setting GPIO mode to BCM')
        GPIO.setup(gpioPort, GPIO.OUT)
        logger.info(f'Turning ON GPIO port {gpioPort} for a duration of {duration} seconds')
        GPIO.output(gpioPort, GPIO.HIGH)
        logger.info(f'Turning OFF GPIO port {gpioPort}')
        GPIO.output(gpioPort, GPIO.LOW)

    except Exception as e:
        logger.error("Unexpected error:" + str(e))
        logger.info(f'Cleaning up GPIO ports!')

So basically im using a certain pin number to drive the relaiy. once the light goes off by schedule, i want to call the cleanup(), though only for that specific pin. an the same time an second light bulb could still be on, so when i call the cleanup(), it clears all the pins, and not only the one i want to clean.

is there a other approach to this ?

Edit: I forgot to mention im using Python + RPi.GPIO module

2 Answers 2


See RPi.GPIO documentation.


At the end any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. Note that this will only clean up GPIO channels that your script has used. Note that GPIO.cleanup() also clears the pin numbering system in use.

To clean up at the end of your script:


It is possible that don't want to clean up every channel leaving some set up when your program exits. You can clean up individual channels, a list or a tuple of channels:


GPIO.cleanup( (channel1, channel2) )

GPIO.cleanup( [channel1, channel2] )

  • ah thanx! how could i have missed this bit of the doc.... thanx for pointing it out
    – Dante1986
    Jun 17, 2020 at 21:33

I would look to use the gpiozero module as that’s more powerful but saying that the cleanup function is designed to reset all pins as it’s the last thing you should do in your program NOT part way through.

Also the setting of the pin mode should only be executed once in your program.

Normally, you would ‘reset’ the output by putting a high or low voltage level on it depending on what the default state needs to be. So you would just use:

GPIO.output(gpioPort, GPIO.HIGH)


GPIO.output(gpioPort, GPIO.LOW)

to set the port to the value you need.

Remember overall, you should not leave pins in unknown states if the program errors. Trap possible fails everywhere and call a general tidy up routine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.