Siddhant Kumar
Project 054 · Security

Smart Tamper Safe.

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.

Intermediate 12–18 hours 34 min read LockSensorsAlerts
Jump to source Bill of materials
Smart Tamper Safe — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
₹3,200 – ₹5,000 (+ the lockbox)
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Security
Last updated
28 July 2026
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.

Pallet racking in a distribution warehouse
A lockbox that both controls and records access and detects attack in real time. Photograph sourced from Wikimedia Commons — Warehouse racking.jpg. Reused under the licence stated on that page; please check it before republishing.

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

SettingHow it is used
Home / office valuables and documentsA lockbox that both controls access and alerts instantly if it is attacked or moved.
Cash handling / small retailA till-safe with an access log per user and immediate tamper alerts.
Pharmacy / controlled-item storageAccountable access to medicines or controlled items with a tamper trail.
Shared / hostel lockersPer-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

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build cost₹3,200 – ₹5,000 (+ the lockbox)
Primary disciplineSecurity
Reference platformESP32 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.

ComponentKey specificationQtyApprox. 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 DAC1₹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-backed1₹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 SPI1₹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⁷ operations1₹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 DMP1₹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 out1₹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 body1₹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 diameter1₹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 out1₹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 discharge1₹450
Solenoid/motor lock + strike
Fail-secure so power loss does not open it
Electric lock for the lid/door, fail-secure1₹700
Enclosure tamper switchesMicro-switches that trip if the case/electronics compartment is opened2₹240
Battery backup + chargerInternal pack so mains loss does not disarm; sensed for supervision1₹350
Backup notification path
Optional but defeats a Wi-Fi-jam attack
GSM/secondary link so alerts get out even if Wi-Fi is cut1₹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

PartSpecificationSupplyInterfaceReference
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 DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
4×4 matrix membrane keypad16 keys, 8-wire matrix, 35 × 76 mm adhesive-backedlogic level8 GPIO matrix scanDatasheet
MFRC522 13.56 MHz RFID reader + card + fobISO/IEC 14443A, MIFARE Classic 1K, 0–60 mm range, up to 10 Mbit/s SPI2.5–3.6 VSPI (also I²C/UART)Datasheet
Reed switch + magnet pair (door contact)NO contact, 10–15 mm operating gap, 100 V / 0.5 A, > 10⁷ operationspassiveDigital with pull-upDatasheet
MPU-6050 6-axis IMU3-axis gyro ±250–2000 °/s, 3-axis accel ±2–16 g, 16-bit ADC, on-chip DMP2.375–3.46 V (module 5 V tolerant)I²C (0x68/0x69)Datasheet
SW-420 vibration switch moduleSpring-mass normally-closed switch, adjustable sensitivity, digital out3.3–5 VDigitalDatasheet
12 V solenoid valve (½″, normally closed)0.02–0.8 MPa, 12 V DC, 8 W, brass body12 VRelay / MOSFET + flyback diodeDatasheet
Active piezo buzzer 5 V85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter3–5 VDigital / PWMDatasheet
DS3231 precision RTC + CR2032 backup±2 ppm (±1 min/year), temperature-compensated crystal, alarms, 32 kHz out2.3–5.5 VI²C (0x68)Datasheet
18650 Li-ion cell 3400 mAh + holder3.7 V nominal, 4.2 V full, 3400 mAh, ~12.6 Wh, 2 C discharge3.0–4.2 VHolder / spot-welded tabsDatasheet

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.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
4×4 matrix membrane keypadlogic level1Debounce in software — 20 ms is enough for membrane keys.
MFRC522 13.56 MHz RFID reader + card + fob2.5–3.6 V26Strictly 3.3 V — 5 V on the SPI pins kills the chip.
MPU-6050 6-axis IMU2.375–3.46 V (module 5 V tolerant)3.9Gyro bias drifts with temperature — re-zero at boot while the device is still.
SW-420 vibration switch module3.3–5 V15A go/no-go switch, not a measurement — use an ADXL345 if you need amplitude or frequency.
12 V solenoid valve (½″, normally closed)12 V650Continuous energising heats the coil — use latching valves for battery builds.
Active piezo buzzer 5 V3–5 V30Active buzzers make tone on DC; passive ones need a PWM carrier.
DS3231 precision RTC + CR2032 backup2.3–5.5 V0.2Vastly 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.json under 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 dialout group: sudo usermod -aG dialout $USER and 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

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
MFRC522 1.4.xSPI driver and MIFARE authentication for the RC522 reader.Library Manager → "MFRC522" by GithubCommunity
MPU6050_light / Adafruit MPU6050 1.3.xIMU register access, calibration and complementary-filter angles.Library Manager → "MPU6050_light" by rfetick
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)
Preferences (NVS) bundledWear-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.

Smart Tamper Safe — system block diagramFunctional block diagram of the Smart Tamper Safe system. AccessKeypad/cardlegitimate openLid reedopen/closedDetect attackAccelerometerstrike/tilt/carryVibrationdrill/impactTamper switchescase openedDecideESP32fuse + forced-openLogtamper-evidentRespondLocal alarminstantNotifyoff-devicerightrightnone
Smart Tamper Safe — system block diagram

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.

