PIR motion sensor and Buzzer with ESP32

This project “PIR motion sensor and Buzzer with ESP32” showing how to interface the PIR sensor and buzzer with ESP32. This project is very useful to make our homes a “Smart home”. The PIR motion sensor detects the motion and the buzzer beeps according to the motion detects. So it is very helpful to prevent strangers to enter our homes and it provides safety.

PIR motion sensor and Buzzer with ESP32

A PIR sensor allows detecting motion of a body. The PIR indicates Pyroelectric Infrared or it also referred to as Passive Infrared Sensor. The working principle of the PIR sensor is the detection of infrared energy emitted by the moving body. The operation of the PIR sensor is very simple. The sensor has a signal pin which outputs a voltage of 3.0 V when motion is detected. Here both the buzzer and sensor operating at 3.3 V.The value of 3.0 V considered as a HIGH logical level by the ESP32. Which means that we can interact with the sensor considering it outputs a digital signal
When any motion is detected by the PIR sensor then we will trigger the buzzer to start emitting a loud sound like an alarm. When the sensor stops detecting motion, then we stop the buzzer.

Components Required

  • ESP32 development board
  • PIR Sensor
  • Buzzer
  • connecting wires

Circuit Diagram

PIR motion sensor and Buzzer with ESP32(1)

Code Snippet

const byte sensorPin = 21;
const byte buzzerPin = 35;
 
int freq = 2000;
int channel = 0;
int resolution = 8;
int dutyCycle = 128;
 
SemaphoreHandle_t syncSemaphore;
 
void IRAM_ATTR handleInterrupt() {
  xSemaphoreGiveFromISR(syncSemaphore, NULL);
}
 
void setup() {
 
  Serial.begin(115200);
 
  syncSemaphore = xSemaphoreCreateBinary();
 
  pinMode(sensorPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(sensorPin), handleInterrupt, CHANGE);
 
  ledcSetup(channel, freq, resolution);
  ledcAttachPin(buzzerPin, channel);
 
}
 
void loop() {
 
    xSemaphoreTake(syncSemaphore, portMAX_DELAY);
 
    if(digitalRead(sensorPin)){
 
      Serial.println("Motion detected");
      ledcWrite(channel, dutyCycle);
 
    }else{
 
      Serial.println("Motion stoped");
      ledcWrite(channel, 0);
 
    }
 
}

Setup the ESP32 board in Arduino IDE

If you want to learn more about the ESP32 development board visit the official website of esp32:
There is an add-on for the Arduino IDE that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow this tutorial to prepare your Arduino IDE: