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()
  • "Quite broken" is a bit of stretch but it's fixed. – Evan Lalo Sep 24 '17 at 18:10
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..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.