문제

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?

도움이 되었습니까?

해결책

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/

다른 팁

You don't seem to have included main in your question. However the problem may occur if the programs exits for some reason other than KeyboardInterrupt. It's better to free the resource in a finally block

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

You are calling main() function but it's not declared (defined), you are using while(blink). So You need to delete the "main()" and put the "Try" before your main function which is the while(blink) loop. Don't forget the proper tabs there.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top