Page 1 of 1

Function called twice at GPIO Event

Posted: Tue Jan 26, 2016 2:24 pm
by shibby
Hallo,

I have a small issue with my code.

Simple setup
With a normally open relais contact I pull GPIO pin 2 to ground.

With the relay, which I can operate remotely; I simulate a push button.
Sounds weird, but this way I don't have to wlak down to floors to test my code.

When I close the contact, the function ding_dong is called:

Code: Select all

from RPi import GPIO
import time

Event_Counter = 0

GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    
def ding_dong(event):
  	global Event_Counter
  	Event_Counter += 1
  	print Event_Counter, " events detected."
  	time.sleep(0.3)
  	# here I will put code that checks if GPIO pin 2 is still LOW
  	# need that to filter out the false trigger of GPIO pin 2
  	# due to power surges or EM pulses

GPIO.add_event_detect(2, GPIO.FALLING, ding_dong, bouncetime=250)

raw_input("Press Enter to quit program.\n\n>") 
GPIO.remove_event_detect(2)
GPIO.cleanup() 
What I can not figure out is, that the function is called twice when I close the contact.
When I reduce the time.sleep value to be lower than the bouncetime, the function is just called once when I close the contact.

Can anyone explain why that is?

What I also can not figure out is, that the finction is also called at 90% of the times I open the contact (riding edge on pin 2).
Any ideas?

Re: Function called twice at GPIO Event

Posted: Tue Jan 26, 2016 5:01 pm
by Davies
on your wiring do you have a pull down resistor in addition to the pud_down? I don't know for sure but could the rpi detect the difference between the falling edge of the internal pud and that of the external pull down?
ive used gpio.wait_for_edge before and found that within my project it detected the rising and falling of background gpio work, probably the small rise and fall of the 3v line. I ended up using the standard "If gpio" set up to avoid false positives within my project.

Re: Function called twice at GPIO Event

Posted: Tue Jan 26, 2016 5:03 pm
by paddyg
This is a problems with the add_event_detect() even with debounce. You need to put some code in the function so only one instance does anything at once - probably using a global (as a control token) and checking time. Search on this forum for peoples' thoughts..