Français

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.

To testNot built by us yet: code compiled, circuit and safety checked. Build at your own risk; younger makers with an adult.
Print the sheet

Do these lessons first

  1. Voltage, current, resistanceavailablewhy the resistor, how a voltage is measured.
  2. Your first circuitavailablewhich breadboard holes are connected, how to spot a short circuit.
  3. LEDs and the right resistoravailablewhich way round the LED goes, why 220 Ω in front of it.
  4. Your first program: connect and upload code to your ESP32availableinstall the Arduino IDE, connect the board, upload a sketch.
  5. 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 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.
  • The red rail is 3V3 only. The 4×AA pack goes into the 5V pin 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 5V pin 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.

The shopping list is at the bottom of the page.

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.

How the beam works Two rows. Top, beam clear: the IR emitter shines an invisible infrared beam onto the IR receiver. Inside the receiver, the output switch stays open, so the OUT wire is free and the ESP32's pull-up resistor holds GPIO32 at 3.3 volts: the pin reads HIGH and the Serial Monitor prints clear. Bottom, beam broken: a hand blocks the beam. The receiver's output switch closes and pulls OUT down to ground: GPIO32 reads LOW, about 0 volts, and the monitor prints broken. If the alarm is armed, the buzzer sounds. In the code, BROKEN equals LOW; if your module gives the opposite, change it to HIGH. Keep the modules out of direct sunlight: it contains infrared and can cause false alarms. FIG. 3 — HOW THE BEAM WORKSBeam clearIR emitterIR receiverinfrared, invisibleinside the receiveropen: OUT freeOUTESP323V3pull-upGPIO32HIGH≈ 3.3 V"clear"All quiet.Beam brokenIR emitterIR receiverinside the receiverclosed: OUT → GNDOUTESP323V3pull-upGPIO32LOW≈ 0 V"broken"Armed? The buzzer sounds.const int BROKEN = LOW;Swapped on your module? Change LOW to HIGH (step 10).Keep out of direct sunlight: it contains infrared and can cause false alarms.
Tap the diagram to open it full screen.

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.

