Python GPIO add_event_detect各个州

时间:2016-06-11 11:25:24

标签: python raspberry-pi gpio

我目前有一些杠杆式开关,我希望只要它打开/关闭所有其他开关就打开状态。

到目前为止,我已经走到了这一步:

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 个答案:

答案 0 :(得分:1)

我现在没有吃树莓派,所以我无法对此进行测试,但我非常确定您需要以下内容。

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)

使用从其接收输入的通道的参数调用回调。我们可以使用它来根据引脚字典来选择性地打印出杠杆编号。另外,我们可以使用这个字典的键作为一种用杠杆迭代所有引脚的方法,并在每个引脚上附加一个上升和下降事件。冉冉升起,堕落正在关闭。