while conditions not meeting in python
-
21-12-2019 - |
Question
Well, I'm trying to develop a home alarm which takes pictures according to the feedback received from a PIR module (using raspberry pi and its GPIOs).
The problem is the following. When the PIr is triggered, takes 5 pics, then goes to a function that remains checking for another trigger during the next 5 seconds OR until it is triggered again.
It only goes out of the while in case the 5 seconds have passed (time.time() < start + secs) and no movement is detected (Curren_State remains == 0)
Code block that I'm having trouble with:
#secs is received as a parameter (let's say the integer 5)
while time.time() < start + secs or not Current_State==True:
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1:
takePics(3)
THE PROBLEM: When I make this condition (without the OR):
while time.time() < start + secs:
#CODE
The script seems to act as normal: if the 5 seconds have passed it goes out. But if to the while condition I add (*or not Current_State==True*) it just doesn't attend the first condition since I display in every loop the comparison of time.time() and start + secs and I see that the first is bigger than the second one and still keeps executing the while.
So I'm still developing the code but the code is, more or less something like this. In case the following code is not well summed up: http://pastebin.com/0xP4Le1U
# Import required Python libraries
# Here I define GPIO stuff
# Photo dimensions and rotation
# global variables
Current_State=0
Previous_State=0
def takePics(nPics):
#Here I take pics
def reCheck:
global Current_State, alert
alert=0
start = time.time()
Current_State = 0
while time.time() < start + secs or not Current_State==True:
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1:
takePics(3)
#If there's no movement, this alert remains =0
#and will exit the "while" from which it was called
alert=1
#Here I have more functions like sendEmail and so on
def main():
#main code
while True:
#SOME CODE
if Current_State==1 and Previous_State==0:
print "----> Motion detected!"
Previous_State = 1
alert=1
#sendMail()
switchLightON() # Switch on the light using the relay
takePics(5)
while alert==1:
reCheck(4) # we check again in case movement was detected in reCheck
if __name__ == "__main__":
main()
Solution
Change or
to and
. Optionally, consider simplifying not Current_State==True
to Current_State is not True
or just not Current_State
if Current_State
is a boolean.
while time.time() < start + secs and Current_State is not True:
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1:
takePics(3)
That will loop until either secs
seconds have passed, or Current_State stops being true. The trick is that while only stops when it's condition is false. or
is false only if both conditions are false, and
is false if either condition is false.