2016-06-11 91 views
0

我目前有幾個槓桿型關閉開關,我希望打印狀態,只要它獨立開關所有其他開關。Python GPIO add_event_detect每個狀態單獨

到目前爲止,我已經走到這一步:

import RPi.GPIO as GPIO 
from time import sleep 

GPIO.setmode(GPIO.BCM) 

GPIO.setup(7, GPIO.IN) # switch 2 
GPIO.setup(11, GPIO.IN) # switch 3 

def print_func(pin): 
     if GPIO.input(7) == 0: 
       print "switch 2 on" 
     elif GPIO.input(7) == 1: 
       print "switch 2 off" 
     elif GPIO.input(11) == 0: 
       print "switch 3 on" 
     elif GPIO.input(11) == 1: 
       print "switch 3 off" 


GPIO.add_event_detect(7, GPIO.BOTH, callback=print_func, bouncetime=300) 
GPIO.add_event_detect(11, GPIO.BOTH, callback=print_func, bouncetime=300) 

while True: 
     sleep(1) 

然而,這並不讓我在任何地方。我無法弄清楚如何剛纔提到的槓桿只是移動的狀態,沒有通過循環提及每個人的狀態。

任何幫助將非常感謝!

回答

1

我現在沒有一個覆盆子pi,所以我不能測試這個,但我很確定以下是你需要的。

lever_num_by_pin = [7: 2, 11: 3] 

def printOn(pin): 
    print "switch", lever_num_by_pin[pin], "on" 

def printOff(pin): 
    print "switch", lever_num_by_pin[pin], "off" 

for pin in lever_num_by_pin: 
    GPIO.add_event_detect(pin, GPIO.RISING, callback=printOn, bouncetime=300) 
    GPIO.add_event_detect(pin, GPIO.FALLING, callback=printOff, bouncetime=300) 

回調函數被調用時使用了他們接收到的輸入信道的參數。我們可以使用它來根據引腳字典來選擇打印杆號。此外,我們可以使用該字典的鍵作爲遍歷所有帶槓桿的引腳的方法,並在每個引腳上附加上升和下降事件。瑞星正在開啓,並且下降正在關閉。