Contents — 26 sections
Project Overview
A lockbox that records every legitimate opening and — the moment anyone tries to force, move or drill it — sounds an alarm and sends an instant, timestamped tamper alert.
A safe protects valuables in two ways: it resists physical attack, and it tells you when an attack happens. Ordinary safes do only the first, silently — if someone forces, drills or carries one off, you find out when you next open it, often long after the thief is gone. This project adds the second, missing half: a lockbox that keeps a complete access log of who opened it and when, and that detects tampering in real time — a lid forced, the body struck or drilled, the whole safe lifted and moved — sounding a local alarm and firing an instant timestamped notification so you know at the moment it matters, not the morning after.
The intelligence sits around a normal lock. Legitimate access is by keypad or card, and every successful and failed attempt is written to a tamper-evident log with a timestamp, so there is always an accountable record of openings. Tamper detection layers several sensors that together recognise attack: a lid/door contact that flags an opening that did not follow a valid unlock (i.e. it was forced), an accelerometer/vibration sensor that recognises the signatures of striking, drilling or the safe being tilted and carried, and enclosure/tamper switches that trip if the case is opened or the electronics interfered with. Fusing these distinguishes a real attack from an innocent bump, so the alarm is meaningful.
Because a determined attacker will try to cut the power or the network, the design is built to defend itself: it runs on internal battery backup so pulling the mains does not disarm it (and loss of power is itself logged and alerted), the tamper alarm sounds locally regardless of connectivity, and alerts are sent the instant tamper is detected rather than on a schedule an attacker could wait out. Everything — openings, failed attempts, tamper events, power loss — is timestamped and, where possible, mirrored off-device so the record survives even if the safe is taken. It is honest that a DIY tamper layer does not turn a lockbox into a certified burglary-rated safe — physical resistance still depends on the box itself — but it converts a silent container into one that is accountable, self-defending and, crucially, tells you the moment something is wrong.
What this project does
- Logs every legitimate opening and failed attempt with a timestamp
- Detects a forced opening (lid opened without a valid unlock)
- Recognises attack signatures — striking, drilling, tilting/carrying
- Trips on enclosure/tamper interference
- Sounds a local alarm and sends an instant tamper notification
- Runs on battery backup so cutting power does not disarm it (and logs power loss)
- Keeps a tamper-evident record, mirrored off-device where possible
Real-World Applications
| Setting | How it is used |
|---|---|
| Home / office valuables and documents | A lockbox that both controls access and alerts instantly if it is attacked or moved. |
| Cash handling / small retail | A till-safe with an access log per user and immediate tamper alerts. |
| Pharmacy / controlled-item storage | Accountable access to medicines or controlled items with a tamper trail. |
| Shared / hostel lockers | Per-user access logging and movement/forced-open detection for shared storage. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Complete, tamper-evident access log (openings + failed attempts)
- Forced-open detection: opening without a valid unlock
- Motion/vibration attack recognition (strike, drill, carry)
- Enclosure tamper and power-loss detection
- Instant local alarm + notification, not scheduled reporting
- Battery backup so power-cut attacks do not disarm it
- Honest scope: adds detection/accountability, not a burglary rating
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 12–18 hours |
| Indicative build cost | ₹3,200 – ₹5,000 (+ the lockbox) |
| Primary discipline | Security |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Access logging with a real-time clock (tamper-evident)
- Fusing contact, vibration and accelerometer signals to detect attack
- Forced-open logic (opening without a valid unlock)
- Battery-backup and power-loss detection
- Instant local + remote alerting
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 1 | ₹450 |
| 4×4 matrix membrane keypad Debounce in software — 20 ms is enough for membrane keys. | 16 keys, 8-wire matrix, 35 × 76 mm adhesive-backed | 1 | ₹70 |
| MFRC522 13.56 MHz RFID reader + card + fob Strictly 3.3 V — 5 V on the SPI pins kills the chip. | ISO/IEC 14443A, MIFARE Classic 1K, 0–60 mm range, up to 10 Mbit/s SPI | 1 | ₹180 |
| Reed switch + magnet pair (door contact) Wire it normally-closed so a cut cable reads the same as an open door — fail-safe by construction. | NO contact, 10–15 mm operating gap, 100 V / 0.5 A, > 10⁷ operations | 1 | ₹55 |
| MPU-6050 6-axis IMU Gyro bias drifts with temperature — re-zero at boot while the device is still. | 3-axis gyro ±250–2000 °/s, 3-axis accel ±2–16 g, 16-bit ADC, on-chip DMP | 1 | ₹190 |
| SW-420 vibration switch module A go/no-go switch, not a measurement — use an ADXL345 if you need amplitude or frequency. | Spring-mass normally-closed switch, adjustable sensitivity, digital out | 1 | ₹60 |
| 12 V solenoid valve (½″, normally closed) Continuous energising heats the coil — use latching valves for battery builds. | 0.02–0.8 MPa, 12 V DC, 8 W, brass body | 1 | ₹650 |
| Active piezo buzzer 5 V Active buzzers make tone on DC; passive ones need a PWM carrier. | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 1 | ₹25 |
| DS3231 precision RTC + CR2032 backup Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell — cut that resistor. | ±2 ppm (±1 min/year), temperature-compensated crystal, alarms, 32 kHz out | 1 | ₹180 |
| 18650 Li-ion cell 3400 mAh + holder Never charge below 0 °C; always use a protected cell or a BMS. | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 1 | ₹450 |
| Solenoid/motor lock + strike Fail-secure so power loss does not open it | Electric lock for the lid/door, fail-secure | 1 | ₹700 |
| Enclosure tamper switches | Micro-switches that trip if the case/electronics compartment is opened | 2 | ₹240 |
| Battery backup + charger | Internal pack so mains loss does not disarm; sensed for supervision | 1 | ₹350 |
| Backup notification path Optional but defeats a Wi-Fi-jam attack | GSM/secondary link so alerts get out even if Wi-Fi is cut | 1 | ₹700 |
Estimated total: ₹4,300, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter — continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, I²C, I²S, CAN, PWM | Datasheet |
| 4×4 matrix membrane keypad | 16 keys, 8-wire matrix, 35 × 76 mm adhesive-backed | logic level | 8 GPIO matrix scan | Datasheet |
| MFRC522 13.56 MHz RFID reader + card + fob | ISO/IEC 14443A, MIFARE Classic 1K, 0–60 mm range, up to 10 Mbit/s SPI | 2.5–3.6 V | SPI (also I²C/UART) | Datasheet |
| Reed switch + magnet pair (door contact) | NO contact, 10–15 mm operating gap, 100 V / 0.5 A, > 10⁷ operations | passive | Digital with pull-up | Datasheet |
| MPU-6050 6-axis IMU | 3-axis gyro ±250–2000 °/s, 3-axis accel ±2–16 g, 16-bit ADC, on-chip DMP | 2.375–3.46 V (module 5 V tolerant) | I²C (0x68/0x69) | Datasheet |
| SW-420 vibration switch module | Spring-mass normally-closed switch, adjustable sensitivity, digital out | 3.3–5 V | Digital | Datasheet |
| 12 V solenoid valve (½″, normally closed) | 0.02–0.8 MPa, 12 V DC, 8 W, brass body | 12 V | Relay / MOSFET + flyback diode | Datasheet |
| Active piezo buzzer 5 V | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 3–5 V | Digital / PWM | Datasheet |
| DS3231 precision RTC + CR2032 backup | ±2 ppm (±1 min/year), temperature-compensated crystal, alarms, 32 kHz out | 2.3–5.5 V | I²C (0x68) | Datasheet |
| 18650 Li-ion cell 3400 mAh + holder | 3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge | 3.0–4.2 V | Holder / spot-welded tabs | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. |
| 4×4 matrix membrane keypad | logic level | 1 | Debounce in software — 20 ms is enough for membrane keys. |
| MFRC522 13.56 MHz RFID reader + card + fob | 2.5–3.6 V | 26 | Strictly 3.3 V — 5 V on the SPI pins kills the chip. |
| MPU-6050 6-axis IMU | 2.375–3.46 V (module 5 V tolerant) | 3.9 | Gyro bias drifts with temperature — re-zero at boot while the device is still. |
| SW-420 vibration switch module | 3.3–5 V | 15 | A go/no-go switch, not a measurement — use an ADXL345 if you need amplitude or frequency. |
| 12 V solenoid valve (½″, normally closed) | 12 V | 650 | Continuous energising heats the coil — use latching valves for battery builds. |
| Active piezo buzzer 5 V | 3–5 V | 30 | Active buzzers make tone on DC; passive ones need a PWM carrier. |
| DS3231 precision RTC + CR2032 backup | 2.3–5.5 V | 0.2 | Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell — cut that resistor. |
Summed typical draw is 886.1 mA. With a 1.5× design margin the supply should deliver at least 1400 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools → Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
- Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager → "PubSubClient" by Nick O'Leary |
| MFRC522 1.4.x | SPI driver and MIFARE authentication for the RC522 reader. | Library Manager → "MFRC522" by GithubCommunity |
| MPU6050_light / Adafruit MPU6050 1.3.x | IMU register access, calibration and complementary-filter angles. | Library Manager → "MPU6050_light" by rfetick |
| NTPClient / configTime bundled | Wall-clock time from an NTP server for timestamping. | Bundled (`configTime()` on ESP32) |
| Preferences (NVS) bundled | Wear-levelled key/value storage in ESP32 flash for settings. | Bundled with the ESP32 core |
| SQLite 3.45+ | Zero-configuration embedded database for local logs. | Bundled with Python (`import sqlite3`) |
Block Diagram
The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| Keypad / RC522 | matrix / SPI | GPIO | Access credential |
| Lid reed | NC | GPIO 34 | Open/closed state |
| MPU-6050 | SDA/SCL | GPIO 21/22 | Motion/attack (I²C) |
| Vibration | DOUT | GPIO 35 | Strike/drill detection |
| Lock | IN | GPIO 26 | Actuate (fail-secure) |
| Tamper switches | NC | GPIO 27/14 | Enclosure interference |
| Buzzer/siren | IN | GPIO 13 | Local alarm |
| RTC + battery sense | I²C / ADC | GPIO 21-22 / 32 | Timestamps + power supervision |
Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- Use a fail-secure lock so a power cut cannot open the safe; run everything from a battery-backed supply so the electronics stay armed when mains is removed.
- Mount the accelerometer rigidly to the safe body so it faithfully feels strikes, drilling and tilting; place a vibration sensor for high-frequency drill/impact energy.
- Wire the lid reed so an opening is unambiguous, and cross-check it against the lock state to detect a forced open.
- Add enclosure tamper switches on the case and the electronics compartment, wired so opening either trips an alarm.
- Give the RTC coin-cell backup and sense the mains/battery so power loss is timestamped and alerted.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
The safe's premise is that a container should be accountable and self-aware, not just strong. Physical resistance — how long the box withstands a drill or a pry bar — is a property of the box's material and construction, and this project does not change it. What it adds is the two things a plain safe lacks: a record of every legitimate access, so you always know who opened it and when, and real-time detection of attack, so you learn about a break-in as it happens rather than at the next opening. Those two properties transform the safe from a passive vault into an active guardian of its contents.
Detecting attack reliably means sensor fusion, because no single sensor cleanly separates an assault from ordinary life. A lid contact alone cannot tell a normal opening from a forced one; an accelerometer alone will trip on someone bumping the shelf; a vibration sensor alone fires on a slammed door nearby. The key discriminators come from combining them with context. The most powerful is the forced-open test: if the lid contact reports the safe is open but no valid unlock preceded it, that is an attack by definition — a legitimate opening always follows an authorised credential, so an opening without one is unauthorised. Layered on top, the accelerometer recognises the signatures of specific attacks — the repetitive high-energy impacts of striking, the sustained buzz of drilling, the slow tilt-and-lift of the whole safe being carried away — and the enclosure tamper switches catch attempts to open the case or disable the electronics. Fused, these turn "something moved" into "the safe is being forced / drilled / carried", which is an alarm worth acting on.
A safe's alarm system must assume the attacker will attack the alarm itself, and the obvious move is to cut the power or the network. So the design defends those: battery backup keeps the electronics armed when the mains is pulled, and — importantly — the loss of mains is itself treated as a tamper event, logged and alerted, because an unexpected power cut to a safe is suspicious. The alarm sounds locally the instant tamper is detected, independent of any network, so jamming Wi-Fi does not buy silence. Alerts are sent immediately on detection rather than on a polling schedule an attacker could exploit, ideally over a path that a local jammer cannot easily kill (a secondary link). And because the safe might be carried off entirely, the log is mirrored off-device where possible, so the evidence survives even if the box does not.
The whole thing is bound by tamper-evident logging and honest scope. Every event — each opening, each failed code, each tamper trip, each power loss — is timestamped against a backed-up clock and appended to storage that cannot be quietly rewritten, giving both an access-accountability trail and a forensic record of any attack. And the design is candid about what it is: a detection-and-accountability layer around a lockbox, not a certified burglary- or fire-rated safe. It will not make a thin box strong. But it makes any box truthful — it records who used it, and it shouts, immediately and unmissably, the moment someone tries to attack it, which is exactly the half that ordinary safes leave out.
The maths behind it
Forced-open detection
A legitimate opening always follows a valid unlock:
forced_open = lid_open AND (time_since_valid_unlock > τ)
If the lid reports open but no authorised credential
preceded it within τ, the opening is unauthorised → alarm.
This single context test catches the core attack.
Attack-signature fusion
From accelerometer a(t) and vibration v(t):
strike : repeated high |a| impulses
drill : sustained high-frequency v energy
carry : orientation change (tilt) + low-freq motion
sustained over seconds
attack = strike OR drill OR carry OR tamper_switch
OR forced_open OR power_loss
Context + fusion separate assault from an innocent bump.
Power-loss as tamper
Battery backup keeps the safe armed; mains state is watched:
if mains_lost AND not(maintenance_mode):
log "power loss" ; raise tamper alert
An unexpected power cut to a safe is itself suspicious —
it is the classic move to disable an alarm.
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Fit the lock and arm-through-power-loss electronics
Install a fail-secure lock so power loss cannot open the safe, and run all electronics from an internal battery-backed supply so removing mains leaves it armed. Sense the mains so its loss is detectable.
Mount the detection sensors
Bolt the accelerometer rigidly to the safe body and add a vibration sensor for drill/impact energy; fit the lid reed and enclosure tamper switches on the case and the electronics compartment.
Set up access, clock, alarm and notification
Add the keypad/card reader for legitimate access, a backed-up RTC for timestamps, a loud local siren, and a notification path (ideally with a secondary link) so alerts get out even if Wi-Fi is cut.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Log legitimate access
On a valid credential, unlock and append a timestamped opening record; on a bad attempt, log the failure. Keep the log append-only and mirror it off-device.
Detect attack by fusion and context
Continuously evaluate the forced-open test, the accelerometer/vibration attack signatures, the tamper switches and power state, and raise an alarm on any of them.
cpptamper-detect.inouint32_t lastValidUnlock = 0; #define UNLOCK_GRACE_MS 8000 // opening must follow a valid unlock within this bool forcedOpen(bool lidOpen) { return lidOpen && (millis() - lastValidUnlock > UNLOCK_GRACE_MS); } // Classify accelerometer/vibration activity into attack signatures. bool attackMotion(float aMag, float vibEnergy, float tiltDeg) { static uint8_t impacts = 0; static uint32_t drillMs = 0; bool strike = aMag > 2.5f; // hard impulse (g) if (strike) impacts++; else if (impacts) impacts--; bool drilling = vibEnergy > VIB_THRESH; if (drilling) drillMs += 50; else drillMs = 0; bool carry = tiltDeg > 20.0f; // being tilted/lifted return (impacts > 4) || (drillMs > 1500) || carry; } bool tamperDetected(bool lidOpen, float aMag, float vib, float tilt, bool caseTamper, bool mainsLost) { return forcedOpen(lidOpen) || attackMotion(aMag, vib, tilt) || caseTamper || mainsLost; }return lidOpen && (millis() - lastValidUnlock > UNLOCK_GRACE_MS)The forced-open test: an opening that did not follow an authorised unlock within the grace window is unauthorised by definition, catching the core attack with simple context.if (strike) impacts++; else if (impacts) impacts--Repeated hard impulses accumulate toward a strike alarm while isolated bumps decay away, separating a real assault from an innocent knock.if (drilling) drillMs += 50; else drillMs = 0Sustained high-frequency vibration energy over time is the signature of drilling, distinct from a momentary vibration.bool carry = tiltDeg > 20.0fA sustained change in orientation means the whole safe is being tilted and carried away — an attack a stationary safe would never produce.return forcedOpen(lidOpen) || attackMotionAny one of forced-open, attack motion, case tamper, or power loss raises the alarm — fusion so no single evasion defeats detection.Alarm instantly and alert off-device
On any tamper, sound the local siren immediately, append the event to the log, and fire an instant notification over the (ideally redundant) path — never wait for a schedule.
Complete Source Code
The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.
/* ═══════════════════════════════════════════════════════════════
Smart Tamper Safe — ESP32
Logs legitimate access and detects attack in real time (forced open,
strike, drill, carry, case tamper, power loss), sounding a local
alarm and sending an instant tamper alert. Battery-backed so cutting
power does not disarm it. Adds detection/accountability, not a rating.
══════════════════════════════════════════════════════════════════ */
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <MPU6050.h>
#include <RTClib.h>
#include <Preferences.h>
#include <math.h>
#define PIN_LID 34
#define PIN_VIB 35
#define PIN_TAMPER 27
#define PIN_MAINS 32 // high when mains present
#define PIN_LOCK 26
#define PIN_SIREN 13
#define UNLOCK_GRACE_MS 8000
MPU6050 imu;
RTC_DS3231 rtc;
Preferences prefs;
WiFiClient net; PubSubClient mqtt(net);
uint32_t lastValidUnlock = 0, logSeq = 0;
bool alarmed = false;
void logEvent(const char *type, const char *detail) {
DateTime t = rtc.now();
// Append-only local record.
appendLog(logSeq++, t, type, detail);
// Instant off-device mirror/alert (redundant path if available).
char m[160];
snprintf(m, sizeof m, "{\"type\":\"%s\",\"detail\":\"%s\"}", type, detail);
mqtt.publish("safe/1/event", m);
}
void unlock(const char *who) {
lastValidUnlock = millis();
digitalWrite(PIN_LOCK, HIGH); delay(4000); digitalWrite(PIN_LOCK, LOW);
logEvent("open", who); // legitimate access logged
}
bool attackMotion() {
int16_t ax,ay,az; imu.getAcceleration(&ax,&ay,&az);
float g = 1.0f/16384.0f;
float aMag = sqrtf((ax*g)*(ax*g)+(ay*g)*(ay*g)+(az*g)*(az*g));
float tilt = acosf(constrain((az*g)/aMag,-1.0f,1.0f))*57.3f; // from vertical
bool vib = digitalRead(PIN_VIB) == HIGH;
static uint8_t impacts=0; static uint32_t drillMs=0; static float tilt0=NAN;
if (isnan(tilt0)) tilt0 = tilt;
if (aMag > 2.5f) impacts++; else if (impacts) impacts--;
if (vib) drillMs += 50; else drillMs = 0;
bool carry = fabsf(tilt - tilt0) > 20.0f;
return (impacts > 4) || (drillMs > 1500) || carry;
}
void setup() {
Serial.begin(115200);
pinMode(PIN_LID, INPUT_PULLUP);
pinMode(PIN_VIB, INPUT);
pinMode(PIN_TAMPER, INPUT_PULLUP);
pinMode(PIN_MAINS, INPUT);
pinMode(PIN_LOCK, OUTPUT);
pinMode(PIN_SIREN, OUTPUT);
Wire.begin(21,22); imu.initialize(); rtc.begin();
WiFi.begin(WIFI_SSID, WIFI_PASS);
mqtt.setServer(MQTT_HOST, 1883);
}
void loop() {
if (!mqtt.connected() && WiFi.status()==WL_CONNECTED) mqtt.connect("safe-1");
mqtt.loop();
// legitimate access (keypad/card handled elsewhere -> calls unlock())
handleAccess();
bool lidOpen = digitalRead(PIN_LID) == HIGH;
bool caseTamper = digitalRead(PIN_TAMPER) == HIGH;
bool mainsLost = digitalRead(PIN_MAINS) == LOW;
bool forced = lidOpen && (millis() - lastValidUnlock > UNLOCK_GRACE_MS);
bool tamper = forced || attackMotion() || caseTamper || mainsLost;
if (tamper && !alarmed) {
alarmed = true;
digitalWrite(PIN_SIREN, HIGH); // instant local alarm
const char *why = forced ? "forced open" :
caseTamper ? "case tamper" :
mainsLost ? "power loss" : "attack motion";
logEvent("TAMPER", why); // instant alert + log
}
if (!tamper) { alarmed = false; digitalWrite(PIN_SIREN, LOW); }
delay(50);
}
Configuration & Calibration
Configuration steps
- Set the unlock grace window, the strike/drill/tilt thresholds, and which events alert.
- Configure access credentials and the tamper-evident log (RTC/NTP, off-device mirror).
- Ensure the lock is fail-secure and the battery backup sized for the armed run-time you need.
- Configure the notification path(s), ideally with a redundant link against Wi-Fi jamming.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Attack thresholds
Tune strike/drill/tilt thresholds by simulating each attack (safely) and confirming detection, while normal handling and nearby bumps do not alarm.
Forced-open grace
Set the grace window long enough for a legitimate open after unlocking but short enough that a forced open is caught quickly.
Power/backup
Verify the safe stays armed and detects/alerts on a simulated mains cut, and that battery run-time meets your requirement.
Network Architecture & Connectivity
Communication protocol
Access and tamper events publish immediately over TLS, ideally on a redundant path so a local jam cannot silence alerts; the local siren and logging are independent of the network.
| Topic / endpoint | Direction | Payload |
|---|---|---|
safe/1/event | safe → owner | open / failed / tamper (type, detail, time) |
safe/1/status | safe → owner | armed, battery, mains, RTC health |
safe/1/cmd | owner → safe | arm/disarm, acknowledge, maintenance mode |
Message contract between the device and the broker.
Cloud platform configuration
An owner app / monitoring service keeps the access and tamper trail (mirrored off-device so it survives the safe being taken) and pushes instant tamper alerts, with a maintenance/battery view.
Dashboard setup
Access history and tamper events with timestamps, current armed/battery/mains status, and alerting on any tamper.
Mobile app integration
Instant push on any tamper (forced open, strike/drill, carry, power loss) and on repeated failed access.
Security considerations
- TLS and authenticated commands; append-only, off-device-mirrored logs.
- Redundant notification path and local alarm so jamming/power-cut cannot buy silence.
- Treat power loss and connectivity loss as suspicious events, not silent conditions.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Open with a valid credential | Unlocks; opening logged; no alarm |
| Open the lid without unlocking | Forced-open alarm + instant alert + log |
| Strike/drill the body (simulated) | Attack-motion alarm |
| Tilt and lift the safe | Carry alarm |
| Cut mains power | Stays armed on battery; power-loss tamper alert + log |
| Open the electronics compartment | Case-tamper alarm |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
The app shows an access log (openings/failed attempts) and a tamper log (forced open, strike, drill, carry, tamper, power loss), each timestamped; a tamper fires an instant alert.
{
"type": "TAMPER",
"detail": "forced open",
"seq": 512,
"time": "2026-07-27T02:41:09"
}
A forced-open event is logged and pushed instantly while the local siren sounds; legitimate openings appear as "open" events with the credential, giving both accountability and real-time attack alerts.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- Poll the detection sensors fast enough (tens of Hz) to catch a strike/drill promptly.
- Accumulate impact/vibration evidence over time to reject bumps without missing sustained attacks.
- Keep the local alarm and logging independent of the network; alert instantly on detection.
- Mirror the log off-device in near-real time so evidence is not lost with the box.
- Replace every
delay()with amillis()comparison — blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
Safety Precautions
- This adds detection and accountability, not physical burglary resistance; the box's strength is its own.
- Use a fail-secure lock and battery backup so power loss neither opens nor disarms the safe.
- Do not store the only copy of critical logs on the device that may be stolen — mirror off-device.
- For high-value or regulated storage, use a certified safe; this is an enhancement, not a certification.
- Lithium cells vent and burn when abused. Only use protected cells or a proper BMS, never charge below 0 °C, and never leave a charging pack unattended on a wooden desk.
- Moving parts pinch. Keep fingers, cables and hair out of gear trains and wheels, and always test motion with the drivetrain unloaded and the robot on blocks first.
- Motors are inductive — always fit a flyback diode across a DC coil, or use a driver that already has one, or the back-EMF spike will destroy your GPIO.
- Water and electronics: mount all boards above the maximum possible water line, use drip loops on every cable, and pressure-test plumbing before wiring anything up.
- Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Test each attack signature and the forced-open logic periodically.
- Check and replace the backup battery and RTC coin cell on schedule.
- Verify the off-device log mirror and the redundant notification path.
- Re-tune thresholds if the safe is relocated or its mounting changes.
- Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
- Log pack voltage. When resting voltage after a full charge drops below about 4.0 V, the cell is near end of life — replace it.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Add a GPS/cellular tracker so a carried-off safe can be located.
- Add a camera snapshot on tamper for evidence.
- Cryptographically sign log records for a court-defensible trail.
- Add multi-user roles and duress codes (a code that opens but silently alarms).
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- Safes and burglary ratings — overviewReference
- Tamper detection and tamper-evident designReference
- Accelerometers for shock/vibration detectionReference
- MPU-6050 accelerometer/gyro (datasheet)TDK InvenSense
- Intrusion detection principlesReference