【问题标题】:Raspberry Pi - Python GPIO Rising-Event triggers for multiple PinsRaspberry Pi - 多个引脚的 Python GPIO 上升事件触发器
【发布时间】:2021-03-07 14:50:05
【问题描述】:

在我的 Python 脚本中,我试图在按下 特定 按钮时调用一个函数(实际上我有 5 个不同的按钮,每个按钮连接到 3,3V,另一端连接到 GPIO -别针)。 当我读取引脚的值时,按钮连接到 通过轮询(每 0.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”。 我错过了什么?

【问题讨论】:

  • 您找到解决方案了吗? - 我遇到了完全相同的问题 - 无论哪个引脚变高,所有回调都会触发。

标签: python raspberry-pi gpio interrupt-handling


【解决方案1】:

你有原理图要分享吗?

另外,这可能不是问题,但通常您不希望在 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")

【讨论】:

  • 它缺乏序列化保护。我不知道库是如何实现的,但(理论上?)foo() 可能会在另一个线程中被调用。
猜你喜欢
  • 2013-04-15
  • 2013-07-15
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多