user5740843
user5740843

Reputation: 1620

Python GPIO add_event_detect each state individually

I currently have a few lever-type on off switch that I would like to have the status printed as soon as it switches on/off independantly off all the other switches.

So far, I have come this far:

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)

However, this doesn't get me anywhere. I can't figure out how to just mentioned the status of the lever that just move, without going through the loop mentioning the status for each one..

Any help would be really appreciated!

Upvotes: 0

Views: 2477

Answers (1)

define cindy const
define cindy const

Reputation: 632

I don't have a raspberry-pi on me right now so I can't test this, but I'm pretty sure the following is what you need.

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)

Callbacks are called with an argument of the channel they received input from. We can use this to selectively print out the lever number based on a dictionary of pins to number. Additionally, we can use this dictionary's keys as a way of iterating through all pins with levers and attach a rising and falling event on each. Rising is turning on, and falling is turning off.

Upvotes: 2

Related Questions