Mission 01 wiring, breadboard view (battery power) Full-size breadboard seen from above, row 1 on the left. The ESP32 pins sit in columns i and a, rows 1 to 19, USB port at row 1; column j stays free: each pin on the j side has a free hole. Fifteen numbered wires, numbered as in the sheet. 1 red from 3V3 (j19) to the right red rail, which is 3V3 only; 2 black from GND (j6) to the right blue rail, the GND rail. The ESP32 runs on its own switched 4×AA pack, labelled ESP32 4×AA: wire 3, the pack's red pin end, goes into j1, the hole next to the 5V pin, never into a red rail; wire 4, its black end, into the right blue rail. The IR receiver: 5 red to the 3V3 rail, 6 black to the GND rail, 7 white or yellow (OUT) into j13, next to GPIO32. 8 orange from GPIO25 (j11) to the buzzer S (j39), 9 red from the 3V3 rail to buzzer plus (j40), 10 black from buzzer minus (j41) to the GND rail. 11 green from GPIO26 (j10) to row 26 (b26), the R1 strip: the 220 ohm resistor R1 lies from d26 to d30; the LED's long leg is in b30, its short leg in b31; 12 black from d31 to the left blue rail, near row 34. 13 blue from GPIO27 (j9) to j44; the button straddles the gap in e44, f44, e46 and f46; 14 black from a46 to the left blue rail. 15 black links the left blue rail to the right blue rail. The emitter is not on the breadboard: on the door, its red and black wires join the red and black wires of its own switched 3×AA pack, labelled EMITTER 3×AA, through two lever connectors. No wire goes from the emitter to the ESP32. FIG. 1 — BREADBOARD VIEW (FROM ABOVE)+−−+jihgfedcba+−−+jihgfedcba253035404555ESP325VCMDD3D213GND1214GPIO27GPIO26GPIO2533GPIO323534VNVPEN3V3USB · row 1S+−+AB++++ONOFFESP32 4×AA34j1 = 5VIROUT+−756IR receiveron the frame or wall, wiredOUT wire: white or yellowEmitter: on the door,with its own pack (panel E).8GPIO25 → buzzer S1113GPIO27 → button A12910121415buzzer moduleR1 220 ΩLEDbuttonRight rails (top here): red + = 3V3 only · blue − = GND.Left rails (bottom here): blue − = GND, joined by wire 15 · red + unused.LED: long leg (+) in b30, short leg in b31.Held with row 1 toward you, column j is on the right.Wire list#COLOURFROMTO1redESP32 3V3 (j19)3V3 rail (+), right2blackESP32 GND (j6)GND rail (−), right3redESP32 4×AA pack red (+)j1 (5V row) · not a red rail4blackESP32 4×AA pack black (−)GND rail (−), right5redreceiver red (+)3V3 rail (+)6blackreceiver black (−)GND rail (−)7yellowreceiver OUT (white/yellow)GPIO32 (j13)8orangeESP32 GPIO25 (j11)buzzer S (j39)9red3V3 rail (+)buzzer + (j40)10blackbuzzer − (j41)GND rail (−)11greenESP32 GPIO26 (j10)row 26 (b26), R1 strip12blackLED − row (d31)GND rail (−), left13blueESP32 GPIO27 (j9)button leg A (j44)14blackbutton leg B (a46)GND rail (−), left15blackleft GND rail (−)right GND rail (−)Eemitter red / blackEMITTER 3×AA, 2 WAGO3–7 and E are the parts' own wires. E never goes to the ESP32.EOn the door: emitter + its own pack+++ONOFFEMITTER 3×AAIRIR emitter2 WAGO, red to red, black to blackNo wire to the ESP32 · none across the door gap.Power rulesESP32 4×AA (3, 4): red → j1, the 5V row.Never on a red rail: it is 3V3 only.EMITTER 3×AA (E): the emitter only.Never 4 cells on the emitter (5.5 V max).Receiver OUT (7) → GPIO32 only. Never 5 V.Pack OFF before USB and before moving a wire.
Tap the diagram to open it full screen.
Mission 01 wiring, schematic IEC schematic, battery version. Top left: the ESP32 4×AA pack, with its ON/OFF switch, feeds the ESP32 5V pin through wire 3; its minus side, wire 4, goes to ground. Inside the ESP32 board, a regulator (AMS1117 on the original board) turns the pack voltage into 3.3 volts for the chip and the 3V3 pin. The 3V3 pin feeds a supply line that powers the IR receiver (wires 5 and 6) and the buzzer (wires 9 and 10). Inside the ESP32, a pull-up resistor turned on by the code (INPUT_PULLUP) links GPIO32 to 3.3 volts. The receiver OUT wire 7 goes to GPIO32; inside the receiver, an open-collector transistor can only pull that wire down to ground, when the infrared beam is broken. The emitter is a separate circuit on the door leaf: its own switched EMITTER 3×AA pack, about 4.5 volts, feeds the infrared LED through two lever connectors (E); no wire links it to the ESP32 or crosses the door gap. GPIO25 drives the S pin of the buzzer module (wire 8). GPIO26 goes through a 220 ohm resistor to the LED, then to ground (wires 11 and 12). GPIO27 goes to a push button whose other side is ground (wires 13 and 14), also with the internal pull-up. FIG. 2 — SCHEMATIC (IEC SYMBOLS)+−ESP32 4×AA packON/OFF4.0–6.4 V34Into the 5V pin only.The board's regulator makes the 3.3 V.Never on the 3V3 line (3.6 V max).5V3.3 V REGAMS1117ESP32DevKit3V3GPIO32GPIO25GPIO26GPIO27GNDinternal pull-up(INPUT_PULLUP)3V3IR receiverOUT = open collector+OUT−S+−3V3buzzer(active)220 ΩLEDbuttonGPIO32 and GPIO27 use the internal pull-up: idle = HIGH.door gaponly the beam crosses, no wireframe sidedoor-leaf side+−IR emitterIR LED−+≈4.5 VON/OFFWAGOEMITTER 3×AA(own pack, on the door)IR beam(invisible)12567EE891011121314Wire 15 (breadboard only) joins the two GND rails: one ground.
Tap the diagram to open it full screen.
Show the 16 wires and the pin table

