1

In my Python script, I'm trying to call a function when a specific button is pressed (actually I have 5 different buttons, each connected to 3,3V and the other end to a GPIO-Pin). When I'm reading the value of the pins the buttons are connected to via polling (every .01 seconds) it works just fine. But I'd like to react to the GPIO.RISING event instead of polling manually. And here comes my problem: After setting up the interrupts/events, pressing one button results in multiple events triggered. E.g. pressing button1 also triggers the eventhandlers connected to button2 and button3.

Am I doing something wrong?

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")

now, pressing button connected to pin1 results in printing "9 8 26". What am i missing?

1
  • Did you ever get a solution? - I'm having exactly the same problem - doesn't matter which pin goes high all the callbacks fire. Commented Nov 14, 2021 at 13:58

1 Answer 1

0

Do you have a schematic to share?

Also, likely not the issue but in general you do not want to perform any time intensive tasks in your ISR or interrupt service routine. I would recommend this revised code to judge performance instead:

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")
Sign up to request clarification or add additional context in comments.

1 Comment

It lacks of serialization protection. I dunno how library is implemented, but it's (theoretically?) possible that foo() will be called in another thread.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.