A PIR (passive infrared) sensor notices the warmth of people and animals moving in front of it. It's the sensor in automatic lights and alarm systems. In this lesson the ESP32 lights an LED whenever it detects motion.
What you'll learn
- How a PIR motion sensor works
- How to read a digital sensor output
- How to react only when something changes
What you need
- ESP32-DevKitC V4 board and USB cable
- HC-SR501 PIR motion sensor
- Breadboard
- 1 LED and 1 resistor, 220 Ω
- Jumper wires
Wiring
The PIR sensor needs 5 V, but its output signal is 3.3 V, so it's safe to connect straight to the ESP32. The LED and resistor are wired like in lesson 1, on GPIO 26.

| From | To |
|---|---|
| PIR VCC | ESP32 5V |
| PIR OUT | ESP32 GPIO 27 |
| PIR GND | GND (breadboard − rail) |
| ESP32 GPIO 26 | Resistor, then the LED's long leg |
| LED short leg | GND (breadboard − rail) |
| ESP32 GND | Breadboard − rail |
The sketch
const int PIR_PIN = 27;
const int LED_PIN = 26;
bool lastMotion = false;
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
Serial.println("Warming up the PIR sensor (30 seconds)...");
delay(30000);
Serial.println("Ready!");
}
void loop() {
bool motion = digitalRead(PIR_PIN) == HIGH;
digitalWrite(LED_PIN, motion ? HIGH : LOW);
if (motion && !lastMotion) {
Serial.println("Motion detected!");
}
if (!motion && lastMotion) {
Serial.println("Motion ended");
}
lastMotion = motion;
delay(50);
}
Upload the sketch, open the Serial Monitor at 115200 baud and keep still for the 30-second warm-up. Then wave your hand in front of the sensor.
How it works
Behind the white dome, a sensor sees infrared light, which is the heat our bodies give off. When a warm object moves across its view, the sensor sets OUT to HIGH. The sketch remembers the last state in lastMotion, so it prints a message only when the state changes instead of hundreds of times a second.
Adjusting the sensor
- The two orange knobs set the sensitivity (distance, up to about 7 m) and the time OUT stays HIGH after motion (from a few seconds up to a few minutes).
- Turn the time knob fully anticlockwise for the shortest delay while you test.
Try this next
- Count how many times motion is detected and print the total.
- Combine this with the relay lesson to switch a low-voltage lamp on when someone walks in.
Troubleshooting
- The LED stays on all the time: wait for the warm-up, keep still, and turn the time knob anticlockwise.
- Nothing is detected: check that VCC is on 5V, not 3V3, and that OUT is on GPIO 27.