Wykrywanie ruchu z Raspberry Pi and HC-SR501

Motion detection with Raspberry Pi


The example shows how we can detect motion using the PIR sensor in combination with a Raspberry Pi.


In this example we used the following elements:


Connect the sensor with a RaspberryPi:

You need to connect both devices at the table


GPIO Raspberry PiPIR sensor




Circuit connect PIR sensor with the Raspberry Pi.


In order to use GPIO pins in the Raspberry we need a library that permits us to do it. To this end, we use wiringPi. Description how to download and install find here. Simply copy the following command. In the end, to validate the installation:


  • gpio readall

After this command we should see the following table:



Now we will write a simple program. Create a file pir.cpp


  • nano pir.cpp


The file should contain the following programs:


using namespace std; 

int sensor = 1; //GPIO1 pin associated with the signal from the sensor 

int main(void) 
 pinMode(sensor, INPUT); //adjustment the contact of the Raspberry as the entrance 

 cout<<endl<<"---- TEST MOTION SENSOR ----"<<endl; 

 int movement = digitalRead(sensor); //read the value from the sensor 
 if(motion == HIGH) //display information on the monitor 
 { //high means motion detection, low - lack of movement 
 cout<<" MOTION DETECTED!"<<endl; 
 else {cout<<"no motion"<<endl;} 

 delay(200); //delay between consecutive readings 

Then save the changes to the file and close it. To compile the file you created, use the command:


  • g++ -Wall -o PIR.on pir.cpp -lwiringPi


The program

The program displays messages on the screen. When the sensor detects motion, to a Raspberry Pi is sent to a high status, and on the screen appears the message: "MOTION DETECTED!".


The program is run using the following command:


  • sudo ./PIR.on


The result of the program can be viewed on the monitor:



The screen of the monitor.