Wire list

#ColourFromTo
1 redESP32 3V3 (hole j19)3V3 rail (right red +)
2 blackESP32 GND (hole j6)GND rail (right blue −)
3 red4×AA pack red (+)the hole next to the ESP32 5V pin (j1). Never a red rail.
4 black4×AA pack black (−)GND rail (right blue −)
5 redIR receiver red (+)3V3 rail
6 blackIR receiver black (−)GND rail
7 yellowIR receiver OUT (white or yellow)GPIO32 (j13; pulled up to 3V3 by the code, never to 5 V)
8 orangeESP32 GPIO25 (j11)buzzer S (j39)
9 red3V3 railbuzzer + (j40)
10 blackbuzzer − (j41)GND rail
11 greenESP32 GPIO26 (j10)220 Ω resistor, leg 1 (b26)
12 blackLED short leg (−)GND rail
13 blueESP32 GPIO27 (j9)button leg A (j44)
14 blackbutton leg B (diagonal)GND rail
15 blackleft blue railright blue rail (a link of GND)
E red / blackemitter wires3×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

PinGoes toRole
5V4×AA pack + (the only thing that goes here)Power in (about 4.4–6.5 V; below that it misbehaves)
3V33V3 rail: IR receiver +, buzzer +Power out (3.3 V)
GNDGND rail: pack −, IR receiver −, buzzer −, LED, buttonGround
GPIO32IR receiver OUTInput with internal pull-up (LOW = beam broken). Wakes the board from deep sleep.
GPIO25Buzzer SOutput
GPIO26220 Ω → LEDOutput
GPIO27Button (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.

  1. Step 1 · Lay out your parts.

    Check: Every part in the list is on the table.

  2. Step 2 · Check your board.

    Look at the little 3-legged chip with a big flat tab, next to the 5V pin. 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.

    Step 2: check your board Top view of an ESP32 DevKitC, USB port at the left. Next to the 5V pin, near the USB end, sits a small black chip with three legs on one side and a big flat tab on the other: the regulator. A magnifier shows its marking, AMS1117. A second pointer shows the 5V pin and the label 5V printed on the board next to it. Below, two cases: AMS1117 means 4 alkaline or 4 NiMH cells are fine; a tiny chip with 5 legs, or no marking, means 4 NiMH cells only. Always follow the labels printed on your own board: pin order can differ on clones. 2×1USB5VGND272625323V3ESP32AMS11173.3regulator: read its marking5V pin + its printed labelAMS11174 alkaline or 4 NiMH cellsare fine!tiny, 5 legs or no marking4 NiMH cells only(lower voltage)Clones: pin order can differ. Always follow the labels printed on your board.

    Check: You know which chip regulates your board, and you have found the pins 5V, GND, 3V3, 25, 26, 27 and 32 by their printed labels.

  3. 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.

    Step 3: place the ESP32 The ESP32 is pressed across the middle gap of the breadboard, its pins in columns a and i, rows 1 to 19, USB port at row 1, antenna toward row 20. The 5V pin lands in i1. Column j stays free: each pin on the j side has a free hole, highlighted. Rows 20 to 23 are hatched: the antenna zone, leave them empty. 3×1×1830+−5VCMD123j: freei: pins5V in i1 · USB at row 1rows 20–23: antenna zone, keep empty

    Check: The board sits flat, no pin is bent, and the pin 5V is in row 1, column i.

  4. Step 4 · Rails.

    Wire the ESP32 pin 3V3 (hole j19) to the right red (+) rail and the pin GND (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.

    Step 4: rails Three wires. Wire 1 red from the 3V3 pin (j19) to the right red rail, which becomes the 3V3 rail: 3V3 only. Wire 2 black from a GND pin (j6) to the right blue rail, the GND rail. Wire 15 black, near row 50, joins the left blue rail to the right blue rail, so both blue rails are GND. 4×3+−1215red rail: 3V3 only− GND rail− GND rail (left)

    Check: Red wire on the red rail, black wire on the blue rail, and nothing else touches the red rail yet.

  5. Step 5 · Wire the receiver. Ask for help

    Pack and USB both off. Receiver red wire to the 3V3 rail, black wire to the GND rail, white or yellow wire (OUT) to GPIO32 (hole j13). Not 5 V.

    Step 5: wire the receiver (ask for help) Pack and USB both off. The IR receiver has three wires. Wire 5 red goes into the 3V3 rail, wire 6 black into the GND rail, wire 7 white or yellow (OUT) into j13, the hole next to GPIO32. Nothing goes to 5 V. 5×1OFFIR+−567GPIO32 · j133V3 rail (+)GND rail (−)IR receiverOUT → GPIO32 only · not 5 V

    Check: Someone experienced (or you, twice) has checked that red is on 3V3 and OUT is on GPIO32 only.

  6. 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 5V pin (j1). Never into a red rail. Leave the switch OFF.

    Step 6: power the ESP32 from its pack (ask for help) The ESP32 4×AA pack sits behind the left end of the breadboard, switch OFF. Wire 3, its red pin end, goes into j1: the hole next to the 5V pin, in row 1. Wire 4, its black pin end, goes into the right blue rail. A red cross marks the red rail: the pack's red wire never goes there, it is 3V3 only. A magnifier shows j1 next to the 5V pin. 6×1OFF×4AA×1+++++−34never the red railESP32 4×AAswitch OFF5Vj1i1red → j1, next to 5V

    Check: Red goes to the 5V row, black to the blue rail, the switch is OFF, and someone experienced (or you, twice) has checked it.

  7. 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.

    Step 7: prepare the emitter's pack (ask for help) The EMITTER 3×AA pack, switch OFF, labelled. Two WAGO lever connectors join it to the IR emitter. Left connector, lever open: the pack's red wire and the emitter's red wire, stripped about 11 millimetres, are pushed into its two entries, then the lever is closed. Right connector, lever closed: the two black wires, joined the same way. Give each wire a gentle tug. Red to red, black to black. No wire goes to the ESP32. 7×1OFF×3AA×2×1+++ONOFFEMITTER 3×AAIRIR emitterlever open: push inlever closed: tug teststrip about 11 mmEEswitch OFF · cells per the + marksRed with red, black with black · no wire 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.

  8. 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.

  9. 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.

  10. 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, change LOW to HIGH, upload again.

    Check: “clear” with nothing in the way, “broken” with your hand.

  11. Step 11 · Add the buzzer.

    Everything OFF and unplugged. Buzzer S to GPIO25, + 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: change BUZZER_ON in the code.

    Step 11: add the buzzer Everything off and unplugged first. The buzzer module's three pins go into h39 (S), h40 (+) and h41 (−), following the labels on the module. Wire 8 orange goes from GPIO25 (j11) to j39, wire 9 red from the 3V3 rail to j40, wire 10 black from j41 to the GND rail. 11×1×3OFFIR+−8910S · h39+ · h40− · h41

    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.

  12. Step 12 · Add the LED.
  13. Step 13 · Add the arm button.
  14. 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.

    Step 14: stick the emitter, its pack and the receiver on the door Seen from above, two moments. Door closed: the IR emitter and its EMITTER 3×AA pack are taped to the door leaf, near the handle side; the IR receiver is taped to the wall or frame next to it, 15 to 20 centimetres away, lenses facing and lined up. The beam is intact and the Serial Monitor shows clear. Door opens: the leaf swings on its hinge, the emitter moves away, the receiver loses the beam: the monitor shows broken and, if armed, the alarm goes off. Only the receiver is wired to the ESP32; no wire crosses the door gap. Keep the modules out of direct sunlight: it contains infrared and can cause false alarms. The same idea works for a cupboard, a drawer or a box lid. 14×15 mm×15 mm×1×1FROM ABOVEDoor closed: beam intactESP3215–20 cmdoor leafframe / wallDoor opens: beam lost → alarmESP32door leafframe / wallEMITTER 3×AAemitterreceiverhinge115200clearclear115200clearbrokensame height, tape bothKeep out of direct sunlight: it contains infrared and can cause false alarms.Same idea for a cupboard, a drawer or a box lid.

    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.

  15. 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.

    Step 15: align it with the door closed For the alignment the ESP32 runs from USB: a USB cable goes into its port at row 1, from the computer, and the Serial Monitor is open. The ESP32 4×AA pack stays connected but switched OFF: never pack ON and USB at the same time. The emitter's own pack, on the door, is switched ON. 15×1data×1++++IR+−34ESP32 4×AA: OFFUSB in → ESP32 pack OFFEMITTER 3×AA on the door: ON

    Check: “clear” stays steady with the door closed, even when you tap the door gently.

  16. 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.

  17. 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.

    Step 17: test like a spy Four moments, left to right. 1: USB unplugged, the ESP32 pack is switched ON: the LED blinks twice. 2: press the button: the LED blinks once a second for 10 seconds while you leave and close the door. 3: one long flash: the alarm is armed. 4: the door opens, seen from above: the receiver loses the beam and the buzzer sounds, the LED blinks fast. Press the button: the alarm stops and is disarmed, two short blinks. 17ON1pack ON2press: 10 s to leave3long flash: armedON10 s4door opens: alarmESP32LED fast + buzzer, 30 sPress the button: it stops, two short blinks = disarmed

    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 the LED says Pictogram card, nine rows. Each row shows a short timeline of the LED, green blocks for the moments it is lit, and what it means. 1: lit while the beam is broken, for the first 90 seconds after power-on or reset: the test mode; a short buzzer chirp ends the test. 2: two short blinks: switched on, or disarmed, nothing is watching. 3: one blink a second for 10 seconds: arming, 10 seconds to leave, press again to cancel. 4: one long flash: armed, the beam was clear. 5: a tiny flash every 30 seconds: armed and asleep, each wake-up gives one tiny flash. 6: fast blinking for 2 seconds: the beam is already broken, it stays disarmed, check the emitter. 7: one blink a second for up to 60 seconds, then fast blinking: the door was still open at the end of the 10 second countdown; it stays disarmed. 8: fast blinking with the buzzer: alarm, press the button to stop it. 9: a tiny flash every 5 seconds: after an alarm, it waits for the door to close, then arms again. Outside the test mode there is no steady light: the board sleeps between flashes to save the batteries. WHAT THE LED SAYSWhat the LED says190 sLit while the beam is brokenFirst 90 s after power-on or reset: test.A short buzzer chirp ends the test.2Two short blinksSwitched on, or disarmed.Nothing is watching.310 s1 blink a second, 10 sArming: 10 s to leave.Press again to cancel.4One long flashArmed.The beam was clear.530 sTiny flash every 30 sArmed and asleep.Each wake-up = one tiny flash.62 sFast blinking, 2 sBeam already broken: stays disarmed.Check the emitter: ON? aimed? door shut?760 s1 blink a second, then fastDoor still open after the 10 s: waits up to 60 s.Then fast blinking: stays disarmed.830 sFast blinking + buzzerAlarm!Press the button to stop it.95 sTiny flash every 5 sAfter an alarm: waits for the door to close.Door closed, beam back: it arms again.Outside the test, no steady light: the board sleeps between flashes to save the batteries.
Tap the diagram to open it full screen.
What you seeWhat 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 blinksBoard just switched on, or alarm disarmed. Nothing is watching.
One blink per second for 10 sArming. You have 10 seconds to leave and close the door. Press the button again to cancel.
One long flashArmed. The beam was clear and the alarm is watching.
One tiny flash every 30 sArmed and asleep. It woke up for a moment and went back to sleep.
Fast blinking for 2 s, and it stays disarmedThe 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 disarmedThe 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 buzzerAlarm! It rings for 30 seconds. Press the button to stop it at once.
One tiny flash every 5 sAfter 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?

PackBattery lifeNotes
ESP32 box, 4×AA alkalineabout 10–14 daysAlmost 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×AAabout 6 days if left on all the time2–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)

  1. 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 sources
  2. Chunk 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: BROKEN only if step 10 told you to; BUZZER_ON only if step 11 told you to; the numbers if you like

    Show 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;
  3. 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");
    }
  4. 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");
    }
  5. 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");
    }
  6. 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");
    }
  7. 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
    }
  8. 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: nothing

    Show 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?

