2

I have several lever switches that represent scores. I want a single callback function when pressed that acts on the value of that lever. I have this working except it seems to call the function twice. This stops happening if I remove the second add_event_detect for the other channel

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def buttonPressed(value):
    print('Scored! %s'%value)
    print(time.time())

GPIO.add_event_detect(17, GPIO.FALLING, callback=lambda x: buttonPressed(50), bouncetime=2000)
GPIO.add_event_detect(27, GPIO.FALLING, callback=lambda x: buttonPressed(150), bouncetime=2000)

When I push the switch once on channel 17 I get outputted:

 Scored! 50
 1374739135.76
  Scored! 50
 1374739135.76

Note the extra space on the third line, not sure if that has any importance to the issue.

How can I make sure it only gets called once when the lever is pressed and why is adding the second add_event_detect causing the callback function to be fired?

  • and your question is? – lenik Jul 24 '13 at 21:12
  • sorry if it wasn't clear in the intro text, I've added it again at the end – Titan Jul 24 '13 at 21:21
1

I have had no idea what that lamda is supposed to do, but this is what I would use:

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def buttonPressed(channel):
    if channel==17:
        value=50
    elif channel==27:
        value=150
    print('Scored! %s'%value)
    print(time.time())

GPIO.add_event_detect(17, GPIO.FALLING, callback=buttonPressed, bouncetime=2000)
GPIO.add_event_detect(27, GPIO.FALLING, callback=buttonPressed, bouncetime=2000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.