1

I have a PIR motion sensor hooked up to an LED strip. When motion is detected, the lights turn on as expected. My problem is trying to get the lights to turn off only if there has not been any movement for a certain amount of time. If, however, there continues to be movement, the lights will stay on.

I tried doing this with time.sleep but it would shut off after the specified time even if movement was still being detected. I have looked at the API documentation here but I have not been able to figure it out.

Here's my code.

import RPi.GPIO as GPIO
import time
from gpiozero import MotionSensor
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
pir = MotionSensor(16)
pinList = [3]
for i in pinList: 
 GPIO.setup(i, GPIO.OUT) 
 GPIO.output(i, GPIO.HIGH)
try: 
 if pir.motion_detected: 
 GPIO.output(3, GPIO.LOW)
 print("On")
 time.sleep(7)
 GPIO.output(3, GPIO.HIGH)
except KeyboardInterrupt:
 GPIO.cleanup()
Stephen Rauch
2451 gold badge4 silver badges11 bronze badges
asked Sep 24, 2017 at 16:07
1
  • "Quite broken" is a bit of stretch but it's fixed. Commented Sep 24, 2017 at 18:10

1 Answer 1

1

I find the easiest way to construct these sorts of loops is to keep track of the event times separately from the logic to perform an action based on that time. Something like:

import time
last_motion = 0
while True:
 try:
 if pir.motion_detected:
 last_motion = time.time()
 if time.time() - last_motion <= 7:
 GPIO.output(3, GPIO.LOW)
 print("On")
 else:
 GPIO.output(3, GPIO.HIGH)
 print("Off")
 time.sleep(1)
 except KeyboardInterrupt:
 break

This could be optimized further to only perform the action on a change, but this should provide the basic functionality..

answered Sep 24, 2017 at 18:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.