繁体   English   中英

Raspberry Pi - Python 多个引脚的 GPIO 上升事件触发器

[英]Raspberry Pi - Python GPIO Rising-Event triggers for multiple Pins

在我的 Python 脚本中,我试图在按下特定按钮时调用 function(实际上我有 5 个不同的按钮,每个按钮连接到 3,3V,另一端连接到 GPIO 引脚)。 当我读取通过轮询(每 01 秒)连接到按钮的引脚值时,它工作得很好 但我想对GPIO.RISING 事件做出反应,而不是手动轮询。 我的问题来了:设置中断/事件后,按下一个按钮会触发多个事件 例如,按下 button1 也会触发连接到 button2 和 button3 的事件处理程序。

难道我做错了什么?

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")

现在,按下连接到 pin1 的按钮会打印“9 8 26”。 我错过了什么?

你有原理图可以分享吗?

此外,可能不是问题,但通常您不想在 ISR 中执行任何时间密集型任务或中断服务例程。 我会推荐这个修改后的代码来判断性能:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM