Raspberry Pi and HC-SR501 motion sensor (PIR). Recording in the database and display the facts movement on WEB

Welcome to my blog! 🙂 Once we have carried out the connection of the sensor (HC-SR501) to Arduino. Today we’ll discuss how to implement a similar (and even more;)) with the Raspberry Pi.

Figure 1 – The exterior sensor HC-SR501

This sensor has 3 pins: +5V (power +), Ground and OUT (informative).

Connect the sensor in such a way


Numbering GPIO pins on the Raspberry Pi


Below is a Python-script for Raspberry Pi, which will read the motion sensor and displays, when a motion display it on your computer and display before switching on the red LED Raspberry Pi (GPIO 8). A fact of motion is written in the MySQL database, and the last ten entries displayed on the web page php-script. Important! can be used as an external hosting and database, and install a web server and database server on the same Raspberry Pi.In the database you need to create a table with two fields ( motion of type varchar (20) and datetime field of type datetime and do it right the primary key). Our records will be sorted by date so that php-script will extract the last 10 entries.


Extremely important! Python is very demanding to the correct tab! Be careful not to change the program code within the left of the code (paragraphs), or get a bunch of errors 😉

Type in the terminal
nano /usr/local/bin/motion.py
Then copy or type content of this Python-script

After making changes save the file (CTRL O + Enter) and close it (CTRL X).
Run our script in a terminal:
sudo python motion.py
Now, if everything is connected correctly, we will see information about the fact of motion in the terminal:


Plus our red LED lights up for 5 seconds, and the information that was recorded motion and the exact time written in the database. Stop script can be a combination of CTRL X.

Now consider the php-script that gets about 10 of the last movement of the facts and displays it all work well on the Web. Itself script HERE
The result of the script in Figure