Smart Tamper Safe — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBKeypad / RC522GPIOAccess credentialLid reedGPIO 34Open/closed stateMPU-6050GPIO 21/22Motion/attack (I²C)VibrationGPIO 35Strike/drilldetectionLockGPIO 26Actuate(fail-secure)Tamper switchesGPIO 27/14EnclosureinterferenceBuzzer/sirenGPIO 13Local alarmRTC + battery senseGPIO 21-22 / 32Timestamps + powersupervision
Smart Tamper Safe — wiring schematic
PeripheralPeripheral pinController pinSignal
Keypad / RC522matrix / SPIGPIOAccess credential
Lid reedNCGPIO 34Open/closed state
MPU-6050SDA/SCLGPIO 21/22Motion/attack (I²C)
VibrationDOUTGPIO 35Strike/drill detection
LockINGPIO 26Actuate (fail-secure)
Tamper switchesNCGPIO 27/14Enclosure interference
Buzzer/sirenINGPIO 13Local alarm
RTC + battery senseI²C / ADCGPIO 21-22 / 32Timestamps + 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.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module fusing lid, accelerometer, vibration and tamper signals to recognise a forced open, drill or carry. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

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.

Smart Tamper Safe — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · MFRC522 13.56 MHz RFID reader + card +fob · MPU-6050 6-axis IMUDriver layerwifi · pubsub · mfrc522 · mpuApplication logicsampling loop · filtering · thresholds · state machineTransport layerWi-Fi + MQTT (+ redundant link) → owner/monitoring · TLS · retry andbackoffPresentation layerdashboard · mobile notifications · historical charts
Smart Tamper Safe — architecture stack

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

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

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

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

Smart Tamper Safe — firmware flowchartControl flow through the main program loop. Armed / idleValid unlock?Unlock; log openingCheck for attackUnlock; log openingCheck for attackLid opened w/o unlock, orstrike/tilt/tamper/power-loss?Alarm + instant alert + logArmed / idleAlarm + instant alert + logRelock; re-arm
Smart Tamper Safe — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

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

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

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

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

  2. 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.ino
    uint32_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.
  3. 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.

cppsmart-tamper-safe.ino
/* ═══════════════════════════════════════════════════════════════
   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);
}
void unlock(const char *who)A legitimate opening records the time of the valid unlock and logs the access — this timestamp is what the forced-open test measures against.
bool forced = lidOpen && (millis() - lastValidUnlock > UNLOCK_GRACE_MS)The lid opening without a recent authorised unlock is a forced entry — the single most decisive attack signal.
bool carry = fabsf(tilt - tilt0) > 20.0fA sustained change from the safe's resting orientation means it is being tilted and carried off, a motion a static safe never makes.
bool mainsLost = digitalRead(PIN_MAINS) == LOWLoss of mains is treated as a tamper condition, because the battery keeps the safe armed and an unexpected power cut to a safe is itself suspicious.
digitalWrite(PIN_SIREN, HIGH); // instant local alarmThe siren sounds locally the instant tamper is detected, independent of any network, so jamming connectivity does not buy the attacker silence.

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.

  1. Attack thresholds

    Tune strike/drill/tilt thresholds by simulating each attack (safely) and confirming detection, while normal handling and nearby bumps do not alarm.

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

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

Smart Tamper Safe — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsSmart safeESP32Backup linkGSM optionalWi-Fi 2.4 GHzRouter / GSMredundant pathMQTT/TLSOwner app / monitoraccess + tamper logsOwnerinstant alertsMonitoraudit trail
Smart Tamper Safe — network topology

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 / endpointDirectionPayload
safe/1/eventsafe → owneropen / failed / tamper (type, detail, time)
safe/1/statussafe → ownerarmed, battery, mains, RTC health
safe/1/cmdowner → safearm/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.

TestWhat you should see
Open with a valid credentialUnlocks; opening logged; no alarm
Open the lid without unlockingForced-open alarm + instant alert + log
Strike/drill the body (simulated)Attack-motion alarm
Tilt and lift the safeCarry alarm
Cut mains powerStays armed on battery; power-loss tamper alert + log
Open the electronics compartmentCase-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.

jsonsafe-event.json
{
  "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.

A small monochrome OLED display module
Every opening and every tamper is timestamped and pushed instantly, with a local siren independent of power and network. Photograph sourced from Wikimedia Commons — OLED display module.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Nuisance alarms from bumps

Likely cause. Thresholds too sensitive / single-sensor triggering

Fix. Require accumulated impacts / sustained energy; fuse with context; raise thresholds

Real attack missed

Likely cause. Thresholds too high or sensor not rigidly mounted

Fix. Mount the accelerometer solidly; lower thresholds; validate each attack signature

Disarmed by pulling the plug

Likely cause. No battery backup / not fail-secure

Fix. Add battery backup and a fail-secure lock; treat power loss as tamper

Alerts blocked by Wi-Fi jam

Likely cause. Single network path

Fix. Add a secondary link; sound the local alarm regardless; alert instantly

Log lost when safe taken

Likely cause. Only stored on-device

Fix. Mirror the log off-device so the record survives loss of the box

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

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 a millis() 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_t where 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

Does this make my box burglar-proof?

No — it adds detection and accountability, not physical resistance. It records every opening and alarms instantly on attack, but how long the box withstands a drill is down to the box itself.

How does it know an opening was forced?

A legitimate opening always follows a valid unlock. If the lid opens without an authorised credential just before it, that opening is unauthorised by definition — the core attack signal.

What stops a thief just unplugging it?

Battery backup keeps it armed, the loss of mains is itself logged and alerted as a tamper event, and the local siren sounds regardless of power or network.

What if they carry the whole safe away?

The accelerometer detects the tilt-and-lift of being carried and alarms, and the log is mirrored off-device so the record survives even if the box is taken; a GPS option can help locate it.

Won't it false-alarm on normal handling?

It fuses several sensors with context — accumulating impacts, sustained drill energy, sustained tilt — so a single bump does not trip it while a genuine, persistent attack does.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. Safes and burglary ratings — overviewReference
  2. Tamper detection and tamper-evident designReference
  3. Accelerometers for shock/vibration detectionReference
  4. MPU-6050 accelerometer/gyro (datasheet)TDK InvenSense
  5. Intrusion detection principlesReference