It seems to me that when one adds and event detection, then removes it and the adds it again, something strange happen: 1) an event is removed to the "detection list"; 2) the event happens; 3) The event is added to the detection list; Result) The callback function is called immediately after 3) even if the event occurred while it was not detected
My setup is the following:
I want my RPI to be a door guard, in particular
My code is the following
import RPi.GPIO as GPIO
from threading import Event
import signal
import sys
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.OUT, initial=0)
GPIO.setup(17, GPIO.OUT, initial=1)
STATUS = False
#When a door event occour:
def door(channel):
if GPIO.input(23):
print("The door has been opened!")
else:
print("The door has been closed!")
#When one pushes the button to toggle the sysyem
def toggle(channel):
global STATUS
if STATUS:
GPIO.output(17,1)
GPIO.output(18,0)
GPIO.remove_event_detect(23)
STATUS = False
else:
GPIO.output(18,1)
GPIO.output(17,0)
GPIO.add_event_detect(23, GPIO.BOTH, callback=door, bouncetime=300)
STATUS = True
GPIO.add_event_detect(24, GPIO.FALLING, callback=toggle, bouncetime=300)
#Cleanup function to gently close the system
def cleanup(signum, frame):
GPIO.cleanup()
sys.exit(0)
#to handle signals
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)
#Wait forever
Event().wait()
In particular, when one activate the system, an event detection is added both if the door is opened or closed. When one deactivate the system the detection of the event is removed
The Problem
I have the following situation that I cannot understand:
Immediately after that I get an event "The door has been opened!". What I do not understand is my door has been opened before I armed the system. It seems that when I add the detection of the event again the RPi.GPIO remembers what happened when the detection was removed. The funny is that the problem is not symmetric: if I exchanged opening and closing events in the previous list, I do not get the message "The door has been closed!"
Where am I wrong? Is there a way to "flush" the events while they are not added to the interrupt list?