Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

Lesson 12: PIR Motion Module (HC-SR501)

In this lesson, you will learn how to use a PIR (Passive Infrared) motion sensor with an ESP32 Development Board. You’ll learn how to read digital inputs from the sensor to detect motion and output a corresponding message to the serial monitor. We’ll cover the setup and programming required for the ESP32 board to respond when the sensor detects someone’s presence by displaying “Somebody here!”

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Universal Maker Sensor Kit

94

Universal Maker Sensor Kit

You can also buy them separately from the links below.

Component Introduction

Purchase Link

ESP32 & Development Board (ESP32 Board)

BUY

PIR Motion Module (HC-SR501)

-

Breadboard

BUY

Wiring

../_images/Lesson_12_PIR_Module_esp32_bb.png

Code

Code Analysis

  1. Setting up the PIR Sensor Pin. The pin for the PIR sensor is defined as pin 25.

    const int pirPin = 25;
    int state = 0;
    
  2. Initializing the PIR Sensor. In the setup() function, the PIR sensor pin is set as an input. This allows the Arduino to read the state of the PIR sensor.

    void setup() {
      pinMode(pirPin, INPUT);
      Serial.begin(9600);
    }
    
  3. Reading from the PIR Sensor and Displaying the Results. In the loop() function, the state of the PIR sensor is continuously read.

    void loop() {
      state = digitalRead(pirPin);
      if (state == HIGH) {
        Serial.println("Somebody here!");
      } else {
        Serial.println("Monitoring...");
        delay(100);
      }
    }
    

    If the state is HIGH, meaning motion is detected, a message “Somebody here!” is printed to the serial monitor. Otherwise, “Monitoring…” is printed.