python-3.x - 使 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)
有没有人有办法解决吗?
解决方案
这是因为 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
推荐阅读
- xml - 在 XML 中单独转义 &,但忽略 &
- excel - 如何使函数递归
- python - 没有任何游戏库的 Python 国际象棋?
- javascript - Chrome 扩展中弹出的错误 file_not_found
- postgresql - PostgreSQL 中是否有替代临时表的方法来保存和操作结果集?
- angular - 如何修复菜单中的 *ngIf 语句?
- inno-setup - 有条件地在 Inno Setup 中包含文件夹
- azure - B2C 令牌未能授予对 AAD 安全 API 的访问权限
- microsoft-graph-api - Microsoft-Graph:创建团队选项卡不起作用
- javascript - 映射对象内的映射对象