RuntimeWarnings with GPIO.setup and GPIO.cleanup not work with KeyboardInterrupt

Denis0189 picture Denis0189 · May 15, 2014 · Viewed 44.5k times · Source

I have a problem with my code working with raspberry pi. I just started with python so i need some help.

This is the code:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

led1=22
led2=17

GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)

def blink():
    GPIO.output(led1, 1)
    time.sleep(1)
    GPIO.output(led1, 0)

    GPIO.output(led2, 1)
    time.sleep(1)
    GPIO.output(led2, 0)

while(blink):
    blink()

try:
    main()
except KeyboardInterrupt:
    GPIO.cleanup()

when I run this error appear in the console:

RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. GPIO.setup(led1, GPIO.OUT) and:

RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings. GPIO.setup(led2, GPIO.OUT)

If I understand correctly the command GPIO.cleanup() should reset all pin of GPIO port and turn off the led.

but this in not happening in fact one of the led remain on.

How can change my code to resolve this issue?

Answer

Peter Varo picture Peter Varo · May 15, 2014

Here is a little help, how to effectively separate your functions, and make them more general. Although this is a working Python script I provided, I didn't tested it on my raspi, but I think it will work -- anyway, let me know if there were any problems!

import RPi.GPIO as GPIO
import time

# Module level constants
LED1 = 22
LED2 = 17

# Sets up pins as outputs
def setup(*leds):
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    for led in leds:
        GPIO.setup(led, GPIO.OUT)
        GPIO.output(led, GPIO.LOW)

# Turn on and off the leds
def blink(*leds):
    # Blink all leds passed
    for led in leds:
        GPIO.output(led, GPIO.HIGH)
        time.sleep(1)
        GPIO.output(led, GPIO.LOW)

if __name__ == '__main__':
    # Setup leds
    setup(LED1, LED2)
    # Run blinking forever
    try:
        while True:
            blink(LED1, LED2)
    # Stop on Ctrl+C and clean up
    except KeyboardInterrupt:
        GPIO.cleanup()

A friendly recommendation:

There is a dedicated Raspberry Pi StackExchange site too: https://raspberrypi.stackexchange.com/