Reputation: 47
Below code is for a PIR sensor written in Python.
What it should do
When the sensor was activate the first time, it should wait for 10 second once and then keep printing "Intruder detected" until the sensor was = 0.
what is actually do
Rather than waiting 10s once, the code below wait ever 10s when the pir sensor was tigger.
Why is that?
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(11)
if i==0: #When output from motion sensor is LOW
print "No intruders",i
GPIO.output(3, 0) #Turn OFF LED
time.sleep(0.1)
elif i==1: #When output from motion sensor is HIGH
time.sleep(10) #This should be only run once when the pir sensor is trigger
print "Intruder detected",i
GPIO.output(3, 1) #Turn ON LED
time.sleep(0.1)
Upvotes: 0
Views: 363
Reputation: 51683
Simply remember if it was triggererd:
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) # Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) # LED output pin
wasTriggered = False # not yet triggered
while True:
i=GPIO.input(11)
if i == 0: # When output from motion sensor is LOW
print "No intruders",i
wasTriggered = False # reset trigger if True else does nothing
GPIO.output(3, 0) # Turn OFF LED
time.sleep(0.1)
elif i == 1: # When output from motion sensor is HIGH
if wasTriggered == False: # already triggered ?
time.sleep(10) # only run once when the pir sensor is trigger
print "Intruder detected",i
GPIO.output(3, 1) # Turn ON LED
wasTriggered = True # set was triggered
time.sleep(0.1)
This is creating a "memory" - it will only reset once the Sensor reports one 0
on pin 11. You might want to switch the "Led goes red + Output text" and the sleep around to make it more "snappy" - meaning it will react immediately to the sensor change and then pause for 10s instead of pausing for 10s and then switch the light & print text which would disconnect the "Act"->"React" sequence.
Upvotes: 1