PROJECT 4 · SENSOR + TIMERS

PIR Motion Sensor + Buzzer

Detect movement with an HC‑SR501 and sound a buzzer — using a non‑blocking millis() timer.

⬇ Download the sketch Save Project_4_ESP32_PIR_Motion_Sensor.ino, then open it in the Arduino IDE (setup: Project 0b).

1 · How the PIR sensor works

HC-SR501 PIR sensor with pins and adjusters labeled
HC‑SR501: OUT goes HIGH on motion; two trimmers set range and hold time.
Warm‑up: after power‑on the PIR needs ~30–60 s to stabilize before it reads reliably.

2 · Non‑blocking timing: delay() vs millis()

delay(3000) freezes the whole program for 3 s. Instead we record when motion last happened and check elapsed time — keeping the loop responsive:

lastMotionTime = millis();                    // remember "now"
if (millis() - lastMotionTime >= holdTime) {  // has enough time passed?
  ...
}

This pattern scales to programs doing many things at once — a habit worth building early.

3 · Parts

QtyPartNotes
1ESP32 · breadboard · jumper wires
1HC‑SR501 PIRPowered from 5 V
1Active buzzerBeeps on its own when powered

4 · Wiring

PIR OUT to GPIO 27, buzzer to GPIO 26, PIR on VIN/5V
PIR OUT → GPIO 27 · Buzzer → GPIO 26 · PIR powered from VIN (5 V).
FromTo
PIR VCCVIN (5 V)
PIR GNDGND
PIR OUTGPIO 27
Buzzer +GPIO 26
Buzzer GND
Why VIN, not 3V3? The HC‑SR501 needs 5 V (on VIN when USB‑powered). Its OUT signal is still ESP32‑safe.

5 · Code & expected serial output

The buzzer turns on when motion starts and off after ~3 s with no motion. Logging is event‑based — one line on, one line off. Open Serial Monitor at 115200:

==============================================
 Project 4: ESP32 PIR Motion Sensor + Buzzer
==============================================
PIR OUT -> GPIO 27
Buzzer  -> GPIO 26
Buzzer holds ON for 3000 ms after motion stops.
NOTE: the PIR needs ~30-60 s to warm up after power-on.
----------------------------------------------
[EVENT] MOTION detected  -> buzzer ON
[EVENT] No motion (hold elapsed) -> buzzer OFF
Improved from the original sketch: the kit's version re‑printed the same message every loop and had a confusing "stop alarm" line. This one logs only the two real events.

6 · Demonstration

PIR and buzzer wired to the ESP32 with serial output
Wave your hand → buzzer sounds & "MOTION detected" prints. Stay still → it stops after ~3 s.

7 · Troubleshooting

SymptomLikely causeFix
Always triggersWarming up / sensitivity too highWait 60 s; lower the sensitivity trimmer
Never triggersPIR on 3.3 V, or OUT mis‑wiredPower VCC from VIN (5 V); OUT → GPIO 27
Buzzer silentReversed / wrong pin+ → GPIO 26, − → GND
Buzzer never stopsConstant motion / retrigger jumperHold still; check the jumper
Monitor blankWrong baudSet it to 115200
← Project 3 · PWM Project 5 · Switch Web Server →