我正在尝试计算从按下按钮开始到按下 GPIO 按钮结束的时间(以便区分长按和短按)。我想使用回调来立即按下按钮而不进行轮询。这是我首先尝试的:
import RPi.GPIO as GPIO
import time
def my_callback(channel):
start = time.time()
GPIO.add_event_detect(25, GPIO.FALLING)
end = time.time()
elapsed = end - start
print(elapsed)
GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
#while other stuff is running
Run Code Online (Sandbox Code Playgroud)
运行这个程序时我得到:
RunTimeError:已为此 GPIO 通道启用冲突边沿检测。
因为我无法对我尝试过的两者进行轮询:
def my_callback(channel):
GPIO.remove.event.detect(25)
start = time.time()
GPIO.add_event_detect(25, GPIO.FALLING)
end = time.time()
elapsed = end - start
print(elapsed)
GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback)
Run Code Online (Sandbox Code Playgroud)
这有效过一次,但不可重复,因为我正在删除事件检测并重新定义它。因此我尝试在回调中恢复事件检测:
def my_callback(channel):
GPIO.remove.event.detect(25)
start = time.time()
GPIO.add_event_detect(25, GPIO.FALLING)
end = time.time()
elapsed = end - start
print(elapsed)
GPIO.remove.event.detect(25)
GPIO.add_event_detect(25, GPIO.RISING, callback=my_callback) …Run Code Online (Sandbox Code Playgroud)