gpt4 book ai didi

python - 按钮 GPIO.FALLING 事件被触发两次

转载 作者:行者123 更新时间:2023-11-28 18:30:39 26 4
gpt4 key购买 nike

这是我第一次尝试在面包板上编写 Raspberry Pi 和硬件按钮的代码。程序很简单,当检测到按下按钮时,打开面包板上的 LED 1 秒钟。我的代码似乎有效,但奇怪的是,每隔一段时间按下一个按钮就会触发回调函数两次。我是一个完全的编程菜鸟,所以我不确定问题是否出在我的代码上,或者硬件或按钮是否以某种方式实际上下降了两次。我希望这里有人可以帮助我解决这个问题。这是我的代码:

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time


LedPin = 11 # pin11 --- led
BtnPin = 12 # pin12 --- button

def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V)
GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def Light(ev=None):
print 'A button press was detected'
GPIO.output(LedPin, 0) # switch led status on
time.sleep(1)
GPIO.output(LedPin, 1) # switch led status off

def loop():
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light) # wait for Button Press (GPIO Falling)
while True:
pass # Don't do anything, sit forever

def destroy():
GPIO.output(LedPin, GPIO.HIGH) # led off
GPIO.cleanup() # Release resource

if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()

最佳答案

尝试为您的事件检测调用添加去抖动值。单位为毫秒。

GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light, bouncetime = 250) 

关于python - 按钮 GPIO.FALLING 事件被触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com