这是我第一次尝试在面包板上编写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()
答案 0 :(得分:1)
我找到了解决方案。使用代码here解决了我的问题。
如果您喜欢我,并在使用GPIO.add_event_detect时获取随机重复按钮事件,请尝试使用链接代码。
答案 1 :(得分:0)
尝试在事件检测调用中添加一个防抖动值。单位是毫秒。
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=Light, bouncetime = 250)