Vadim Tabakman

Jump to bottom

HC-SR501 Motion Detection Sensor 

HC-SR501 Motion Detection Sensor

Yet another sensor to play with.  This time a Motion Detection sensor.  This has actually taken to me a different stage of my learning.  So far, I've been using Python code that polls the sensors to get data from.  But I realized that there must be a better way, because by polling, there's a change I'm missing out on events.  The thing I found was Triggers.

The sensor looks like this :

Kind of reminds of the room sensors you see in shops you walk into or even ones you might have at home with an alarm system.

Polling

#!/usr/bin/env python

import os
import RPi.GPIO as GPIO
import time

pin = 6

GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)

print "Press Ctrl+c to exit"
time.sleep(2)
print "Ready"

try:
   while True: 
      if (GPIO.input(pin)==1): 
         print "Motion Detected"
      time.sleep(1)
except KeyboardInterrupt: 
   print "Program Cancelled..." 
   GPIO.cleanup()

Trigger

#!/usr/bin/env python

 

import os
import RPi.GPIO as GPIO
import time

pin = 6

GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN)

print "Press Ctrl+c to exit"
time.sleep(2)
print "Ready"

def MOTION(pin):
   print "Motion Detected!"

try:
   GPIO.add_event_detect(pin, GPIO.RISING, callback=MOTION)
   while True: 
      time.sleep(100)
except KeyboardInterrupt: 
   print "Program Cancelled..." 
   GPIO.cleanup()

There's not a huge difference.  But it's all about the Callback function called MOTION.  It's registered by using the GPIO.add_event_detection function.  We are telling it that on that pin that the sensor is connected, when we get a Rising edge event, you need to call MOTION.

Not that hard right?  This is going to make for some interesting apps now that my app doesn't have to sit in a loop, constantly polling a sensor and when an event occurs, my code has to stop what it's doing to process it.  In this case, the Callback function MOTION would be called on another thread behind the scenes, and my app can continue on it's merry way.

If you want to check out the code, it's available in the download section.

Downloads

Download the HC-SR501Sensor scripts - this is zipped.  So unzip it when you want to run it.  To run it :

python HCSR501SensorPoll.py

or

python HCSR501SensorTrigger.py

Posted by Vadim Tabakman Tuesday, January 17, 2017 10:29:00 PM Categories: HC-SR501 Motion Detection Python Raspberry PI