Projects · 01
Intrusion alarm
Guard a door with an invisible line. When the door opens, the infrared beam breaks and a buzzer sounds. It runs on batteries, so you can stick it anywhere. Then, if you like, add a phone alert or solder it into a permanent box.
Do these lessons first
- Voltage, current, resistanceavailablewhy the resistor, how a voltage is measured.
- Your first circuitavailablewhich breadboard holes are connected, how to spot a short circuit.
- LEDs and the right resistoravailablewhich way round the LED goes, why 220 Ω in front of it.
- Your first program: connect and upload code to your ESP32availableinstall the Arduino IDE, connect the board, upload a sketch.
- Inputs, outputs and ifavailableread a button, switch a buzzer, let the code decide.
You can start without them: the “Reminder” boxes give the idea in two lines.
- Level
- Level 1the easiest mission
- Time
- One afternoon2–3 h (base build). Permanent version: add 2–3 h · estimate
- Cost
- About 50–85 CADestimate
- Tools
- Easybase build: no soldering, no power tools. The permanent version needs a soldering iron.
- Ask for help
- 3 stepssteps 5, 6 and 7
- Lesson first
- Voltage, current, resistanceavailable
3.3 V logic only. The receiver's output wire goes to GPIO32 and is pulled up to 3V3 only (the code turns on the board's built-in pull-up). The ESP32 uses 3.3 V logic (3.6 V absolute maximum): never connect any ESP32 signal pin to 5 V. The one exception is the board's own 5V power pin, which takes the battery pack and nothing else.
Safety first
Read this box before you plug anything in.
- Batteries
- Small parts
- 3.3 V logic only. The receiver's output wire goes to
GPIO32and is pulled up to 3V3 only (the code turns on the board's built-in pull-up). The ESP32 uses 3.3 V logic (3.6 V absolute maximum): never connect any ESP32 signal pin to 5 V. The one exception is the board's own5Vpower pin, which takes the battery pack and nothing else. - The red rail is 3V3 only. The 4×AA pack goes into the
5Vpin row and the blue rail (−). Never put its + wire on a red rail. - The two packs are not interchangeable. The 4×AA pack (up to 6.4 V) is for the ESP32 only. The emitter is rated 5.5 V at most, so it takes the 3×AA pack, never 4 cells. Put a label on each: “ESP32 4×AA” and “EMITTER 3×AA”.
- Pack OFF before USB. The board takes one power source at a time. With the pack ON and USB plugged in, current can flow back into the cells. Switch the pack OFF before you plug in the USB cable, and before you move any wire.
- Batteries: never mix alkaline and rechargeable cells, old and new, or brands in one holder; replace all the cells at once. Follow the + / − marks inside the holder. Never let the bare ends of a pack touch each other or metal. Never recharge alkaline cells; recharge NiMH cells only in a NiMH charger, outside the box. No 9 V battery, no 5- or 6-cell holder, no LiPo for this mission. Take the cells out if the alarm sits unused for a month; white crust on a cell means it leaked, so wear gloves, clean it and dispose of it properly. Recycle used cells at a drop-off point.
- Keep the beam out of direct sunlight: sunlight contains infrared and can cause false alarms.
- Small parts and cells: keep small parts, wires and batteries away from pets and from anyone who might put them in their mouth.
Parts
Base build, on a solder-free breadboard. The parts for the permanent version are in a separate list further down.
Show the 13 parts · About 50–85 CAD
- 1
ESP32 board×1
The brain
Exact spec: ESP32-DevKitC V4 or a clone: ESP32-WROOM-32, 38 pins, 3.3 V logic. Check the regulator before you buy or use it (step 2): the 3-legged chip with a big tab near the
5Vpin should say AMS1117. - 2
Infrared break-beam pair, 5 mm1 pair
The emitter sends an invisible beam, the receiver sees it
Exact spec: 5 mm LED version (Adafruit 2168 type): emitter (2 wires, red and black) + receiver (3 wires: red +, black −, white or yellow OUT), open-collector output, supply 3.3–5.5 V. Rated range about 50 cm at 5 V; we use 15–20 cm, so there is margin. Test it.
- 3
4×AA battery holder with ON/OFF switch, cover and header-pin ends×1
Powers the ESP32 board
Exact spec: Switched 4×AA holder with a snap-on cover and 0.1 in (2.54 mm) pin ends that plug straight into the breadboard (Adafruit 830 type). Fresh alkaline cells give about 6.4 V, flat ones about 4 V. The board needs about 4.4–6.5 V: below that it misbehaves, so change the cells before they get that low.
- 4
3×AA battery holder with ON/OFF switch and cover×1
Powers the emitter on the door
Exact spec: Switched 3×AA holder, about 4.5 V. Three cells, never four: the emitter takes 5.5 V at most.
- 5
AA batteries×7
4 for the ESP32 pack, 3 for the emitter pack
Exact spec: Alkaline AA (LR6), or low-self-discharge NiMH AA (the kind sold as “ready to use”). Same type and brand in each holder, never mixed. 4×NiMH only if your regulator is not an AMS1117 (step 2).
- 6
WAGO 221-412 lever connectors×2
Join the emitter's wires to its pack, no solder
Exact spec: 2-conductor lever connectors, one for red and one for black. If a wire is very thin, strip 11 mm and fold it back on itself so it fills the connector. (Alternative: if both the pack and the emitter have header-pin ends, 2 female-to-female jumpers.)
- 7
220 Ω resistor×1
Protects the LED
Exact spec: 220 Ω, 1/4 W, through-hole
- 8
LED×1
Shows what the alarm is doing
Exact spec: 5 mm LED, any colour, through-hole
- 9
Active buzzer module×1
Makes the alarm sound
Exact spec: Active (built-in tone) buzzer module, 3 pins S / + / −, 3.3–5 V, sounds when S is HIGH. Test it in step 11: some modules are the other way round.
- 10
Push button×1
Arms and disarms
Exact spec: 6 mm tactile switch, 4 legs
- 11
Breadboard×1
Connects parts without soldering
Exact spec: Full-size 830 points (fits a 38-pin ESP32)
- 12
Jumper wires1 set
Link the parts
Exact spec: Male-to-male, about 10–20 cm, 20 wires or more. Only if your 4×AA holder has bare wires instead of pin ends: 10 cm of 22 AWG solid wire, one red and one black.
- 13
USB data cable×1
Upload the code
Exact spec: Data cable (not charge-only) matching the board's port. Used for programming only: the alarm itself runs on batteries.
Tools
Show the 5 tools (2 optional)
Computer with Arduino IDE
Upload the code
Exact spec: Arduino IDE 2.x + “esp32 by Espressif” 3.3.x (free download from arduino.cc)
Tape
Stick the emitter and its pack on the door leaf and the receiver on the frame
Exact spec: Double-sided tape, masking tape or blue tack (removable)
Ruler or tape measureoptional
Check the 15–20 cm gap
Exact spec: Any
Sticky labels and a pen
Label the two packs
Exact spec: Any
Multimeteroptional
Check wires, cells and voltages (needed for the permanent version)
Exact spec: Any basic digital multimeter
How it works
The emitter shines an invisible infrared light toward the receiver. While the receiver sees it, its output wire reads one level; when the light is lost, it switches to the other level. The ESP32 only has to read that wire: clear or broken.
For a door, the emitter is stuck on the door leaf and the receiver on the frame or the wall, facing each other 15–20 cm apart when the door is closed. Open the door: the emitter moves away, the receiver loses the beam, the alarm goes off. The emitter has its own battery pack on the door; Adafruit notes that the two halves need not share power or ground, because the signal travels as light.
The receiver’s output is open collector: it can pull the wire down to GND but cannot push it up, so the wire needs a pull-up (a resistor to 3.3 V). The ESP32 has one built in, and the code turns it on.
The whole alarm runs on AA batteries. To make them last, the board sleeps almost all the time and wakes up only when you press the button or the beam breaks. Armed and beam broken: the buzzer sounds for 30 seconds. After that the alarm waits for the door to close and arms itself again. Adding a phone alert and soldering the circuit into a box are optional next steps.
Related lessons: Voltage, current, resistance · Your first circuit · LEDs and the right resistor · Your first program: connect and upload code to your ESP32 · Inputs, outputs and if
Wiring
Two views of the same circuit: the breadboard as you will build it, and the schematic. Tap a diagram to open it full screen.
Show the 16 wires and the pin table
Wire list
| # | Colour | From | To |
|---|---|---|---|
| 1 | red | ESP32 3V3 (hole j19) | 3V3 rail (right red +) |
| 2 | black | ESP32 GND (hole j6) | GND rail (right blue −) |
| 3 | red | 4×AA pack red (+) | the hole next to the ESP32 5V pin (j1). Never a red rail. |
| 4 | black | 4×AA pack black (−) | GND rail (right blue −) |
| 5 | red | IR receiver red (+) | 3V3 rail |
| 6 | black | IR receiver black (−) | GND rail |
| 7 | yellow | IR receiver OUT (white or yellow) | GPIO32 (j13; pulled up to 3V3 by the code, never to 5 V) |
| 8 | orange | ESP32 GPIO25 (j11) | buzzer S (j39) |
| 9 | red | 3V3 rail | buzzer + (j40) |
| 10 | black | buzzer − (j41) | GND rail |
| 11 | green | ESP32 GPIO26 (j10) | 220 Ω resistor, leg 1 (b26) |
| 12 | black | LED short leg (−) | GND rail |
| 13 | blue | ESP32 GPIO27 (j9) | button leg A (j44) |
| 14 | black | button leg B (diagonal) | GND rail |
| 15 | black | left blue rail | right blue rail (a link of GND) |
| E | red / black | emitter wires | 3×AA pack wires, through the two WAGO connectors, on the door. No wire to the ESP32. |
Hole names (j19, j6…) assume the board's pins sit in columns a and i of the breadboard, USB end at row 1 (step 3). The resistor's leg 2 and the LED's long leg (+) share the same breadboard row. The red rail on the right is 3V3 only; the left red rail stays unused.
ESP32 pins
| Pin | Goes to | Role |
|---|---|---|
5V | 4×AA pack + (the only thing that goes here) | Power in (about 4.4–6.5 V; below that it misbehaves) |
3V3 | 3V3 rail: IR receiver +, buzzer + | Power out (3.3 V) |
GND | GND rail: pack −, IR receiver −, buzzer −, LED, button | Ground |
GPIO32 | IR receiver OUT | Input with internal pull-up (LOW = beam broken). Wakes the board from deep sleep. |
GPIO25 | Buzzer S | Output |
GPIO26 | 220 Ω → LED | Output |
GPIO27 | Button (other leg to GND) | Input with internal pull-up. Wakes the board from deep sleep. |
Pin order can differ on clones: always follow the labels printed on your board. The table above is for the original DevKitC V4.
Build steps
Do one step, check it, then go on.
Step 1 · Lay out your parts.
Check: Every part in the list is on the table.
Step 2 · Check your board.
Look at the little 3-legged chip with a big flat tab, next to the
5Vpin. Read what is printed on it. If it says AMS1117 (the original board uses it), 4 alkaline cells are fine. If it is tiny, has 5 legs or has no marking, use 4 NiMH cells only (they give a lower voltage). Also read the labels printed on the board next to the pins: on clones the order can differ from this sheet, and your labels win.Check: You know which chip regulates your board, and you have found the pins
5V,GND,3V3,25,26,27and32by their printed labels.Step 3 · Place the ESP32.
Press the board across the middle gap, so its two rows of pins land in columns a and i, rows 1 to 19. USB port at row 1, antenna toward row 20. Leave rows 20–23 empty: that is where the antenna sits. Each pin on the j side now has a free hole next to it (column j). No cable yet.
Check: The board sits flat, no pin is bent, and the pin
5Vis in row 1, column i.Step 4 · Rails.
Wire the ESP32 pin
3V3(hole j19) to the right red (+) rail and the pinGND(hole j6) to the right blue (−) rail. Then link the left blue rail to the right blue rail with one wire. The right red rail is now 3V3 only.Check: Red wire on the red rail, black wire on the blue rail, and nothing else touches the red rail yet.
Step 6 · Power the ESP32 from its pack. Ask for help
Put 4 cells in the 4×AA holder, matching the + / − marks. Switch it OFF. Label it “ESP32 4×AA”. Plug its black pin end into the right blue (−) rail and its red pin end into the hole next to the
5Vpin (j1). Never into a red rail. Leave the switch OFF.Check: Red goes to the
5Vrow, black to the blue rail, the switch is OFF, and someone experienced (or you, twice) has checked it.Step 7 · Prepare the emitter's pack. Ask for help
Put 3 cells in the 3×AA holder, matching the marks. Switch it OFF and label it “EMITTER 3×AA”. Open the lever of a WAGO connector, push in the pack's red wire and the emitter's red wire (strip about 11 mm), close the lever. Same with a second WAGO for the two black wires. Give each wire a gentle tug: it must hold. Red to red, black to black. No wire goes to the ESP32.
Check: Red is joined to red, black to black, the switch is OFF, and nothing from the emitter touches the breadboard or the ESP32.
Step 8 · Upload the code.
Both packs OFF. Install the board package, open the sketch, plug in the USB cable, choose “ESP32 Dev Module”, upload. Unplug the USB cable when it is done.
Check: “Done uploading” appears.
Step 9 · Test the beam on the table.
Emitter and receiver on the table, about 15 cm apart, facing each other. Switch the emitter's pack ON. Plug in the USB cable and open the Serial Monitor at 115200 baud (pack for the ESP32 stays OFF). The board starts in test mode, which lasts 90 seconds after power-on or reset: the monitor prints “clear” or “broken” each time the beam changes. Press EN (reset) to restart the 90 seconds whenever you need. You should see “clear”. Pass your hand between the modules.
Check: The monitor says “broken” while your hand blocks the beam and “clear” otherwise.
Step 10 · Fix swapped words (only if needed).
If the monitor shows “broken” when nothing blocks the beam, find
const int BROKEN = LOW;in the code, changeLOWtoHIGH, upload again.Check: “clear” with nothing in the way, “broken” with your hand.
Step 11 · Add the buzzer.
Everything OFF and unplugged. Buzzer
StoGPIO25,+to the 3V3 rail,−to the GND rail (follow the labels on your module). Test it: at the end of the 90 s test mode (press EN to start it again) the buzzer gives one short chirp (0.2 s). That chirp is the buzzer test; you hear the real alarm in step 17. If the buzzer is silent at the chirp and sounds the rest of the time, your module works the other way round: changeBUZZER_ONin the code.Check: The buzzer gives one short chirp at the end of test mode and is silent otherwise. A buzzer that sounds all the time would empty the batteries in a night.
Step 14 · Stick the emitter, its pack and the receiver on the door.
Close the door. Stick the emitter and its 3×AA pack on the door leaf and the receiver on the frame or the wall next to it, at the same height, facing each other 15–20 cm apart (use the ruler), with both lenses clear of the door trim or moulding. Keep the pack's switch within reach. No wire may cross the gap of the door. Keep the beam out of direct sunlight. Do not press the tape down for good yet.
Check: Both modules face each other at the same height, and the only wires on the door leaf are the emitter's, joined to its own pack.
Step 15 · Align it with the door closed.
Switch the emitter's pack ON. Plug the ESP32 into USB (its pack stays OFF) and open the Serial Monitor. Test mode runs for 90 seconds, and the LED is lit while the beam is broken (press EN to restart the test). With the door closed you should see “clear”. Nudge the emitter or the receiver slightly in every direction: it should stay “clear” with a little room to spare. Then press the tape down.
Check: “clear” stays steady with the door closed, even when you tap the door gently.
Step 16 · Test by opening the door.
Press EN to restart the 90 s test mode. Open the door slowly, then close it. Do it three times.
Check: “broken” appears when the door opens, “clear” returns when it is closed, every time.
Step 17 · Test like a spy.
Unplug USB. Switch the ESP32's pack ON: the 90 s test mode runs, ends with a short chirp, then the LED blinks twice (disarmed). Press the button: the LED blinks once a second for 10 seconds, so you can leave and close the door behind you. Then one long flash: the alarm is armed. Open the door: the buzzer sounds. Press the button to silence it.
Check: The buzzer sounds when the door opens. Press the button: it stops and the alarm is disarmed (two short blinks).
What the LED tells you (deep sleep, in plain words)
To make the batteries last, the board spends almost all its time in deep sleep: nearly switched off, drawing very little. Two things wake it up at once: the button, and the beam breaking. While armed it also wakes briefly every 30 seconds to say it is still alive, which is why you see no steady light.
Show the 9 LED signals and the battery life
| What you see | What it means |
|---|---|
| Lit while the beam is broken (first 90 s) | Test mode, after switching on or pressing EN. The LED shows what the receiver sees. A short chirp from the buzzer ends it. |
| Two short blinks | Board just switched on, or alarm disarmed. Nothing is watching. |
| One blink per second for 10 s | Arming. You have 10 seconds to leave and close the door. Press the button again to cancel. |
| One long flash | Armed. The beam was clear and the alarm is watching. |
| One tiny flash every 30 s | Armed and asleep. It woke up for a moment and went back to sleep. |
| Fast blinking for 2 s, and it stays disarmed | The beam is already broken when you press the button: check the emitter (switched on? aimed? door closed?). |
| One blink per second for up to 60 s, then fast blinking, and it stays disarmed | The door was still open at the end of the 10 s countdown. It waits up to 60 s for you to close it, then gives up. |
| Fast blinking and the buzzer | Alarm! It rings for 30 seconds. Press the button to stop it at once. |
| One tiny flash every 5 s | After an alarm, waiting for the door to close: the board checks every 5 s whether the beam is back. |
After 30 seconds the buzzer stops by itself. The alarm then waits for the beam to come back (door closed) and re-arms itself. If you leave the door open, it keeps waiting (checking every 5 s) and does not ring again.
How long do the batteries last?
| Pack | Battery life | Notes |
|---|---|---|
| ESP32 box, 4×AA alkaline | about 10–14 days | Almost all of the drain comes from the board's own regulator and power LED, not from your code. 4×NiMH low-self-discharge: about 10 days. A door left open after an alarm costs extra (the board checks every 5 s). |
| Emitter, 3×AA | about 6 days if left on all the time | 2–3 weeks if you switch it on only while the alarm is armed (8–10 hours a day). The emitter is the first pack to run out: switch it off when you are not using the alarm. |
These are estimates from datasheet figures, not measurements. To measure on your build: put a multimeter in series with the pack's red wire and read the sleep current (our estimate is 7.5–9 mA). The phone-alert bonus uses a little more. When the batteries run low the alarm becomes less reliable before it stops, so change all the cells together as soon as it misbehaves.
Code walkthrough
Board: ESP32 Dev Module (ESP32-DevKitC V4 or clone, ESP32-WROOM-32, 38 pins). The code below compiles in our CI with the ESP32 board package 3.3.12.
Nothing to install for the base sketch. Two sketches: the base one (01-intrusion-alarm, no Wi-Fi) and the phone one (01b-intrusion-alarm-phone, bonus).
Download the .ino file Download the sketch folder (.zip)
Chunk 1 Header and wiring
Notes, the wiring summary and the libraries it uses. Note the header: the emitter is an infrared LED, not a laser. What to change: nothing
Show the code (33 lines)
// Tinker Mission — Mission 01: Intrusion alarm (battery version, no Wi-Fi) // Board: ESP32 Dev Module ("esp32 by Espressif" 3.3.x). No extra library needed. // // How it works: the emitter is stuck on the door leaf and the receiver on the frame, facing each // other about 15-20 cm apart when the door is closed. When the door opens, the beam is broken: // the buzzer sounds and the LED blinks fast. The emitter is an infrared LED, not a laser. // // Battery trick: "deep sleep". Most of the time the ESP32 is asleep and uses almost nothing. // It wakes up only when something happens: // - you press the button (to arm or disarm), // - the beam is broken while the alarm is armed, // - a small timer rings (a short "I'm alive" flash every 30 s while armed). // Each wake-up starts the sketch again from the top of setup(). loop() is never used. // // Test mode: for 90 s after you switch on (or press the EN button), the LED shows the beam, // so you can line up the emitter and the receiver. Then a short beep, and it is ready. // // Wiring (ESP32 DevKitC, 38 pins): // 4xAA pack red (+) -> 5V pin black (-) -> GND (5V pin ONLY, never a red rail: the rail is 3V3) // IR emitter red / black -> its own 3xAA pack (on the door, no wire to the ESP32) // IR receiver red -> 3V3 pin black -> GND white/yellow (OUT) -> GPIO32 // Buzzer module S -> GPIO25 + -> 3V3 - -> GND (active buzzer) // LED GPIO26 -> 220 ohm resistor -> LED long leg; LED short leg -> GND // Push button GPIO27 -> button -> GND // Switch the pack OFF before you plug in the USB cable: one power source at a time. // // IMPORTANT: the receiver output is "open collector": it can pull the wire down to GND, but it // cannot push it up. So the wire needs a pull-up resistor. We use the ESP32's built-in one, // which pulls up to 3.3 V. Never add a pull-up to 5 V: ESP32 pins use 3.3 V logic. #include "driver/rtc_io.h" // "RTC" pins: their pull-ups keep working while the ESP32 sleeps #include "driver/gpio.h" // gpio_hold_en(): freezes an output pin at its level during sleep #include "esp_sleep.h" // deep sleep and wake-up sourcesChunk 2 Pins, settings and memory
A name for each pin, which level means “broken” (
BROKEN), which level makes the buzzer sound (BUZZER_ON), then the numbers you may change: arming delay (10 s), alarm length (30 s), heartbeat (30 s), door re-check (5 s), door wait (60 s), test mode (90 s). Last, the one word the board remembers through deep sleep: disarmed, armed, or waiting for the door to close. What to change:BROKENonly if step 10 told you to;BUZZER_ONonly if step 11 told you to; the numbers if you likeShow the code (27 lines)
// ---------- Pins (these four can all wake the ESP32 or stay frozen during sleep) ---------- const gpio_num_t BEAM_PIN = GPIO_NUM_32; // IR receiver output const gpio_num_t BUZZER_PIN = GPIO_NUM_25; const gpio_num_t LED_PIN = GPIO_NUM_26; const gpio_num_t BUTTON_PIN = GPIO_NUM_27; // pressed = LOW (wired to GND) // ---------- Settings you may change ---------- // Most receivers pull OUT down to LOW when the beam is broken. Right after you switch on, the // LED lights while the beam is broken (90 s test mode). If it is the other way round, change LOW to HIGH. const int BROKEN = LOW; // Most buzzer modules beep when S is HIGH. A "low-level trigger" module beeps when S is LOW: // if yours beeps all the time while asleep, change HIGH to LOW. const int BUZZER_ON = HIGH; const int ARMING_S = 10; // seconds to leave and close the door after pressing the button const int ALARM_S = 30; // how long the buzzer sounds const int HEARTBEAT_S = 30; // short LED flash every 30 s while armed (0 = no flash, longer battery) const int RECHECK_S = 5; // door left open after an alarm: check again every 5 s const int DOOR_WAIT_S = 60; // after the arming delay, wait up to 60 s for the door to be closed const int TEST_S = 90; // test mode after switching on or EN: 90 s where the LED shows the beam // ---------- Memory that survives deep sleep ---------- // Normal variables are wiped at each wake-up. "RTC_DATA_ATTR" keeps this one in a tiny memory // that stays powered while the ESP32 sleeps. Switching off (or the EN button) resets it. const int DISARMED = 0; // sleeping, only the button can wake it const int ARMED = 1; // watching the beam const int WAIT_CLEAR = 2; // the alarm has rung: waiting for the door to be closed again RTC_DATA_ATTR int state = DISARMED;Chunk 3 Small helpers
Reading the beam, waiting for the button, blinking the LED, disarming. Everything below uses them. What to change: nothing
Show the code (33 lines)
// ---------- Small helpers ---------- bool beamBroken() { return digitalRead(BEAM_PIN) == BROKEN; } bool buttonPressed() { return digitalRead(BUTTON_PIN) == LOW; } void blink(int times, int onMs, int offMs) { for (int i = 0; i < times; i++) { digitalWrite(LED_PIN, HIGH); delay(onMs); digitalWrite(LED_PIN, LOW); delay(offMs); } } void waitButtonRelease() { while (buttonPressed()) delay(10); delay(50); // ignore button bounce } // Waits `ms` milliseconds, but stops early and returns true if the button is pressed. bool waitOrPress(int ms) { for (int t = 0; t < ms; t += 10) { if (buttonPressed()) return true; delay(10); } return false; } void disarm() { digitalWrite(BUZZER_PIN, !BUZZER_ON); // buzzer off blink(2, 150, 150); // 2 short blinks = disarmed state = DISARMED; Serial.println("Disarmed"); }Chunk 4 Arming
The button starts a 10 s countdown with a 1 Hz blink. At the end the beam must be clear. If the door is still open, the LED keeps blinking once a second for up to 60 s while it waits for you to close it, then fast blinking and it stays disarmed. If the beam is already broken when you press the button, you get the error blink at once. What to change: the arming delay (
ARMING_S) and the door wait (DOOR_WAIT_S)Show the code (39 lines)
// ---------- Arming: 10 s to leave, then the door must be closed ---------- void armAlarm() { waitButtonRelease(); if (beamBroken()) { // beam already broken: emitter off, or not facing the receiver Serial.println("Beam broken: check the emitter. Not armed."); blink(20, 50, 50); // fast blinking for 2 s = error state = DISARMED; return; } Serial.println("Arming..."); for (int i = 0; i < ARMING_S; i++) { // LED blinks once per second digitalWrite(LED_PIN, HIGH); bool pressed = waitOrPress(500); digitalWrite(LED_PIN, LOW); if (pressed || waitOrPress(500)) { // a press during the delay cancels waitButtonRelease(); disarm(); return; } } unsigned long start = millis(); while (beamBroken()) { // door still open: keep blinking and wait if (millis() - start > DOOR_WAIT_S * 1000UL) { Serial.println("Door never closed. Not armed."); blink(20, 50, 50); state = DISARMED; return; } digitalWrite(LED_PIN, (millis() / 500) % 2); if (waitOrPress(10)) { waitButtonRelease(); disarm(); return; } } state = ARMED; blink(1, 1000, 0); // one long flash = armed Serial.println("Armed"); }Chunk 5 Alarm, beam check, re-arm
On a beam wake-up it waits 50 ms and checks again (ignores a flicker). Still broken: buzzer and fast LED for 30 s, or until the button. Then it waits for the beam to come back (door closed), two clear readings 100 ms apart, and arms again by itself. What to change: the alarm length (
ALARM_S)Show the code (32 lines)
// ---------- The alarm: buzzer + fast LED for 30 s, the button stops it ---------- void runAlarm() { Serial.println("ALARM: the door was opened!"); digitalWrite(BUZZER_PIN, BUZZER_ON); unsigned long start = millis(); while (millis() - start < ALARM_S * 1000UL) { digitalWrite(LED_PIN, (millis() / 100) % 2); // fast blink if (waitOrPress(10)) { // button = silence and disarm disarm(); return; } } digitalWrite(BUZZER_PIN, !BUZZER_ON); digitalWrite(LED_PIN, LOW); state = WAIT_CLEAR; // re-arm only once the beam is back (door closed) } // Beam broken: check again 50 ms later, so a tiny flicker does not ring the alarm. void checkBeam() { delay(50); if (beamBroken()) runAlarm(); } // Door closed again after an alarm? Two "clear" readings 100 ms apart = re-armed. void tryRearm() { if (beamBroken()) return; delay(100); if (beamBroken()) return; state = ARMED; blink(1, 1000, 0); Serial.println("Beam back: armed again"); }Chunk 6 Test mode
For 90 s after switching on or pressing EN the board stays awake: the LED is lit while the beam is broken and the monitor prints clear or broken. At the end the buzzer gives a short chirp (0.2 s): the buzzer test. What to change: the length of test mode (
TEST_S)Show the code (23 lines)
// ---------- Test mode: 90 s after switching on or pressing EN ---------- // Use it to line up the emitter and the receiver. The LED is ON while the beam is broken, and // the Serial Monitor prints "clear" or "broken" each time it changes. At the end, a short beep // (0.2 s) tests the buzzer. Need more time? Press EN (reset): test mode starts again. void testMode() { Serial.println("Test mode (90 s): wave your hand through the beam"); unsigned long start = millis(); int last = -1; // -1 = nothing printed yet while (millis() - start < TEST_S * 1000UL) { bool broken = beamBroken(); digitalWrite(LED_PIN, broken); // LED on = beam broken if (broken != last) { // print only when it changes Serial.println(broken ? "broken" : "clear"); last = broken; } delay(50); } digitalWrite(LED_PIN, LOW); digitalWrite(BUZZER_PIN, BUZZER_ON); // buzzer test: a short beep = the buzzer works delay(200); digitalWrite(BUZZER_PIN, !BUZZER_ON); Serial.println("End of test mode"); }Chunk 7 Going to sleep
Before sleeping it switches the buzzer and LED off and locks them off, then lists what may wake it: the button, the beam when armed, a 30 s timer for the heartbeat, and a 5 s timer while it waits for the door to close. What to change: nothing
Show the code (42 lines)
// ---------- Going to sleep ---------- void goToSleep() { waitButtonRelease(); // a button still pressed would wake us up at once if (state == ARMED && beamBroken()) { // the beam must be clear before sleeping armed checkBeam(); waitButtonRelease(); } // Freeze the buzzer OFF and the LED off during sleep (else the pins could float). digitalWrite(BUZZER_PIN, !BUZZER_ON); digitalWrite(LED_PIN, LOW); gpio_hold_en(BUZZER_PIN); gpio_hold_en(LED_PIN); gpio_deep_sleep_hold_en(); // Keep the "RTC" part powered so the pull-ups keep working (costs a few microamps). esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); // Wake-up 1, always: the button. "ALL_LOW" with one pin = "the button is pressed". esp_sleep_enable_ext1_wakeup_io(1ULL << BUTTON_PIN, ESP_EXT1_WAKEUP_ALL_LOW); if (state == ARMED) { esp_sleep_enable_ext0_wakeup(BEAM_PIN, BROKEN); // wake-up 2: the beam is broken if (HEARTBEAT_S > 0) esp_sleep_enable_timer_wakeup(HEARTBEAT_S * 1000000ULL); // flash timer } // Door left open after an alarm: no beam wake-up (it would wake us again and again), // just a timer to check the beam every 5 s. if (state == WAIT_CLEAR) esp_sleep_enable_timer_wakeup(RECHECK_S * 1000000ULL); // Built-in pull-ups that stay on during sleep (the receiver needs one even if BROKEN is HIGH). rtc_gpio_init(BEAM_PIN); rtc_gpio_set_direction(BEAM_PIN, RTC_GPIO_MODE_INPUT_ONLY); rtc_gpio_pullup_en(BEAM_PIN); rtc_gpio_pulldown_dis(BEAM_PIN); rtc_gpio_init(BUTTON_PIN); rtc_gpio_set_direction(BUTTON_PIN, RTC_GPIO_MODE_INPUT_ONLY); rtc_gpio_pullup_en(BUTTON_PIN); rtc_gpio_pulldown_dis(BUTTON_PIN); Serial.println(state == ARMED ? "Sleeping (armed)" : state == WAIT_CLEAR ? "Sleeping (waiting for the door)" : "Sleeping (disarmed)"); Serial.flush(); esp_deep_sleep_start(); // the ESP32 stops here; the next wake-up starts setup() again }Chunk 8 setup() and loop()
Runs at every wake-up. It asks what woke the board (power-on or EN, button, beam, timer), acts on it, then goes back to sleep.
loop()is never reached. What to change: nothingShow the code (40 lines)
// ---------- setup(): runs at every wake-up ---------- void setup() { setCpuFrequencyMhz(80); // slower = less current while awake Serial.begin(115200); // Unfreeze the outputs, and give the two input pins back to normal code. gpio_hold_dis(BUZZER_PIN); gpio_hold_dis(LED_PIN); rtc_gpio_deinit(BEAM_PIN); rtc_gpio_deinit(BUTTON_PIN); pinMode(BUZZER_PIN, OUTPUT); digitalWrite(BUZZER_PIN, !BUZZER_ON); pinMode(LED_PIN, OUTPUT); pinMode(BEAM_PIN, INPUT_PULLUP); // built-in pull-up to 3.3 V (see IMPORTANT above) pinMode(BUTTON_PIN, INPUT_PULLUP); // pressed = LOW blink(1, 50, 0); // tiny flash at every wake-up, so you can see it working // Why did we wake up? esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause(); if (cause == ESP_SLEEP_WAKEUP_EXT1) { // the button if (state == DISARMED) armAlarm(); else disarm(); // armed or waiting: the button disarms } else if (cause == ESP_SLEEP_WAKEUP_EXT0) { // the beam if (state == ARMED) checkBeam(); } else if (cause == ESP_SLEEP_WAKEUP_TIMER) { // the timer if (state == ARMED && beamBroken()) checkBeam(); // rare: broken right at the flash if (state == WAIT_CLEAR) tryRearm(); } else { // switched on, or EN (reset) button: test mode first state = DISARMED; testMode(); blink(2, 150, 150); Serial.println("Ready: press the button to arm"); } goToSleep(); } void loop() { // Never reached: goToSleep() always ends setup(). }
The whole sketch, in one piece
// Tinker Mission — Mission 01: Intrusion alarm (battery version, no Wi-Fi)
// Board: ESP32 Dev Module ("esp32 by Espressif" 3.3.x). No extra library needed.
//
// How it works: the emitter is stuck on the door leaf and the receiver on the frame, facing each
// other about 15-20 cm apart when the door is closed. When the door opens, the beam is broken:
// the buzzer sounds and the LED blinks fast. The emitter is an infrared LED, not a laser.
//
// Battery trick: "deep sleep". Most of the time the ESP32 is asleep and uses almost nothing.
// It wakes up only when something happens:
// - you press the button (to arm or disarm),
// - the beam is broken while the alarm is armed,
// - a small timer rings (a short "I'm alive" flash every 30 s while armed).
// Each wake-up starts the sketch again from the top of setup(). loop() is never used.
//
// Test mode: for 90 s after you switch on (or press the EN button), the LED shows the beam,
// so you can line up the emitter and the receiver. Then a short beep, and it is ready.
//
// Wiring (ESP32 DevKitC, 38 pins):
// 4xAA pack red (+) -> 5V pin black (-) -> GND (5V pin ONLY, never a red rail: the rail is 3V3)
// IR emitter red / black -> its own 3xAA pack (on the door, no wire to the ESP32)
// IR receiver red -> 3V3 pin black -> GND white/yellow (OUT) -> GPIO32
// Buzzer module S -> GPIO25 + -> 3V3 - -> GND (active buzzer)
// LED GPIO26 -> 220 ohm resistor -> LED long leg; LED short leg -> GND
// Push button GPIO27 -> button -> GND
// Switch the pack OFF before you plug in the USB cable: one power source at a time.
//
// IMPORTANT: the receiver output is "open collector": it can pull the wire down to GND, but it
// cannot push it up. So the wire needs a pull-up resistor. We use the ESP32's built-in one,
// which pulls up to 3.3 V. Never add a pull-up to 5 V: ESP32 pins use 3.3 V logic.
#include "driver/rtc_io.h" // "RTC" pins: their pull-ups keep working while the ESP32 sleeps
#include "driver/gpio.h" // gpio_hold_en(): freezes an output pin at its level during sleep
#include "esp_sleep.h" // deep sleep and wake-up sources
// ---------- Pins (these four can all wake the ESP32 or stay frozen during sleep) ----------
const gpio_num_t BEAM_PIN = GPIO_NUM_32; // IR receiver output
const gpio_num_t BUZZER_PIN = GPIO_NUM_25;
const gpio_num_t LED_PIN = GPIO_NUM_26;
const gpio_num_t BUTTON_PIN = GPIO_NUM_27; // pressed = LOW (wired to GND)
// ---------- Settings you may change ----------
// Most receivers pull OUT down to LOW when the beam is broken. Right after you switch on, the
// LED lights while the beam is broken (90 s test mode). If it is the other way round, change LOW to HIGH.
const int BROKEN = LOW;
// Most buzzer modules beep when S is HIGH. A "low-level trigger" module beeps when S is LOW:
// if yours beeps all the time while asleep, change HIGH to LOW.
const int BUZZER_ON = HIGH;
const int ARMING_S = 10; // seconds to leave and close the door after pressing the button
const int ALARM_S = 30; // how long the buzzer sounds
const int HEARTBEAT_S = 30; // short LED flash every 30 s while armed (0 = no flash, longer battery)
const int RECHECK_S = 5; // door left open after an alarm: check again every 5 s
const int DOOR_WAIT_S = 60; // after the arming delay, wait up to 60 s for the door to be closed
const int TEST_S = 90; // test mode after switching on or EN: 90 s where the LED shows the beam
// ---------- Memory that survives deep sleep ----------
// Normal variables are wiped at each wake-up. "RTC_DATA_ATTR" keeps this one in a tiny memory
// that stays powered while the ESP32 sleeps. Switching off (or the EN button) resets it.
const int DISARMED = 0; // sleeping, only the button can wake it
const int ARMED = 1; // watching the beam
const int WAIT_CLEAR = 2; // the alarm has rung: waiting for the door to be closed again
RTC_DATA_ATTR int state = DISARMED;
// ---------- Small helpers ----------
bool beamBroken() { return digitalRead(BEAM_PIN) == BROKEN; }
bool buttonPressed() { return digitalRead(BUTTON_PIN) == LOW; }
void blink(int times, int onMs, int offMs) {
for (int i = 0; i < times; i++) {
digitalWrite(LED_PIN, HIGH);
delay(onMs);
digitalWrite(LED_PIN, LOW);
delay(offMs);
}
}
void waitButtonRelease() {
while (buttonPressed()) delay(10);
delay(50); // ignore button bounce
}
// Waits `ms` milliseconds, but stops early and returns true if the button is pressed.
bool waitOrPress(int ms) {
for (int t = 0; t < ms; t += 10) {
if (buttonPressed()) return true;
delay(10);
}
return false;
}
void disarm() {
digitalWrite(BUZZER_PIN, !BUZZER_ON); // buzzer off
blink(2, 150, 150); // 2 short blinks = disarmed
state = DISARMED;
Serial.println("Disarmed");
}
// ---------- Arming: 10 s to leave, then the door must be closed ----------
void armAlarm() {
waitButtonRelease();
if (beamBroken()) { // beam already broken: emitter off, or not facing the receiver
Serial.println("Beam broken: check the emitter. Not armed.");
blink(20, 50, 50); // fast blinking for 2 s = error
state = DISARMED;
return;
}
Serial.println("Arming...");
for (int i = 0; i < ARMING_S; i++) { // LED blinks once per second
digitalWrite(LED_PIN, HIGH);
bool pressed = waitOrPress(500);
digitalWrite(LED_PIN, LOW);
if (pressed || waitOrPress(500)) { // a press during the delay cancels
waitButtonRelease();
disarm();
return;
}
}
unsigned long start = millis();
while (beamBroken()) { // door still open: keep blinking and wait
if (millis() - start > DOOR_WAIT_S * 1000UL) {
Serial.println("Door never closed. Not armed.");
blink(20, 50, 50);
state = DISARMED;
return;
}
digitalWrite(LED_PIN, (millis() / 500) % 2);
if (waitOrPress(10)) {
waitButtonRelease();
disarm();
return;
}
}
state = ARMED;
blink(1, 1000, 0); // one long flash = armed
Serial.println("Armed");
}
// ---------- The alarm: buzzer + fast LED for 30 s, the button stops it ----------
void runAlarm() {
Serial.println("ALARM: the door was opened!");
digitalWrite(BUZZER_PIN, BUZZER_ON);
unsigned long start = millis();
while (millis() - start < ALARM_S * 1000UL) {
digitalWrite(LED_PIN, (millis() / 100) % 2); // fast blink
if (waitOrPress(10)) { // button = silence and disarm
disarm();
return;
}
}
digitalWrite(BUZZER_PIN, !BUZZER_ON);
digitalWrite(LED_PIN, LOW);
state = WAIT_CLEAR; // re-arm only once the beam is back (door closed)
}
// Beam broken: check again 50 ms later, so a tiny flicker does not ring the alarm.
void checkBeam() {
delay(50);
if (beamBroken()) runAlarm();
}
// Door closed again after an alarm? Two "clear" readings 100 ms apart = re-armed.
void tryRearm() {
if (beamBroken()) return;
delay(100);
if (beamBroken()) return;
state = ARMED;
blink(1, 1000, 0);
Serial.println("Beam back: armed again");
}
// ---------- Test mode: 90 s after switching on or pressing EN ----------
// Use it to line up the emitter and the receiver. The LED is ON while the beam is broken, and
// the Serial Monitor prints "clear" or "broken" each time it changes. At the end, a short beep
// (0.2 s) tests the buzzer. Need more time? Press EN (reset): test mode starts again.
void testMode() {
Serial.println("Test mode (90 s): wave your hand through the beam");
unsigned long start = millis();
int last = -1; // -1 = nothing printed yet
while (millis() - start < TEST_S * 1000UL) {
bool broken = beamBroken();
digitalWrite(LED_PIN, broken); // LED on = beam broken
if (broken != last) { // print only when it changes
Serial.println(broken ? "broken" : "clear");
last = broken;
}
delay(50);
}
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, BUZZER_ON); // buzzer test: a short beep = the buzzer works
delay(200);
digitalWrite(BUZZER_PIN, !BUZZER_ON);
Serial.println("End of test mode");
}
// ---------- Going to sleep ----------
void goToSleep() {
waitButtonRelease(); // a button still pressed would wake us up at once
if (state == ARMED && beamBroken()) { // the beam must be clear before sleeping armed
checkBeam();
waitButtonRelease();
}
// Freeze the buzzer OFF and the LED off during sleep (else the pins could float).
digitalWrite(BUZZER_PIN, !BUZZER_ON);
digitalWrite(LED_PIN, LOW);
gpio_hold_en(BUZZER_PIN);
gpio_hold_en(LED_PIN);
gpio_deep_sleep_hold_en();
// Keep the "RTC" part powered so the pull-ups keep working (costs a few microamps).
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
// Wake-up 1, always: the button. "ALL_LOW" with one pin = "the button is pressed".
esp_sleep_enable_ext1_wakeup_io(1ULL << BUTTON_PIN, ESP_EXT1_WAKEUP_ALL_LOW);
if (state == ARMED) {
esp_sleep_enable_ext0_wakeup(BEAM_PIN, BROKEN); // wake-up 2: the beam is broken
if (HEARTBEAT_S > 0) esp_sleep_enable_timer_wakeup(HEARTBEAT_S * 1000000ULL); // flash timer
}
// Door left open after an alarm: no beam wake-up (it would wake us again and again),
// just a timer to check the beam every 5 s.
if (state == WAIT_CLEAR) esp_sleep_enable_timer_wakeup(RECHECK_S * 1000000ULL);
// Built-in pull-ups that stay on during sleep (the receiver needs one even if BROKEN is HIGH).
rtc_gpio_init(BEAM_PIN);
rtc_gpio_set_direction(BEAM_PIN, RTC_GPIO_MODE_INPUT_ONLY);
rtc_gpio_pullup_en(BEAM_PIN);
rtc_gpio_pulldown_dis(BEAM_PIN);
rtc_gpio_init(BUTTON_PIN);
rtc_gpio_set_direction(BUTTON_PIN, RTC_GPIO_MODE_INPUT_ONLY);
rtc_gpio_pullup_en(BUTTON_PIN);
rtc_gpio_pulldown_dis(BUTTON_PIN);
Serial.println(state == ARMED ? "Sleeping (armed)" : state == WAIT_CLEAR ? "Sleeping (waiting for the door)" : "Sleeping (disarmed)");
Serial.flush();
esp_deep_sleep_start(); // the ESP32 stops here; the next wake-up starts setup() again
}
// ---------- setup(): runs at every wake-up ----------
void setup() {
setCpuFrequencyMhz(80); // slower = less current while awake
Serial.begin(115200);
// Unfreeze the outputs, and give the two input pins back to normal code.
gpio_hold_dis(BUZZER_PIN);
gpio_hold_dis(LED_PIN);
rtc_gpio_deinit(BEAM_PIN);
rtc_gpio_deinit(BUTTON_PIN);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, !BUZZER_ON);
pinMode(LED_PIN, OUTPUT);
pinMode(BEAM_PIN, INPUT_PULLUP); // built-in pull-up to 3.3 V (see IMPORTANT above)
pinMode(BUTTON_PIN, INPUT_PULLUP); // pressed = LOW
blink(1, 50, 0); // tiny flash at every wake-up, so you can see it working
// Why did we wake up?
esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause();
if (cause == ESP_SLEEP_WAKEUP_EXT1) { // the button
if (state == DISARMED) armAlarm();
else disarm(); // armed or waiting: the button disarms
} else if (cause == ESP_SLEEP_WAKEUP_EXT0) { // the beam
if (state == ARMED) checkBeam();
} else if (cause == ESP_SLEEP_WAKEUP_TIMER) { // the timer
if (state == ARMED && beamBroken()) checkBeam(); // rare: broken right at the flash
if (state == WAIT_CLEAR) tryRearm();
} else { // switched on, or EN (reset) button: test mode first
state = DISARMED;
testMode();
blink(2, 150, 150);
Serial.println("Ready: press the button to arm");
}
goToSleep();
}
void loop() {
// Never reached: goToSleep() always ends setup().
}
Is the code tested?
The code is compiled automatically every time we change it, so it should build without errors. A real test on real hardware happens when we build this project; until then this sheet stays marked “To test”, and some details (cost, battery life, timing, range on a real door) may change. The code assumes the receiver output goes LOW when the beam is broken. Check this on your own module (step 9) and change the BROKEN constant if it is reversed.
Test checklist
- The Serial Monitor says “broken” when your hand blocks the beam, “clear” otherwise
- With the door closed, “clear” stays steady
- Switch on the pack: 90 s of test mode, a chirp, then two short blinks. Button: 10 s of blinking, then one long flash
- Opening the door sounds the buzzer for 30 seconds
- Pressing the button silences and disarms everything
- After the alarm, closing the door re-arms it
- Both packs are labelled, and the + rail reads 0 V with the pack ON and the ESP32 unplugged (permanent version)
Troubleshooting
Nothing happens when I switch the pack on
5V row (not a rail), and that the switch is ON. Measure the pack with the multimeter: 4×AA should read about 4.4–6.5 V; below that the board misbehaves, so change the cells.The red power LED lights but the LED does not blink
Stuck on “broken” with the door closed
The emitter goes dark after a few days
The buzzer sounds all the time (or never)
BUZZER_ON in the code (step 11).The alarm goes off by itself
The board does not wake when I open the door
GPIO32) and that the alarm is armed (one long flash after the countdown).No phone alert (bonus)
Go further 1: phone alert
Same build, no new wire. Add Wi-Fi so your phone buzzes when the alarm goes off. The buzzer still sounds first and always rings its 30 seconds, whatever the Wi-Fi does.
3 bonus steps · 1 code chunk · Wi-Fi needed
Step B1 · Set up the phone.
Install the free ntfy app, subscribe to a topic you make up (random letters and numbers, no names). Anyone who guesses it can read it.
Check: The topic appears in the app.
Step B2 · Load the phone-alert sketch and fill it in.
Open the sketch “01b-intrusion-alarm-phone”. Type your Wi-Fi name, password and the same topic. The ESP32 joins 2.4 GHz Wi-Fi only (not 5 GHz). Upload it (both packs OFF, then USB, as before).
Check: The topic in the code matches the app exactly.
Step B3 · Test it.
Arm the alarm and open the door.
Check: The buzzer sounds and, a few seconds later, the alert arrives on your phone. One alert per alarm.
Wi-Fi is only switched on while an alarm is going off (it waits at most 10 s to connect), so the batteries still last about 10–14 days. When the cells get low, the phone alert stops working first: replace them. If the board restarts during an alert (low cells), it comes back disarmed (two blinks): change the cells. The button is not read while the alert is being sent (about 10 s).
Bonus chunk The phone alert
Only in the phone sketch. Switches Wi-Fi on only during an alarm (10 s at most to connect), sends one short message to ntfy, then switches Wi-Fi off.
setInsecure()skips certificate checks to keep it simple. What to change: Wi-Fi name, password, topic, the message textShow the code (34 lines)
// ---------- The phone alert ---------- // Sends one short message to the ntfy service (Wi-Fi must be connected). void sendPhoneAlert() { WiFiClientSecure client; client.setInsecure(); // skips certificate checks to keep it simple HTTPClient http; http.setConnectTimeout(5000); // never wait more than 5 s for the server http.setTimeout(5000); http.begin(client, String("https://ntfy.sh/") + NTFY_TOPIC); int code = http.POST("Alarm: the door was opened (infrared beam broken)."); Serial.printf("Phone alert sent (answer %d)\n", code); http.end(); } // Wi-Fi on, one alert, Wi-Fi off. The LED keeps blinking fast meanwhile. // Returns true if the button was pressed while we waited for Wi-Fi. bool phoneAlert() { WiFi.mode(WIFI_STA); WiFi.begin(WIFI_NAME, WIFI_PASS); bool pressed = false; unsigned long start = millis(); while (WiFi.status() != WL_CONNECTED && millis() - start < WIFI_TIMEOUT_S * 1000UL) { digitalWrite(LED_PIN, (millis() / 100) % 2); if (waitOrPress(10)) { pressed = true; break; } } if (!pressed && WiFi.status() == WL_CONNECTED) sendPhoneAlert(); else if (!pressed) Serial.println("No Wi-Fi: no phone alert (check name, password, 2.4 GHz)"); WiFi.disconnect(true); // Wi-Fi off again: it is the biggest battery user WiFi.mode(WIFI_OFF); return pressed; }
Make it permanent
On a breadboard, a knock can pull out a wire. Here you solder the same circuit onto a perfboard, plug the ESP32 into sockets (so you can still take it out), and put it all in a 3D-printed box. The layout is the breadboard copied hole for hole, so everything you learned still applies. You need to be ready to solder: it is a good skill and not hard, but the iron is very hot.
Soldering safety
- Lead-free solder with a flux core (0.8 mm is easy to use).
- Iron with a stand and a temperature setting, at 325–375 °C. Turn it down if the solder smokes.
- Ventilation: open a window, or use a small fan with a filter that draws the smoke away from your face.
- Safety glasses: clipped wire ends and solder can fly.
- The iron lives in its stand whenever you are not using it. Never touch the tip or the metal shaft. Work on a heat-proof mat. Unplug the iron when you stop. A burn: cool running water for at least 10 minutes.
- Hold the board with a clamp (“helping hands”), not your fingers.
- Nothing powered while you solder: batteries out of the holder, ESP32 unplugged from its sockets, USB unplugged.
- Wash your hands afterwards, and keep food away from the bench.
- Ask someone who has soldered before to watch your first five joints.
14 steps · +2–3 h · soldering iron · ask for help
Parts for the permanent version
Your base-build parts (ESP32, receiver, buzzer, LED, resistor, button, packs, WAGO connectors) move over. You add:
Show the 6 parts
- 1
Breadboard-pattern perfboard, full size×1
Replaces the breadboard
Exact spec: Full-size, same rows, 5-hole strips and rails as the breadboard (Adafruit Perma-Proto Full-sized 1606 type: 157 × 51 mm, 3 mounting holes). Full size, not half, so the layout copies 1:1.
- 2
Female header, 2.54 mm2 strips: 1×40 + 1×20
The ESP32 and the buzzer plug in, and stay removable
Exact spec: Single row, 2.54 mm pitch, long pins. The 1×40 gives the two 19-socket rows for the ESP32, the 1×20 gives the 3-socket row for the buzzer (H3). Cut with a flush cutter; you lose one socket at each cut.
- 3
Screw terminals, 5.0 / 5.08 mm pitch1 × 2-pole, 1 × 3-pole
Pack and receiver connect without soldering the wires
Exact spec: PCB-mount, wire entry facing out (KF301 / DG301 type).
- 4
Solid hook-up wire, 22 AWG, several colours1 set
Link the holes on the board
Exact spec: Insulated, red, black, yellow, orange, green, blue.
- 5
Lead-free solder, flux core1 reel
Joins the parts
Exact spec: 0.8 mm, for example Sn99.3/Cu0.7 or SAC305.
- 6
M3 screws6 flat-head M3 × 10, 3 pan-head M3 × 6–8
Close the box and fix the board in it
Exact spec: Flat-head (countersunk): 4 for the lid, 2 for the battery hatch. Pan-head: 3 to hold the board on its printed standoffs (M2.5 also works).
Tools for the permanent version
Show the 6 tools (1 optional)
Soldering iron with stand and temperature control
Solder the joints
Exact spec: Adjustable, 325–375 °C
Multimeter
Check the joints before power-on (required here)
Exact spec: Continuity beeper, DC volts, diode test
Safety glasses
Protect your eyes from flying clippings
Exact spec: Any clear pair
Helping-hands clamp or board holder
Hold the board while you solder
Exact spec: Any
Flush cutter and wire stripper
Cut the headers and the wires
Exact spec: Any
Small fan with a filter (or an open window)optional
Keep the solder smoke away
Exact spec: Any
Row 1 is at the USB edge of the perfboard. Rows run along the long side. Columns a–e and f–j are on either side of the middle gap, like the breadboard. Solder from the underside; the parts sit on the top.
Soldering steps
Step P1 · Set up a safe bench. Ask for help
Read the soldering safety list. Window open or fan on, glasses on, iron in its stand on a heat-proof mat, board in the clamp. Ask someone who has soldered before to be there for your first five joints.
Check: Someone experienced is with you, and the iron is hot only when you need it.
Step P2 · Fit the ESP32 sockets.
Plug the two 1×19 female headers onto the pins of the ESP32 (this keeps them lined up). Drop the board and headers onto the perfboard: one header in column a, rows 1–19, the other in column i, rows 1–19, with the USB end at row 1. Turn the whole thing over and solder one pin at each end of each header. Check it sits flat and straight, then solder the remaining pins. Pull the ESP32 out and put it aside.
Check: The sockets stand straight, and each pin is a small shiny cone of solder, not a blob.
Step P3 · Solder the terminals and the buzzer socket.
J1 (2-pole): + at h25, − at h27. J2 (3-pole, for the receiver): + at h31, − at h33, OUT at h35. All openings face the right edge. H3 (1×3 female header, for the buzzer): h39 = S, h40 = +, h41 = − (match the order printed on your module).
Check: Each terminal sits flat on the board with its openings facing the right edge.
Step P4 · Solder the resistor, the LED and the button.
R1 (220 Ω), lying flat: from d26 to d30. D1 (LED): long leg (+) in b30, short leg (−) in b31. Leave a30, a31, c30 and c31 empty. SW1 (button): straddling the middle gap, legs in e44, f44, e46, f46. Clip the extra leg length after soldering.
Check: The LED's long leg is in b30, and the button sits flat.
Step P5 · Solder the power wires (W1 to W4).
Insulated 22 AWG wire, flat on the top, soldered from the underside. W1 red: f1 → f25 (the
5Vpin to J1 +). W2 black: j27 → right − rail (J1 − to GND). W3 red: j19 → right + rail (3V3 rail). W4 black: j6 → right − rail (GND rail). Wires may cross over each other: they are insulated.Check: W1 goes to J1 + and nowhere near the + rail.
Step P8 · Solder the LED and button wires (W11 to W15).
W11 green: g10 → b26 (
GPIO26to row 26, the R1 strip). W12 black: d31 → left − rail, around row 34 (LED −). W13 blue: f9 → h44 (GPIO27to the button, diagonal leg f44). W14 black: a46 → left − rail (button's other diagonal leg e46). W15 black: left − rail → right − rail, around row 52.Check: All 15 wires are in. Keep a 6 mm circle around each mounting hole free of wires and parts, and rows 20–23 free.
Step P9 · Look at the underside.
In good light, look for a blob of solder that joins two strips, or a strip and a rail. Remove any blob with the iron (and desoldering braid if you have it).
Check: No bridge between neighbouring joints.
Step P10 · Multimeter checks, packs OFF and ESP32 not plugged in. Ask for help
Continuity (beep) mode. Must NOT beep: right + rail to right − rail; socket i1 (5V) to the + rail; socket i1 to the − rail; neighbouring sockets i1 to i19 with each other (only i6 may beep to GND parts). Must beep: J1 + to socket i1; J1 − to socket i6 and to a19; socket i19 to the + rail; i13 to J2 OUT; i11 to H3 S; i10 to R1 (row 26). The button: socket i9 to the − rail beeps only while pressed (if it beeps all the time, look for a solder bridge on rows 44–46). LED: diode test, red probe on row 30, black on the − rail: it glows faintly, and a red LED reads about 1.6–2.0 V (blue or white 2.6–3.2 V, or OL).
Check: Every “no beep” is silent and every “beep” beeps.
Step P11 · Check the packs, then the key test. Ask for help
Put the cells in the ESP32 holder, switch ON and read the DC voltage on its wires: +5.6 to +6.5 V (alkaline) or +5.0 to +5.6 V (NiMH). A minus sign means the wires are swapped. Switch OFF and screw the wires into J1 (red = +). Now the key test, with the ESP32 still unplugged: switch the pack ON, then measure the socket i1 to GND: you read the pack voltage. Measure the + rail to GND: it must read 0 V.
Check: The + rail reads 0 V. If it shows the pack voltage: STOP. The 5V line touches the 3V3 rail, and it would destroy the ESP32. Switch OFF, find the bridge, fix it.
Step P12 · Plug in the ESP32.
Pack OFF. Plug the ESP32 into its sockets, USB end at row 1, pin
5Vin socket i1. Switch the pack ON: the red power LED on the board lights, and the + rail reads 3.2–3.4 V. Check the emitter pack too: 4.0–4.8 V, before you join it to the emitter.Check: Power LED on, 3V3 rail at about 3.3 V.
Step P13 · Run the tests again.
Repeat steps 9 to 17 of the base build (beam, buzzer, LED, button, door) on your soldered board.
Check: It behaves exactly like the breadboard version.
Step P14 · Put it in the box.
Print the perfboard box, its lid, the battery hatch, the long button pusher and the emitter holder (files: see “3D files” below). Settings in Bambu Studio: Bambu Lab X1 Carbon 0.4 mm nozzle, Bambu PLA Basic, 0.20 mm Standard, 4 walls, 15 % gyroid, supports off, no brim; each file opens as one plate. Estimated time: about 9 hours in all (box 5 h 20, lid 1 h 40, emitter holder 1 h 05, hatch 40 min, pusher 8 min), from another slicer; the parts are not test-printed yet. The board sits on 3 printed standoffs (3 pan-head screws), the lid takes 4 flat-head M3 × 10 screws, and the battery hatch 2 more, so you change the cells without opening the lid. The 4×AA pack lies in its own bay with its switch reachable through a window in the hatch (measure your holder first: sizes vary by a few mm). The box also has a slot for the micro-USB port, with “PACK OFF” embossed next to it (pack OFF first), a window and light tube for the LED, the long pusher over SW1, sound holes for the buzzer, and a cable exit for the receiver wires. It is not airtight: leave the vent slots open. The emitter goes in its own printed holder on the door: it snaps in, and the 3×AA pack sits in a cradle held by a hook-and-loop strap (20 mm wide, about 25 cm). If you stay on the breadboard, a box exists for the 830 board too.
Check: The pack's switch (through the hatch window), the button and the USB port are reachable, and the vent slots are open.
3D files
One 3MF file per part (opens in Bambu Studio, PrusaSlicer or OrcaSlicer, the text ready for a second colour) and the same part as STL (one colour, any slicer).
Model rev 3d: fit, overhang and layer checks passed; not test-printed yet.
Measure first
Before printing, measure your own parts with a ruler or calipers: both battery holders (size and where the switch is), the breadboard or perfboard, the USB plug and the buzzer. Listings vary by a few millimetres. If one is different, change its size in the OpenSCAD file, or print a small test corner first. Too tight: clearance 0.4 mm; too loose: 0.2 mm.
Show the 8 parts to print
- Breadboard box (solder-free 830-point version)open side up; 4×AA battery bay, USB slotPrinted size: 216 × 130 × 32 mmPrint time · filament: ~4 h 25 · ~123 g 3MF 63 KB STL 1 MB
- Lid of the breadboard boxlogo face down; LED, button and buzzer holes; 6 flat-head M3 × 10 screwsPrinted size: 216 × 60 mmPrint time · filament: ~1 h 15 · ~35 g 3MF 123 KB STL 1.4 MB
- Button pusher (breadboard box)flange down; tear off the round disc after printingPrinted size: Ø6 × 4.7 mmPrint time · filament: 2 min 3MF 7 KB STL 97 KB
- Perfboard box (permanent version)open side up; 4×AA bay, USB slot, sound holes, vent slots, 3 standoffsPrinted size: 188 × 144 × 38 mmPrint time · filament: 5 h 20 · 144 g 3MF 84 KB STL 1.3 MB
- Lid of the perfboard boxlogo face down; LED light tube; 6 flat-head M3 × 10 screwsPrinted size: 188 × 75 mmPrint time · filament: 1 h 40 · 38 g 3MF 122 KB STL 1.4 MB
- Long button pusher (perfboard box)sits over SW1; print 2 side by side (tall thin rod)Printed size: Ø4 × 27.9 mmPrint time · filament: 8 min (×2) 3MF 7 KB STL 97 KB
- Battery hatch (both boxes)label face down; window for the pack's switch, 2 flat-head M3 × 10 screwsPrinted size: 86 × 69 × 2 mmPrint time · filament: 37 min · 12 g 3MF 71 KB STL 688 KB
- Emitter holder for the doorbase down; emitter snaps in, 3×AA cradle with a hook-and-loop strapPrinted size: 119 × 55 × 18.6 mmPrint time · filament: 1 h 05 · 25 g 3MF 63 KB STL 970 KB
Bambu Studio settings
Bambu Lab X1 Carbon 0.4 nozzle · Bambu PLA Basic · 0.20 mm Standard · 4 walls · 15 % gyroid infill · supports off · no brim. Print each part in the orientation of the file. Two colours: if the text loads merged into the part, right-click it, Split, To parts, and give the text part filament 2.
Licence: Our own designs, shared under the CC BY-NC 4.0 licence: credit “Tinker Mission”, non-commercial use only. Licence text
Go further 2 (coming soon)
Show the ideas
- Months on batteries: swap the board for a low-power one, which sleeps with almost no drain, so the same cells last far longer.
- The magnet version: instead of an infrared beam, a small magnet and a reed switch. It uses almost nothing, so it can run for a very long time.
Coming soon. You will be able to reuse your buzzer, LED, button and packs.
Go further
Ready for more? This is the upgrade of this mission:
- a visible beam: a red dot you can aim and see;
- an analog reading: instead of “clear / broken”, the ESP32 reads a number from 0 to 4095;
- threshold calibration: you pick the cut-off number yourself.
You can reuse the ESP32, buzzer, LED and button from this build.
Shopping list
Made from the parts and tools lists above, with quantities. Each line opens an Amazon.ca search; Amazon has no multi-item cart link without exact product codes, so you add items one by one. Copy the list to keep it.
Each link opens a plain Amazon.ca search built from the keywords (not an affiliate link). Pick a listing that matches the exact spec in the parts list.
Show the 30 items
- ×1ESP32 boardAmazon.ca
- 1 pairInfrared break-beam pair, 5 mmAmazon.ca
- ×14×AA battery holder with ON/OFF switch, cover and header-pin endsAmazon.ca
- ×13×AA battery holder with ON/OFF switch and coverAmazon.ca
- ×7AA batteriesAmazon.ca
- ×2WAGO 221-412 lever connectorsAmazon.ca
- ×1220 Ω resistorAmazon.ca
- ×1LEDAmazon.ca
- ×1Active buzzer moduleAmazon.ca
- ×1Push buttonAmazon.ca
- ×1BreadboardAmazon.ca
- 1 setJumper wiresAmazon.ca
- ×1USB data cableAmazon.ca
- ×1Computer with Arduino IDE—
- ×1TapeAmazon.ca
- ×1Ruler or tape measure (optional)Amazon.ca
- ×1Sticky labels and a penAmazon.ca
- ×1Multimeter (optional)Amazon.ca
- ×1Breadboard-pattern perfboard, full size (Make it permanent)Amazon.ca
- 2 strips: 1×40 + 1×20Female header, 2.54 mm (Make it permanent)Amazon.ca
- 1 × 2-pole, 1 × 3-poleScrew terminals, 5.0 / 5.08 mm pitch (Make it permanent)Amazon.ca
- 1 setSolid hook-up wire, 22 AWG, several colours (Make it permanent)Amazon.ca
- 1 reelLead-free solder, flux core (Make it permanent)Amazon.ca
- 6 flat-head M3 × 10, 3 pan-head M3 × 6–8M3 screws (Make it permanent)Amazon.ca
- ×1Soldering iron with stand and temperature control (Make it permanent)Amazon.ca
- ×1Multimeter (Make it permanent)Amazon.ca
- ×1Safety glasses (Make it permanent)Amazon.ca
- ×1Helping-hands clamp or board holder (Make it permanent)Amazon.ca
- ×1Flush cutter and wire stripper (Make it permanent)Amazon.ca
- ×1Small fan with a filter (or an open window) (Make it permanent) (optional)Amazon.ca
Intrusion alarm 1 × ESP32 board — ESP32-DevKitC V4 or a clone: ESP32-WROOM-32, 38 pins, 3.3 V logic. Check the regulator before you buy or use it (step 2): the 3-legged chip with a big tab near the 5V pin should say AMS1117. https://www.amazon.ca/s?k=ESP32+DevKitC+38+pin+WROOM-32+AMS1117 1 pair × Infrared break-beam pair, 5 mm — 5 mm LED version (Adafruit 2168 type): emitter (2 wires, red and black) + receiver (3 wires: red +, black −, white or yellow OUT), open-collector output, supply 3.3–5.5 V. Rated range about 50 cm at 5 V; we use 15–20 cm, so there is margin. Test it. https://www.amazon.ca/s?k=IR+break+beam+sensor+5mm 1 × 4×AA battery holder with ON/OFF switch, cover and header-pin ends — Switched 4×AA holder with a snap-on cover and 0.1 in (2.54 mm) pin ends that plug straight into the breadboard (Adafruit 830 type). Fresh alkaline cells give about 6.4 V, flat ones about 4 V. The board needs about 4.4–6.5 V: below that it misbehaves, so change the cells before they get that low. https://www.amazon.ca/s?k=4+AA+battery+holder+switch+cover+header+pins+breadboard 1 × 3×AA battery holder with ON/OFF switch and cover — Switched 3×AA holder, about 4.5 V. Three cells, never four: the emitter takes 5.5 V at most. https://www.amazon.ca/s?k=3+AA+battery+holder+switch+cover 7 × AA batteries — Alkaline AA (LR6), or low-self-discharge NiMH AA (the kind sold as “ready to use”). Same type and brand in each holder, never mixed. 4×NiMH only if your regulator is not an AMS1117 (step 2). https://www.amazon.ca/s?k=AA+alkaline+batteries+8+pack 2 × WAGO 221-412 lever connectors — 2-conductor lever connectors, one for red and one for black. If a wire is very thin, strip 11 mm and fold it back on itself so it fills the connector. (Alternative: if both the pack and the emitter have header-pin ends, 2 female-to-female jumpers.) https://www.amazon.ca/s?k=WAGO+221-412+lever+nut+2+conductor 1 × 220 Ω resistor — 220 Ω, 1/4 W, through-hole https://www.amazon.ca/s?k=220+ohm+resistor+1%2F4W 1 × LED — 5 mm LED, any colour, through-hole https://www.amazon.ca/s?k=5mm+LED+assorted 1 × Active buzzer module — Active (built-in tone) buzzer module, 3 pins S / + / −, 3.3–5 V, sounds when S is HIGH. Test it in step 11: some modules are the other way round. https://www.amazon.ca/s?k=active+buzzer+module+3+pin+5V 1 × Push button — 6 mm tactile switch, 4 legs https://www.amazon.ca/s?k=6mm+tactile+push+button 1 × Breadboard — Full-size 830 points (fits a 38-pin ESP32) https://www.amazon.ca/s?k=830+point+breadboard 1 set × Jumper wires — Male-to-male, about 10–20 cm, 20 wires or more. Only if your 4×AA holder has bare wires instead of pin ends: 10 cm of 22 AWG solid wire, one red and one black. https://www.amazon.ca/s?k=male+to+male+jumper+wires 1 × USB data cable — Data cable (not charge-only) matching the board's port. Used for programming only: the alarm itself runs on batteries. https://www.amazon.ca/s?k=USB+data+cable+micro+USB 1 × Computer with Arduino IDE — Arduino IDE 2.x + “esp32 by Espressif” 3.3.x (free download from arduino.cc) 1 × Tape — Double-sided tape, masking tape or blue tack (removable) https://www.amazon.ca/s?k=removable+double+sided+tape 1 × Ruler or tape measure (optional) — Any https://www.amazon.ca/s?k=tape+measure 1 × Sticky labels and a pen — Any https://www.amazon.ca/s?k=sticky+labels 1 × Multimeter (optional) — Any basic digital multimeter https://www.amazon.ca/s?k=digital+multimeter+basic 1 × Breadboard-pattern perfboard, full size (Make it permanent) — Full-size, same rows, 5-hole strips and rails as the breadboard (Adafruit Perma-Proto Full-sized 1606 type: 157 × 51 mm, 3 mounting holes). Full size, not half, so the layout copies 1:1. https://www.amazon.ca/s?k=Perma-Proto+full+size+breadboard+PCB 2 strips: 1×40 + 1×20 × Female header, 2.54 mm (Make it permanent) — Single row, 2.54 mm pitch, long pins. The 1×40 gives the two 19-socket rows for the ESP32, the 1×20 gives the 3-socket row for the buzzer (H3). Cut with a flush cutter; you lose one socket at each cut. https://www.amazon.ca/s?k=female+header+1x40+2.54mm 1 × 2-pole, 1 × 3-pole × Screw terminals, 5.0 / 5.08 mm pitch (Make it permanent) — PCB-mount, wire entry facing out (KF301 / DG301 type). https://www.amazon.ca/s?k=screw+terminal+block+5.08mm+2+pin+3+pin 1 set × Solid hook-up wire, 22 AWG, several colours (Make it permanent) — Insulated, red, black, yellow, orange, green, blue. https://www.amazon.ca/s?k=22+AWG+solid+core+hook+up+wire+kit 1 reel × Lead-free solder, flux core (Make it permanent) — 0.8 mm, for example Sn99.3/Cu0.7 or SAC305. https://www.amazon.ca/s?k=lead+free+solder+flux+core+0.8mm 6 flat-head M3 × 10, 3 pan-head M3 × 6–8 × M3 screws (Make it permanent) — Flat-head (countersunk): 4 for the lid, 2 for the battery hatch. Pan-head: 3 to hold the board on its printed standoffs (M2.5 also works). https://www.amazon.ca/s?k=M3+screws+standoffs+assortment 1 × Soldering iron with stand and temperature control (Make it permanent) — Adjustable, 325–375 °C https://www.amazon.ca/s?k=soldering+iron+adjustable+temperature+stand 1 × Multimeter (Make it permanent) — Continuity beeper, DC volts, diode test https://www.amazon.ca/s?k=digital+multimeter+continuity+beep 1 × Safety glasses (Make it permanent) — Any clear pair https://www.amazon.ca/s?k=safety+glasses+clear 1 × Helping-hands clamp or board holder (Make it permanent) — Any https://www.amazon.ca/s?k=helping+hands+PCB+holder 1 × Flush cutter and wire stripper (Make it permanent) — Any https://www.amazon.ca/s?k=flush+cutter+wire+stripper 1 × Small fan with a filter (or an open window) (Make it permanent) (optional) — Any https://www.amazon.ca/s?k=solder+fume+extractor+fan
Sources
Show the 14 sources
- Adafruit, IR Break Beam Sensors guide (wiring, power, sunlight, no shared power or ground between the halves)
- Adafruit product 2168, IR break-beam sensor, 5 mm LEDs (3.3–5.5 V, emitter 10 mA at 3.3 V and 20 mA at 5 V, open-collector receiver)
- Adafruit product 830, 4×AA holder with on/off switch (voltages, dimensions, pin ends)
- Adafruit product 1606, Perma-Proto full-sized breadboard PCB (157 × 51 mm, mounting holes)
- Espressif, ESP32-DevKitC V4 schematic (regulator AMS1117-3.3, 22 µF / 10 V input capacitor, power LED)
- Espressif, ESP32-DevKitC V4 user guide (power options: only one at a time)
- Espressif, ESP32-DevKitC V4 dimensions
- Espressif, ESP32 datasheet (3.6 V maximum, 3.0 V minimum, deep-sleep and Wi-Fi currents, pull-up)
- ESP-IDF, Sleep modes (wake-up sources, RTC pull-ups)
- Arduino-ESP32, Deep sleep API
- SparkFun, How to Solder: Through-Hole Soldering (temperature, glasses, helping hands)
- Adafruit, Guide to Excellent Soldering (ventilation)
- Arduino docs, digitalRead()
- Arduino docs, pinMode() and INPUT_PULLUP
Not sourced yet: Estimates, not sourced: battery life and AA capacities, the 4.4 V lower limit, the WAGO 221-412 wire range, the Perma-Proto hole positions. Measure on your build.
Print the sheet Print the project recap sheet
A print-ready version: parts checklist, wiring table and diagram, every step with its picture.
Built it?
I built this
Coming soon: a simple, anonymous count of builds. Nothing is collected for now.