我正在树莓派3上编写python代码。我正在输入通道21上注册一个事件,以检查水分检测。我收到此错误运行时错误:无法添加边缘检测。 我的代码是:
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
filehandle = open("output.txt", "w") or die ("Could not write out")
if GPIO.input(channel) == 1:
print ("Water Detected!")
filehandle.write("1")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
filehandle.write("0")
GPIO.output(led_output, GPIO.HIGH)
filehandle.close()
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
while True:
time.sleep(5)
答案 0 :(得分:0)
当我重新启动Raspberry并运行您的代码时,它运行完美。 仅在终止进程或CTRL-C键盘中断并再次运行它之后,才会出现问题/错误。我认为这与以下事实有关:您没有正确清理就退出程序。 如果您使用CTRL-C退出运行程序,并获得下面的代码,则在其中包含了 GPIO.cleanup(), 但是...不幸的是,这并不能解决您只是杀死正在运行的程序的情况...在那种情况下,您仍然需要重新启动。 因此,还有改进的空间。 请再次重新插入您自己的文件管理命令。
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
if GPIO.input(channel) == 1:
print ("Water Detected!")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
GPIO.output(led_output, GPIO.HIGH)
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
try:
while True:
#main loop here with some (dummy) code
eg_set_a_dummy_variable = 0
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print ("Program interrupted by CTRL-C")
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:
# this ensures a clean exit and prevents your
# error "Runtime error:Failed to add edge detection"
# in case you run your code for the second time after a break
GPIO.cleanup()
# credits to:
# https://raspi.tv/2013/rpi-gpio-basics-3-how-to-exit-gpio-programs-cleanly-avoid-warnings-and-protect-your-pi
答案 1 :(得分:0)
这不是一个很干净的解决方案,但是您也可以在脚本的开头调用GPIO.cleanup()
,以防万一您的进程在之前被杀死而没有调用GPIO.cleanup()
。