簡體   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