[英]Raspberry Pi - Python GPIO Rising-Event triggers for multiple Pins
In my Python script, I'm trying to call a function when a specific button is pressed (actually I have 5 different buttons, each connected to 3,3V and the other end to a GPIO-Pin).在我的 Python 脚本中,我试图在按下特定按钮时调用 function(实际上我有 5 个不同的按钮,每个按钮连接到 3,3V,另一端连接到 GPIO 引脚)。 When I'm reading the value of the pins the buttons are connected to via polling (every.01 seconds) it works just fine .
当我读取通过轮询(每 01 秒)连接到按钮的引脚值时,它工作得很好。 But I'd like to react to the GPIO.RISING event instead of polling manually.
但我想对GPIO.RISING 事件做出反应,而不是手动轮询。 And here comes my problem: After setting up the interrupts/events, pressing one button results in multiple events triggered .
我的问题来了:设置中断/事件后,按下一个按钮会触发多个事件。 Eg pressing button1 also triggers the eventhandlers connected to button2 and button3.
例如,按下 button1 也会触发连接到 button2 和 button3 的事件处理程序。
Am I doing something wrong?难道我做错了什么?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
pin1 = 9
pin2 = 7
pin3 = 8
pin4 = 16
pin5 = 26
def foo(pin):
print(pin)
GPIO.setup(pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# same for pin3 - pin5
GPIO.add_event_detect(pin1, GPIO.RISING, callback=foo, bouncetime=200)
GPIO.add_event_detect(pin2, GPIO.RISING, callback=foo, bouncetime=200)
# same for pin3 - pin5
try:
while True:
time.sleep(0.01)
except KeyboardInterrupt:
print("end")
now, pressing button connected to pin1 results in printing "9 8 26".现在,按下连接到 pin1 的按钮会打印“9 8 26”。 What am i missing?
我错过了什么?
Do you have a schematic to share?你有原理图可以分享吗?
Also, likely not the issue but in general you do not want to perform any time intensive tasks in your ISR or interrupt service routine.此外,可能不是问题,但通常您不想在 ISR 中执行任何时间密集型任务或中断服务例程。 I would recommend this revised code to judge performance instead:
我会推荐这个修改后的代码来判断性能:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
pressed = None
pin1 = 9
pin2 = 7
pin3 = 8
pin4 = 16
pin5 = 26
def foo(pin):
global pressed
pressed = pin
GPIO.setup(pin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(pin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# same for pin3 - pin5
GPIO.add_event_detect(pin1, GPIO.RISING, callback=foo, bouncetime=200)
GPIO.add_event_detect(pin2, GPIO.RISING, callback=foo, bouncetime=200)
# same for pin3 - pin5
try:
while True:
if pressed:
print(pressed)
pressed = None
time.sleep(0.01)
except KeyboardInterrupt:
print("end")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.