To test

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
Check the cells' + / − marks, that the red wire is in the 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
The board may be in deep sleep: press the button. Check the LED's long leg faces the resistor.
Stuck on “broken” with the door closed
Move the two modules closer, re-aim them (the beam is narrow), keep the lenses clear of the door trim, and check the emitter's pack is ON, its cells are fresh and the receiver is out of direct sunlight.
The emitter goes dark after a few days
Its 3×AA pack is empty. It runs for about 6 days if left on: switch it off when the alarm is not armed, and change all 3 cells together.
The buzzer sounds all the time (or never)
Your buzzer module may work the other way round: change BUZZER_ON in the code (step 11).
The alarm goes off by itself
Direct sunlight on the receiver can cause false alarms: move it or shade it.
The board does not wake when I open the door
Check wire 7 (OUT to GPIO32) and that the alarm is armed (one long flash after the countdown).
No phone alert (bonus)
Check the Wi-Fi name and password (2.4 GHz network), and that the topic in the code matches the app exactly. Low cells can also stop it: replace them. If the board restarts during an alert, it comes back disarmed (two blinks): change the cells.

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
  1. 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.

  2. 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.

  3. 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).

  1. 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 text

    Show 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;
    }

Download the phone-alert sketch (.ino)

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.
Battery safety Four battery-safety pictograms. 1: never mix: an alkaline cell next to a NiMH cell, crossed out; same type, age and brand in one holder, replace all cells at once. 2: polarity: a cell going into the holder with its plus end matching the plus mark. 3: pack OFF before USB: the holder switch in the OFF position, then the USB plug. 4: label the packs: two holders with stickers, ESP32 4×AA and EMITTER 3×AA; the 4-cell pack is for the ESP32 only, the 3-cell pack for the emitter only. BATTERY SAFETY1Never mixSame type, age and brand.Change all cells at once.+ALK+NiMH+ALK+ALK2Follow the marks+ of the cell on the + markinside the holder.++++3OFF before USBSwitch the pack OFF before USBand before moving a wire.ONOFF124Label both packs4×AA → ESP32 only.3×AA → emitter only (5.5 V max).++++ONOFFESP32 4×AA+++ONOFFEMITTER 3×AA
Tap the diagram to open it full screen.
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

