HOW to Use PIR Motion Sensor on Raspberry Pi with ESP32
Overview
In this kit, there is a Keyestudio PIR motion sensor, which mainly uses an RE200B-P sensor elements. It is a human body pyroelectric motion sensor based on pyroelectric effect, which can detect infrared rays emitted by humans or animals, and the Fresnel lens can make the sensor’s detection range farther and wider.
In the experiment, we determine if there is someone moving nearby by reading the high and low levels of the S terminal on the module. The detected results will be displayed on the Shell.
Working Principle
The upper left part is voltage conversion(VCC to 3.3V). The working voltage of sensors we use is 3.3V, therefore we can’t use 5V directly. The voltage conversion circuit is needed.
When no person is detected or no infrared signal is received, and pin 1 of the sensor outputs low level. At this time, the LED on the module will light up and the MOS tube Q1 will be connected and the signal terminal S will detect Low levels.
When one is detected or an infrared signal is received, and pin 1 of the sensor outputs a high level. Then LED on the module will go off, the MOS tube Q1 is disconnected and the signal terminal S will detect high levels.
Required Components
|
|
|
---|---|---|
ESP32 Board*1 |
ESP32 Expansion Board*1 |
Keyestudio DIY PIR Motion Sensor*1 |
|
|
|
3P Dupont Wire*1 |
Micro USB Cable*1 |
|
Connection Diagram
Test Code
//*************************************************************************************
/*
* Filename : PIR motion
* Description : Reading the value of the human body infrared sensor
* Auther : http://www.keyestudio.com
*/
int val = 0;
int pirPin = 15; //The pin of PIR motion sensor is defined as GPIO15
void setup() {
Serial.begin(9600); //Set baud rate to 9600
pinMode(pirPin, INPUT); //Set the sensor to input mode
}
void loop() {
val = digitalRead(pirPin); //Read the sensor value
Serial.print(val);//Print val value
if (val == 1) {//There is movement nearby, output high level
Serial.print(" ");
Serial.println("Some body is in this area!");
delay(100);
}
else {//If no movement nearby, output low level
Serial.print(" ");
Serial.println("No one!");
delay(100);
}
}
//*************************************************************************************
Test Result
Connect the wires according to the experimental wiring diagram, compile and upload the code to the ESP32. After uploading successfully, we will use a USB cable to power on, open the serial monitor and set the baud rate to 9600. We need to press the reset button on the ESP32, then the serial monitor will display the corresponding data and characters.
When the sensor detects someone nearby, value is 1, the LED will go off and the monitor will show “1 Somebody is in this area!”. In contrast, the value is 0, the LED will go up and “0 No one!” will be shown.