2

I'm trying to get my raspberry pi to detect motion using the IR sensor, and then turn on an LED for 5 seconds while still polling the IR sensor every 0.5 seconds. Here is my code so far, but it waits for the LED to turn off before checking the IR sensor again...

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 18
GPIO.setup(PIR_PIN, GPIO.IN)
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
def light():
    GPIO.output(LED_PIN, GPIO.input(PIR_PIN))
    time.sleep(5)
    GPIO.output(LED_PIN, False)
try:
   while True:
     if GPIO.input(PIR_PIN):
       print("Motion Detected!")
       light()
     time.sleep(0.5)
except KeyboardInterrupt:
   GPIO.cleanup()
1
  • 1
    Use multi-threads Commented Jul 18, 2017 at 15:49

1 Answer 1

3

That is exactly the correct behavior based on your code. In order for it not to block on the light() def, you can't have blocking statements like time.sleep.

One way to fix this is with threading:

from threading import Thread
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
PIR_PIN = 18
GPIO.setup(PIR_PIN, GPIO.IN)
LED_PIN = 17
GPIO.setup(LED_PIN, GPIO.OUT)
def light():
    GPIO.output(LED_PIN, GPIO.input(PIR_PIN))
    time.sleep(5)
    GPIO.output(LED_PIN, False)
try:
   while True:
     if GPIO.input(PIR_PIN):
       print("Motion Detected!")
       t = Thread(target=light) # Create thread
       t.start() # Start thread
     time.sleep(0.5)
except KeyboardInterrupt:
   GPIO.cleanup()

Threading allows you to run multiple things at once in your program. Although, this now opens up another can of worms where you need thread synchronization.

I would strongly suggest further reading on multi threading with python before implementing the above code, threading is very dangerous if done incorrectly.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks good! Will I have to call t.stop() in the light function?
Nope, you once it's done, it's done. Stopping a thread externally is generally a bad idea, you should let a thread run it's course and handle stopping itself
Ok - works great! Is there a way to restart the thread (or I guess rather the sleep timer) if motion is detected again while the light is on?

Your Answer

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.