GPIO按钮按下多次运行打印方法

时间:2018-01-20 02:37:09

标签: button raspberry-pi state gpio

使用raspberry pi 3读取GPIO按钮状态     ----------------------------------------------

问题:当我运行下面的代码并按下我的pi 附加的按钮时,它会多次打印“按钮已被按下”(有时,它可以打印它100次)

有谁知道为什么会这样?    在此先感谢您的合作

-----
code:
-----
 buttonPin = 17
    import RPi.GPIO as gpio
    gpio.setmode(gpio.BCM)
    gpio.setup(buttonPin, gpio.IN)
    count=0
    ButtonState=True    #means that the button is in the up position and has not yet been pressed.

    while True:
        input_value = gpio.input(17)
        if input_value == False:
            print('The button has been pressed...')
            print(count)

1 个答案:

答案 0 :(得分:0)

是的,您需要在print()之后添加延迟。您的脚本移动太快,第一次迭代后仍然按下开关。

轻松修复:

buttonPin = 17
import RPi.GPIO as gpio

#Import time library for delays
import time

gpio.setmode(gpio.BCM)
gpio.setup(buttonPin, gpio.IN)
count=0
ButtonState=True    #means that the button is in the up position and has not yet been pressed.

while True:
    input_value = gpio.input(17)
    if input_value == False:
        print('The button has been pressed...')
        print(count)

        #Add a debounce delay "time.sleep(duration)"
        time.sleep(0.5)

这意味着您的脚本在按下按钮后0.5秒才会继续,为按钮释放时间。