C and Python implementation for RaspberryPi to detect movement using PIR motion sensor (HC-SR501)
21 November 2014 By Bhavyanshu Parasher
Overview
I recently bought a motion detection sensor HC-SR501. First, we will see how to connect it to our raspberry pi and then we will run the C code which helps us detect motion. Once the movement has been detected, it will set LED to HIGH and play an audio (.wav) file. There are a lot of python implementations for it out there but if you are interested in specifically using C for this, then you have come to the right place.
Hardware
- Breadboard
- Jumper Wires
- 4.7K ohm resistor (If using +5 volt - PIN 2) else no resistor required, if using +3.3V (PIN 1). See diagram below.
- HC-SR501
- 3.5 mm jack speaker/headphones (Optional, if you want sound)
- Raspberry Pi (I am using model B revision 2)
We connect board pin number 1 (+3.3 V) to the VCC of the sensor, pin number 6 for GND and finally pin number 7 as data input from the sensor to raspberry pi. PIR sensors work by detecting a change in the infrared radiation level in the detection region. So when there is no movement, the digital out pin on the sensor will remain LOW but as soon as there is a movement in the detection range, it will go HIGH and our Raspberry Pi will be able to sense this change when we run our C program. Next we connect anode of LED to pin number 11 and cathode to GND. Look at the figure below to understand the connections. It may not be the best diagram ever but this is all I have for now.
The fun begins
Please make sure your connections are correct. If you are using some other pins then keep them in mind. You will have to change the #define SENSOR
and #define LED
macro in that case. The below given C program depends on bcm2835 library. It will not compile without it. First copy paste the contents of pir.c file or you can find the raw file here.
pir.c file :
You will have to install the library manually using
$ wget http://www.open.com.au/mikem/bcm2835/bcm2835-1.5.tar.gz
$ tar zxvf bcm2835-1.5.tar.gz
$ cd bcm2835-1.5
$ ./configure
$ make
$ sudo make check
$ sudo make install
and then compile the pir.c using
gcc pir.c -o pir -l bcm2835
To run it, use
sudo ./pir
It has to be run as root for it to be able to access hardware.
That’s all. Now move around the sensor. You will see LED is HIGH while you move and the .wav file also plays. Once you stand still, the LED will go off too. If there is an audio issue, take a look at this or post a comment below.
Now let us quickly go through python implementation as well. Raw File
pir.py file :
Run above using
sudo python pir.py
That’s all. Test it out and if you get stuck, just post in the comments below. I will help you out.
blog comments powered by Disqus