Mission 01, soldered version: perfboard layout Top view of a full-size breadboard-pattern perfboard, 157 by 51 millimetres, row 1 at the USB edge on the left, right rails at the top. Two 19-socket female headers, H1 in a1 to a19 and H2 in i1 to i19, take the ESP32, which plugs in and stays removable; its outline is dashed. J1, a 2-pole screw terminal for the ESP32 4×AA pack, plus at h25 and minus at h27. J2, a 3-pole screw terminal for the IR receiver, plus at h31, minus at h33, OUT at h35. Their openings face the right edge. H3, a 3-socket female header for the buzzer module, S at h39, plus at h40, minus at h41. R1, 220 ohms, lies flat from d26 to d30. D1, the LED, long leg in b30, short leg in b31. SW1, the button, straddles the middle gap in e44, f44, e46 and f46. Fifteen insulated wires on the top side: W1 red f1 to f25; W2 black j27 to the right minus rail; W3 red j19 to the right plus rail; W4 black j6 to the right minus rail; W5 red j31 to the plus rail; W6 black j33 to the minus rail; W7 yellow g13 to f35; W8 orange h11 to f39; W9 red j40 to the plus rail; W10 black j41 to the minus rail; W11 green g10 to row 26 (b26), the R1 strip; W12 black d31 to the left minus rail near row 34; W13 blue f9 to h44; W14 black a46 to the left minus rail; W15 black links the left minus rail to the right minus rail at row 52. Keep-outs, dashed: rows 20 to 23 for the antenna, and a 6 millimetre circle around each of the three mounting holes in the middle gap. FIG. 3 — PERFBOARD LAYOUT, TOP VIEW (SOLDERED VERSION)++−−−−++jihgfedcba1102030405060W1W2W3W4W5W6W7W8W9W10W11W12W13W14W15H2H1J1J2H3R1D1SW1antenna: rows 20–23 freeDashed outline: the ESP32 plugs into H1/H2, USB at the row-1 edge.Orange dashed circles: 6 mm keep-out around each mounting hole. Rows 20–23: antenna, keep free.Parts and wires on the top side, joints soldered from below. Solder all wires before plugging in the ESP32.PartsH1, H22 × female header 1×19a1–a19 · i1–i19J12-pole screw terminal, ESP32 4×AA+ h25 · − h27J23-pole screw terminal, receiver+ h31 · − h33 · OUT h35H3female header 1×3, buzzerS h39 · + h40 · − h41R1220 Ω, flatd26 → d30D15 mm LED, flat on the board+ b30 · − b31SW16 mm buttone44 f44 e46 f46Wires (22 AWG solid, insulated)W1f1 → f255V pin → J1 +W2j27 → − railJ1 − → GNDW3j19 → + rail3V3 railW4j6 → − railGND railW5j31 → + railreceiver +W6j33 → − railreceiver −W7g13 → f35GPIO32 → receiver OUTW8h11 → f39GPIO25 → buzzer SW9j40 → + railbuzzer +W10j41 → − railbuzzer −W11g10 → b26GPIO26 → row 26 (b26), R1 stripW12d31 → left − railLED −W13f9 → h44GPIO27 → button (f44)W14a46 → left − railbutton (e46) → GNDW15left − rail → right − railGND link, row 52Rails: + at the top = 3V3 only. The 5V line (W1, J1 +)must never touch it: check with the multimeter.Board: Perma-Proto full-size type, 157 × 51 mm. Mounting-holepositions derived from the datasheet: measure your board.
Tap the diagram to open it full screen.

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

  1. 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.

  2. Step P2 · Fit the ESP32 sockets.
  3. Step P3 · Solder the terminals and the buzzer socket.
  4. Step P4 · Solder the resistor, the LED and the button.
  5. 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 5V pin 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.

    Permanent P5: solder the power wires (W1 to W4) Top view of the perfboard, rows 1 to 30. Highlighted wires: W1 red from f1 to f25, the 5V pin to J1 plus, running in the middle gap away from the mounting hole; W2 black from j27 to the right minus rail; W3 red from j19 to the right plus rail, the 3V3 rail; W4 black from j6 to the right minus rail. W1 stays far from the plus rail. P5×422 AWG×1++−−−−++jihgfedcba1102030405060W1W2W3W4W1 (5V) goes to J1 + only, never near the + railInsulated wire, flat on top, soldered from below.

    Check: W1 goes to J1 + and nowhere near the + rail.

  6. Step P6 · Solder the receiver wires (W5 to W7).
  7. Step P7 · Solder the buzzer wires (W8 to W10).
  8. Step P8 · Solder the LED and button wires (W11 to W15).
  9. 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.

  10. 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).

    Permanent P10: multimeter checks before power-on (ask for help) Packs OFF, ESP32 not plugged in. Left: the multimeter in continuity (beep) mode, red probe in socket i1, the 5V socket, black probe on the right plus rail: it must NOT beep. Right, the key test: pack switched ON, ESP32 still unplugged, the multimeter on DC volts between the plus rail and the minus rail must read 0 volts. If it shows the pack voltage, STOP: the 5V line touches the 3V3 rail and would destroy the ESP32. P10×1++−−−−++jihgfedcba1102030405060i1 (5V)- - -))NO BEEPi1 (5V) ↔ + rail+ rail ↔ − rail: no beep tooKey testPack ON · ESP32 still unplugged0.00V+ rail ↔ − rail0 V= correctPack voltage? STOP.5V touches the 3V3 rail:it would destroy the ESP32.Switch OFF, find the bridge, fix it.

    Check: Every “no beep” is silent and every “beep” beeps.

  11. 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.

  12. Step P12 · Plug in the ESP32.

    Pack OFF. Plug the ESP32 into its sockets, USB end at row 1, pin 5V in 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.

  13. 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.

  14. 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.

    Permanent P15: put it in the box Exploded view of the 3D-printed box, seen from above at an angle, parts lifted off in assembly order. Bottom: the box, with the electronics bay in front and the battery bay behind it at the USB end; three conical standoffs on its floor, a U-shaped USB slot in the end wall with PACK OFF embossed next to it, vent slots in the battery bay wall. Above it: the soldered perfboard, ESP32 plugged into its sockets with the USB port toward the end wall, held by three M3 screws on the standoffs. Behind: the switched 4×AA pack, labelled ESP32 4×AA, lid up, switch at the USB end; its red and black leads pass through a notch in the divider into the J1 screw terminal. Above the pack: the battery hatch with a window over the pack switch and vent slots, two screws. Top: the lid with the LED window over the LED, sound holes over the buzzer and the long pusher dropping into its guide tube over the button; four screws. The box is not airtight: keep the vent slots open. The emitter and its 3×AA pack stay on the door, outside this box. P15×9M3×14×AA×1ESP32 4×AAlid: 4 screwslong pusher → buttonLED windowsound holeshatch: switch window, 2 screwspack: switch at the USB endleads → J1 (notch)board: 3 M3 screws on the standoffsUSB slot · PACK OFF firstvents: keep openNot airtight: never cover the vents

    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:

Mission 02 · Laser alarm

  • 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
  1. Adafruit, IR Break Beam Sensors guide (wiring, power, sunlight, no shared power or ground between the halves)
  2. 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)
  3. Adafruit product 830, 4×AA holder with on/off switch (voltages, dimensions, pin ends)
  4. Adafruit product 1606, Perma-Proto full-sized breadboard PCB (157 × 51 mm, mounting holes)
  5. Espressif, ESP32-DevKitC V4 schematic (regulator AMS1117-3.3, 22 µF / 10 V input capacitor, power LED)
  6. Espressif, ESP32-DevKitC V4 user guide (power options: only one at a time)
  7. Espressif, ESP32-DevKitC V4 dimensions
  8. Espressif, ESP32 datasheet (3.6 V maximum, 3.0 V minimum, deep-sleep and Wi-Fi currents, pull-up)
  9. ESP-IDF, Sleep modes (wake-up sources, RTC pull-ups)
  10. Arduino-ESP32, Deep sleep API
  11. SparkFun, How to Solder: Through-Hole Soldering (temperature, glasses, helping hands)
  12. Adafruit, Guide to Excellent Soldering (ventilation)
  13. Arduino docs, digitalRead()
  14. 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.

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.