Raspberry Pi motion detection
The example shows how we can detect movement using a PIR sensor in combination with Raspberry Pi.
The example uses the following elements:
Connecting the sensor with RaspberryPi:
Connect the two devices according to the table below
GPIO Raspberry Pi | PIR sensor |
---|---|
5 V | VCC |
GND | GND |
GPIO 1 |
OUT |
Diagram of connection between PIR sensor and Raspberry Pi.
Support
To use the GPIO pins in Raspberry we need a library that allows us to do so. For this we will use wiringPi. The description how to download and install it can be found here. Just copy the next commands. Finally, to check the installation:
-
gpio readall
After this command we should see the table below:
Now we will write a simple program. We create a pir.cpp file
-
nano pir.cpp
The file should contain the following program:
#include#include using namespace std; int sensor = 1; //pin GPIO1 connected to a sensor signal int main(void) { wiringPiSetup(); pinMode(sensor, INPUT); // setting the Raspberry pin as input cout<
Then save the changes to the file and close it. To compile the created file we use the command:
-
g++ -Wall -o pir.o pir.cpp -lwiringPi
Operation of the programme
The program displays messages on the screen. When the sensor detects movement, a high state is sent to the Raspberry Pi and a message appears on the screen: "MOTION DETECTED!"
The program starts with the following command:
-
sudo ./pir.o
The result of the program can be viewed on the monitor:
A screenshot of the monitor.