RPi.GPIO.wait_for_edge(4, GPIO.FALLING) 检测按钮的按下和释放

RPi.GPIO.wait_for_edge(4, GPIO.FALLING) detects both press and release of button

我已经阅读了 RPi.GPIO 的文档,并搜索了 Google 以及 SO,但无法完全找到可能是一个非常愚蠢的问题的解决方案。我试图只检测按下按钮的边缘。但无论我指定寻找 "falling" 还是 "rising" 边缘,Pi 都会在按下和释放我的按钮时执行命令。有时它会多次执行代码。我的代码:

import RPi.GPIO as GPIO

buttonPin = 4                 # this is the pin for the button
GPIO.setmode(GPIO.BCM)                 # pinmode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)                 #setting up my pin to be input w/ pullup resistor

if __name__ == '__main__':
    while True:                 # loop
        GPIO.wait_for_edge(buttonPin,GPIO.RISING)                 # looking for a rising edge
        print('Edge detected')                 # this happens regardless of my button being pressed or released

很确定我在这里遗漏了一些基本的东西,非常感谢任何帮助。

您的代码基本没问题,但您需要一些硬件知识...

对于普通的开关和按钮,有一种东西叫做抖动。

一种解决方案是在短时间(通常是几毫秒)后检查按钮状态,并根据延迟的结果采取行动。

您可以使用参数 bouncetime 以编程方式解决它,但是,您必须使用

GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback, bouncetime=200)

GPIO.add_event_callback(channel, my_callback, bouncetime=200)

而不是GPIO.wait_for_edge(channel,GPIO.RISING)

或使用其他硬件:在您的开关上添加一个 0.1uF 电容器,

或者您可以结合使用两者。

Documentation

中的更多内容

和平