首页 > 解决方案 > 使 2 个 LED 闪烁的 python 程序出错

问题描述

LED 不闪烁,每次运行 python 程序时都会出现此错误。

blink.py:4: RuntimeWarning: 这个频道已经在使用中,继续。使用 GPIO.setwarnings(False) 禁用警告。GPIO.setup(16,GPIO.OUT)

blink.py:5: RuntimeWarning: 这个频道已经在使用中,继续。使用 GPIO.setwarnings(False) 禁用警告。GPIO.setup(18,GPIO.OUT)

我已经对该问题进行了一些研究,但没有一个解决方案有效

import RPi.GPIO as GPIO
import time 
GPIO.setmode(GPIO.BCM)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
while True: 
    GPIO.output(16, GPIO.HIGH)
    GPIO.output(18, GPIO.LOW)
    time.sleep(1)
    GPIO.output(16, GPIO.LOW)
    GPIO.output(18, GPIO.HIGH)
time.sleep(1)

有没有人有办法解决吗?

标签: python-3.xraspberry-pi3gpio

解决方案


这是因为 GPIO 引脚已在使用中。在此之前,他们是在另一个脚本中设置的吗?您应该在每次使用后执行 GPIO 清理。正如@Tommi 在他们的回答中提到的那样,try/except/finally 块对于事后触发清理很有用。这是一个演示此的示例,改编自此站点

import RPi.GPIO as GPIO
import time

# Consider calling GPIO.cleanup() first

GPIO.setmode(GPIO.BCM)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)

try:  
    # Your code here 
    while True: 
        GPIO.output(16, GPIO.HIGH)
        GPIO.output(18, GPIO.LOW)
        time.sleep(1)
        GPIO.output(16, GPIO.LOW)
        GPIO.output(18, GPIO.HIGH)
        time.sleep(1) # This line should be here so it is part of the while loop

except KeyboardInterrupt:  
    # Here you put any code you want to run before the program   
    # exits when you press CTRL+C  
    print("Keyboard interrupt")  

except:  
    # This catches ALL other exceptions including errors.  
    # You won't get any error messages for debugging  
    # so only use it once your code is working  
    print("Other error or exception occurred!")

finally:  
    GPIO.cleanup() # This ensures a clean exit  

推荐阅读