Contents — 26 sections
Project Overview
Keeps produce and perishables inside their safe temperature band and keeps a tamper-evident compliance log that proves it — with alarms the moment anything drifts.
Cold storage is a promise: that everything inside stayed within a safe temperature band from the moment it went in until the moment it came out. Break that promise for even a few hours — a door left ajar, a compressor that quietly failed overnight, a sensor no one was watching — and a room full of produce, dairy, vaccines or frozen goods can be spoiled or, worse, made unsafe while still looking fine. And in regulated cold chains, being able to prove the temperature never strayed is as important as the temperature itself: without a trustworthy log, a buyer or an inspector must assume the worst. This monitor does both jobs — it watches the room and keeps the record.
Several temperature probes are placed where the room is actually at risk — near the door, in the warmest corner, at the return air, and among the product — because a single sensor by the evaporator reads the coldest, most flattering spot and misses the excursions that matter. A humidity sensor tracks the condition that governs how fast produce dehydrates or how readily frost forms. A door sensor logs every opening, since the door is the single biggest source of warm, moist air and most excursions begin with it. The controller timestamps everything against a real-time clock, writes it to local storage that cannot be quietly edited, and mirrors it to the cloud so the record survives even if the device is later tampered with.
On top of the raw log sit the two numbers a cold chain lives by: excursions (any time-above-limit event, with its duration and peak) and mean kinetic temperature, a way of summarising a fluctuating temperature history into the single effective temperature the product experienced — the metric regulators use precisely because a brief warm spike is not the same as a steady warm room. Alarms fire the instant the band is breached or the door stays open too long, escalating if no one responds, so a failure at 2 a.m. wakes someone instead of thawing the stock. The result is a cold room that protects its contents and defends its own paperwork.
What this project does
- Monitors temperature at several points in the room, not just the coldest spot
- Tracks humidity and logs every door opening with its duration
- Timestamps all readings against a real-time clock and writes a tamper-evident local log
- Mirrors the log to the cloud so the record survives device tampering
- Detects excursions (time-above-limit) with duration and peak, and computes mean kinetic temperature
- Alarms immediately on band breach or door-open-too-long, with escalation
- Rides through power and network outages on battery and local storage
Real-World Applications
| Setting | How it is used |
|---|---|
| Produce and food cold rooms | Keeping fruit, vegetables, dairy and meat within grade-safe temperatures and proving it to buyers who reject undocumented stock. |
| Pharmaceutical / vaccine storage | Cold-chain compliance where an undocumented excursion can legally condemn an entire batch; MKT and excursion logs are mandatory. |
| Restaurant and retail refrigeration | Automating the manual temperature-check logs that food-safety rules require, with alarms before stock is lost. |
| Agri warehouses and FPO cold stores | Protecting aggregated produce and settling disputes with an objective record of storage conditions. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Multi-zone sensing that catches the warm corners a single probe misses
- Door-event logging — the root cause of most excursions
- Tamper-evident, timestamped compliance log (local + cloud mirror)
- Mean kinetic temperature and excursion reporting for regulated cold chains
- Escalating alarms so a 2 a.m. failure actually reaches someone
- Battery + local logging ride-through for power and network outages
- Exportable audit trail for buyers and inspectors
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Intermediate |
| Estimated completion time | 10–16 hours |
| Indicative build cost | ₹3,200 – ₹4,400 |
| Primary discipline | Agriculture |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Placing multiple temperature probes to represent a room, not a point
- Using a real-time clock and writing timestamped, append-only logs to SD/flash
- Reed-switch door sensing and event logging
- Computing excursions and mean kinetic temperature
- Designing escalating alarms and outage ride-through
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 |
| DS18B20 waterproof temperature probe Dozens can share one GPIO — you address them by ROM code. | −55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID | 4 | ₹640 |
| SHT31-D temperature + humidity sensor The built-in heater burns off condensation — essential for outdoor or greenhouse use. | −40 to +125 °C ±0.2 °C, 0–100 %RH ±2 %, 1 Hz–10 Hz, on-chip heater | 1 | ₹620 |
| 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 |
| 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 |
| microSD card 32 GB A1 class For 24/7 loggers buy a high-endurance card — normal cards die in months. | A1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended | 1 | ₹450 |
| 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 |
| TP4056 Li-ion charger + DW01 protection Buy the version *with* protection ICs — the bare charger will over-discharge your cell. | 1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection | 1 | ₹45 |
| 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 |
| Waterproof DS18B20 probes on cable One 1-Wire bus, addresses mapped to locations | Stainless probes for door/corner/return/in-product placement | 4 | ₹1,920 |
| Door reed switch | Magnetic contact on the cold-room door | 1 | ₹120 |
| Backup battery + charger | 18650 + TP4056 to ride through power cuts and keep logging | 1 | ₹260 |
| IP-rated enclosure (external mount) | Electronics outside the cold, only probes inside, to avoid condensation on the board | 1 | ₹400 |
Estimated total: ₹5,615, 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 |
| DS18B20 waterproof temperature probe | −55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID | 3.0–5.5 V | 1-Wire (multi-drop) | Datasheet |
| SHT31-D temperature + humidity sensor | −40 to +125 °C ±0.2 °C, 0–100 %RH ±2 %, 1 Hz–10 Hz, on-chip heater | 2.4–5.5 V | I²C (0x44/0x45) | 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 |
| 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 |
| microSD card 32 GB A1 class | A1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended | 3.3 V | SDIO / SPI | Datasheet |
| Active piezo buzzer 5 V | 85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter | 3–5 V | Digital / PWM | Datasheet |
| TP4056 Li-ion charger + DW01 protection | 1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection | 4.5–5.5 V in | micro-USB / pads | 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. |
| DS18B20 waterproof temperature probe | 3.0–5.5 V | 6 | Dozens can share one GPIO — you address them by ROM code. |
| SHT31-D temperature + humidity sensor | 2.4–5.5 V | 1.5 | The built-in heater burns off condensation — essential for outdoor or greenhouse use. |
| 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. |
| microSD card 32 GB A1 class | 3.3 V | 100 | For 24/7 loggers buy a high-endurance card — normal cards die in months. |
| Active piezo buzzer 5 V | 3–5 V | 30 | Active buzzers make tone on DC; passive ones need a PWM carrier. |
| TP4056 Li-ion charger + DW01 protection | 4.5–5.5 V in | 1000 | Buy the version *with* protection ICs — the bare charger will over-discharge your cell. |
Summed typical draw is 1297.7 mA. With a 1.5× design margin the supply should deliver at least 2000 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 |
| OneWire + DallasTemperature 2.3.x / 3.9.x | Bus enumeration and conversion commands for DS18B20 probes. | Library Manager → "DallasTemperature" (pulls OneWire) |
| Adafruit Unified Sensor 1.1.x | Common sensor event abstraction; a dependency of most Adafruit drivers. | Library Manager → "Adafruit Unified Sensor" |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager → "ArduinoJson" by Benoit Blanchon |
| Preferences (NVS) bundled | Wear-levelled key/value storage in ESP32 flash for settings. | Bundled with the ESP32 core |
| NTPClient / configTime bundled | Wall-clock time from an NTP server for timestamping. | Bundled (`configTime()` on ESP32) |
| 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 |
|---|---|---|---|
| DS18B20 ×4 | DQ | GPIO 4 | 1-Wire zone temps (4.7 kΩ pull-up) |
| SHT31 | SDA/SCL | GPIO 21/22 | Humidity + temp (I²C) |
| Reed switch | NO | GPIO 27 | Door open/closed |
| DS3231 RTC | SDA/SCL | GPIO 21/22 | Timestamp source (I²C) |
| microSD | SPI | GPIO 18/19/23/5 | Local append-only log |
| Buzzer/relay | IN | GPIO 13 | Local alarm output |
| TP4056 | OUT | VIN / 3V3 reg | Backup-battery supply |
| Mains 5V | +/– | TP4056 IN | Primary supply + charge |
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
- Mount the electronics box outside the cold room. Only the probes and the reed switch go into the cold; a circuit board in a cold, humid room grows condensation and corrodes.
- Run the four DS18B20 probes on one 1-Wire bus with a single 4.7 kΩ pull-up, and map each address to its physical location (door, corner, return, in-product).
- Wire the reed switch so a door opening is unambiguous; debounce it in firmware to log clean open/close events.
- Give the RTC a coin-cell backup so timestamps survive power loss — a compliance log with wrong times is worthless.
- Power from mains with the 18650 as automatic backup, so a power cut does not create a gap in the record.
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
A cold room is not one temperature — it is a field of temperatures, coldest at the evaporator and warmest near the door and the ceiling corners, and it changes every time the door opens or the compressor cycles. A single probe by the cooling coil reads the best-case number and will happily show "all fine" while product near the door sits above its safe limit. Representing the room honestly means several probes placed deliberately at the worst spots — the door, the far top corner, the return air, and within the product mass where thermal inertia matters — so the log reflects what the goods actually experienced, not the flattering minimum.
The door is the villain in most cold-chain stories. Every opening dumps warm, humid air into the room; frequent or prolonged openings are the commonest cause of excursions and of frost and dehydration problems. Logging door events — when, and for how long — both explains excursions after the fact and lets the monitor alarm proactively when a door has been left open past a sensible threshold, catching the classic "someone propped it open and forgot" failure before it spoils anything.
Two derived numbers turn a raw temperature stream into compliance evidence. An excursion is any continuous period above the safe limit, characterised by its start, duration and peak — because regulators and buyers care about how far and how long, not merely that it happened once. Mean kinetic temperature (MKT) collapses a fluctuating history into the single effective temperature the product experienced, weighting warm periods more heavily than a plain average because degradation accelerates with temperature (an Arrhenius relationship). MKT is the standard cold-chain summary precisely because it answers the real question — "given all the ups and downs, what effective temperature did this batch see?" — better than a min/max or an average can.
The record is only worth keeping if it is trustworthy. That means append-only local storage (you can add readings, not silently rewrite history), timestamps from a backed-up real-time clock, and an off-device mirror to the cloud so that even if the local device is lost or tampered with, the evidence survives. And because power and network both fail exactly when you most need the record — during the incident — the monitor runs on a backup battery and keeps logging locally through outages, syncing the backlog when connectivity returns. A compliance monitor that goes blind during a power cut is blind during the very events it exists to document.
The maths behind it
Mean kinetic temperature (Arrhenius-weighted)
MKT summarises a varying temperature history:
MKT = (ΔH/R) / −ln[ (Σ e^(−ΔH/(R·T_i))) / n ]
T_i are absolute temperatures (K) of each interval,
ΔH ≈ 83 kJ/mol (typical activation energy),
R = 8.314 J/mol·K, n = number of intervals.
Warm periods dominate the average far more than in a plain
mean — which is the point: degradation is exponential in T.
Excursion detection
For the representative zone temperature T_rep
(usually the warmest logged zone):
in_excursion while T_rep > T_limit
duration = t_end − t_start, peak = max T_rep in window
Alarm when duration exceeds a grace period (e.g. product
can tolerate a short spike but not a sustained breach).
Log every excursion's start, end, duration and peak.
Door-open alarm
From the reed switch:
open_duration = now − door_opened_at
alarm if door open and open_duration > T_door (e.g. 120 s)
Also count openings per hour; an unusually high rate warns
of a propped door or heavy traffic driving up the room temp.
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.
Place the probes where the room is at risk
Put one probe just inside the door (the warmest, most variable spot), one in the far top corner, one at the evaporator return air, and one inserted into or among the product to capture its thermal inertia.
Run all four on a single 1-Wire cable and record which address is where — the log must say "door zone", not "sensor 2".
Fit the door sensor and mount electronics outside
Install the reed switch and magnet on the door and frame so an opening is cleanly detected. Route its cable out through a gland.
Mount the ESP32/SD/RTC box outside the cold room to avoid condensation on the board; only sensor cables cross the wall.
Set up logging, clock and backup power
Insert the microSD and confirm the RTC holds the correct time with its coin cell in. Wire mains power with the 18650 as automatic backup so logging never stops.
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.
Establish trusted time and the log format
Sync the RTC (from NTP when online) and define an append-only log record: timestamp, each zone temperature, humidity, door state, and any active excursion. Never rewrite past records.
Compute excursions and MKT continuously
Track the warmest representative zone against the limit to open/close excursions, and fold every interval into the MKT accumulator so the effective temperature is always current.
cppcompliance.ino// Running mean kinetic temperature accumulator (Arrhenius-weighted). struct MKT { double sumExp = 0; uint32_t n = 0; }; const double DH_R = 83000.0 / 8.314; // ΔH/R in kelvin void mktAdd(MKT &m, float tempC) { double Tk = tempC + 273.15; m.sumExp += exp(-DH_R / Tk); m.n++; } float mktValue(const MKT &m) { if (m.n == 0) return NAN; double denom = -log(m.sumExp / m.n); return (float)(DH_R / denom - 273.15); } // Excursion state machine on the warmest representative zone. struct Excursion { bool active = false; uint32_t start = 0; float peak = -99; }; void excursionUpdate(Excursion &e, float tRep, float limit, uint32_t now, uint32_t grace) { if (tRep > limit) { if (!e.active) { e.active = true; e.start = now; e.peak = tRep; } if (tRep > e.peak) e.peak = tRep; if (now - e.start > grace) raiseAlarm("Temperature excursion", tRep, e.peak); } else if (e.active) { logExcursion(e.start, now, e.peak); // record start/end/duration/peak e.active = false; e.peak = -99; } }const double DH_RPre-computes the activation-energy-over-gas-constant term, the constant that makes MKT weight warm intervals exponentially more than cool ones.m.sumExp += exp(-DH_R / Tk)Each interval's absolute temperature is folded into a running sum of Arrhenius weights, so MKT can be read out at any time without storing the whole history.if (!e.active)An excursion opens the moment the representative zone crosses the limit, capturing its start time and tracking the peak as it develops.if (now - e.start > grace)A brief spike within the product's tolerance does not alarm; only a breach sustained past the grace period does — matching how cold-chain limits actually work.logExcursion(When the temperature recovers, the full excursion — start, end, duration, peak — is written to the compliance log as a discrete, auditable event.Alarm, escalate, and mirror
Sound the local alarm on an excursion or door-open-too-long; escalate to phone/SMS if unacknowledged. Mirror each record to the cloud, and when offline, queue records on the SD and sync the backlog on reconnect.
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.
/* ═══════════════════════════════════════════════════════════════
Cold Storage Monitor — ESP32, multi-zone temp, door, RTC, SD, cloud
Watches several zones of a cold room, logs a timestamped
append-only compliance record locally and to the cloud, computes
excursions and mean kinetic temperature, and alarms with escalation.
Rides through power/network outages on battery + SD.
══════════════════════════════════════════════════════════════════ */
#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <Adafruit_SHT31.h>
#include <RTClib.h>
#include <SD.h>
#include <SPI.h>
#include <math.h>
#define OW_PIN 4
#define PIN_DOOR 27
#define PIN_ALARM 13
#define SD_CS 5
#define NUM_ZONES 4
#define T_LIMIT 4.0f // safe upper limit (chilled produce example)
#define GRACE_MS 300000UL // 5 min sustained breach before alarm
#define DOOR_MS 120000UL // door open > 2 min alarms
#define LOG_MS 60000UL // log once a minute
OneWire ow(OW_PIN);
DallasTemperature zones(&ow);
Adafruit_SHT31 sht;
RTC_DS3231 rtc;
WiFiClient net;
PubSubClient mqtt(net);
const char *zoneName[NUM_ZONES] = {"door","corner","return","product"};
struct MKT { double sumExp = 0; uint32_t n = 0; } mkt;
const double DH_R = 83000.0 / 8.314;
struct Excursion { bool active=false; uint32_t start=0; float peak=-99; } exc;
uint32_t doorOpenedAt = 0, lastLog = 0, seq = 0;
bool alarmActive = false, alarmAck = false;
void mktAdd(float t) { mkt.sumExp += exp(-DH_R / (t + 273.15)); mkt.n++; }
float mktValue() { return mkt.n ? (float)(DH_R / -log(mkt.sumExp/mkt.n) - 273.15) : NAN; }
// Append-only log line with a sequence number for tamper detection.
void logLine(DateTime t, float *z, float rh, bool doorOpen) {
File f = SD.open("/coldlog.csv", FILE_APPEND);
if (!f) return;
f.printf("%lu,%04d-%02d-%02d %02d:%02d:%02d",
(unsigned long)seq++, t.year(), t.month(), t.day(),
t.hour(), t.minute(), t.second());
for (int i = 0; i < NUM_ZONES; i++) f.printf(",%.2f", z[i]);
f.printf(",%.1f,%d,%.2f,%d\n", rh, doorOpen ? 1 : 0, mktValue(),
exc.active ? 1 : 0);
f.close();
}
void raiseAlarm(const char *why, float v, float peak) {
digitalWrite(PIN_ALARM, HIGH);
alarmActive = true;
char msg[160];
snprintf(msg, sizeof msg,
"{\"alarm\":\"%s\",\"val\":%.2f,\"peak\":%.2f}", why, v, peak);
mqtt.publish("cold/room1/alarm", msg); // triggers escalation server-side
}
void publishLive(float *z, float rh, bool doorOpen) {
char b[240];
int n = snprintf(b, sizeof b,
"{\"mkt\":%.2f,\"rh\":%.1f,\"door\":%d,\"exc\":%d",
mktValue(), rh, doorOpen ? 1 : 0, exc.active ? 1 : 0);
for (int i = 0; i < NUM_ZONES; i++)
n += snprintf(b+n, sizeof b-n, ",\"%s\":%.2f", zoneName[i], z[i]);
snprintf(b+n, sizeof b-n, "}");
mqtt.publish("cold/room1/live", b);
}
void setup() {
Serial.begin(115200);
pinMode(PIN_DOOR, INPUT_PULLUP);
pinMode(PIN_ALARM, OUTPUT);
zones.begin();
Wire.begin(21, 22);
sht.begin(0x44);
rtc.begin();
SD.begin(SD_CS);
WiFi.begin(WIFI_SSID, WIFI_PASS);
mqtt.setServer(MQTT_HOST, 1883);
}
void loop() {
if (!mqtt.connected() && WiFi.status() == WL_CONNECTED) mqtt.connect("cold-1");
mqtt.loop();
uint32_t now = millis();
bool doorOpen = digitalRead(PIN_DOOR) == LOW;
if (doorOpen && doorOpenedAt == 0) doorOpenedAt = now;
if (!doorOpen) doorOpenedAt = 0;
if (now - lastLog >= LOG_MS) {
lastLog = now;
zones.requestTemperatures();
float z[NUM_ZONES], tRep = -99;
for (int i = 0; i < NUM_ZONES; i++) {
z[i] = zones.getTempCByIndex(i);
if (z[i] > tRep) tRep = z[i]; // warmest zone represents risk
}
float rh = sht.readHumidity();
DateTime t = rtc.now();
mktAdd(tRep);
logLine(t, z, rh, doorOpen); // append-only, always (even offline)
if (WiFi.status() == WL_CONNECTED) publishLive(z, rh, doorOpen);
// excursion state machine
if (tRep > T_LIMIT) {
if (!exc.active) { exc.active = true; exc.start = now; exc.peak = tRep; }
if (tRep > exc.peak) exc.peak = tRep;
if (now - exc.start > GRACE_MS && !alarmActive)
raiseAlarm("temp excursion", tRep, exc.peak);
} else if (exc.active) {
char m[120];
snprintf(m, sizeof m,
"{\"exc_end\":1,\"peak\":%.2f,\"dur_s\":%lu}",
exc.peak, (unsigned long)((now - exc.start)/1000));
mqtt.publish("cold/room1/excursion", m);
exc.active = false; exc.peak = -99;
if (!doorAlarmActive()) { digitalWrite(PIN_ALARM, LOW); alarmActive = false; }
}
}
if (doorOpenedAt && now - doorOpenedAt > DOOR_MS)
raiseAlarm("door open too long", (now - doorOpenedAt)/1000.0f, 0);
delay(1000);
}
bool doorAlarmActive() {
return doorOpenedAt && millis() - doorOpenedAt > DOOR_MS;
}
Configuration & Calibration
Configuration steps
- Set T_LIMIT (and, if needed, a low limit for frozen goods) to the product's safe band, and the excursion grace period to its tolerance.
- Map each DS18B20 address to its zone name so the log and alarms are human-readable.
- Set the door-open alarm time and the escalation policy (who is notified, and after how long unacknowledged).
- Configure the cloud endpoint and the offline-backlog sync so outage records are uploaded on reconnect.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Probe agreement
Before installing, bundle all probes in an ice-water bath (0 °C) and a known reference; record and correct any per-probe offset so zone comparisons are fair.
Clock accuracy
Sync the RTC to NTP and confirm it holds time on the coin cell through a power-off. Compliance timestamps must be right.
Excursion timing
Verify with a controlled warm-up that an excursion opens at the limit, the grace period behaves, and the logged duration/peak match reality.
Network Architecture & Connectivity
Communication protocol
Live readings publish once a minute; alarms and excursion start/end publish immediately. The local append-only SD log is the authoritative record, and the cloud is a mirror plus escalation engine — so losing the network degrades visibility, not the evidence.
| Topic / endpoint | Direction | Payload |
|---|---|---|
cold/room1/live | node → broker | per-zone temps, RH, door, MKT |
cold/room1/alarm | node → broker | excursion / door alarm for escalation |
cold/room1/excursion | node → broker | excursion end: duration + peak |
Message contract between the device and the broker.
Cloud platform configuration
A broker feeds an immutable compliance store that mirrors every record and drives escalation — if an alarm is not acknowledged within a set time it is pushed onward to SMS or a phone call, so a failure reaches a human even at night.
Dashboard setup
Live per-zone tiles, an MKT readout, and a timeline of door events and excursions; an export button produces the timestamped audit trail buyers and inspectors require.
Mobile app integration
Escalating push/SMS alerts for excursions and door-open-too-long, with acknowledgement so the system knows a human is handling it.
Security considerations
- Use TLS to the broker and an append-only, sequence-numbered log so records cannot be silently altered.
- Mirror off-device so tampering with the local unit does not erase the evidence.
- Authenticate acknowledgements so only authorised staff can silence an alarm.
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 |
|---|---|
| Warm the door-zone probe above T_LIMIT briefly then recover | Excursion opens and closes; logged with duration and peak; no alarm if within grace |
| Hold above limit past the grace period | Alarm fires locally and publishes for escalation |
| Open the door and leave it open | Door-open alarm after the threshold; opening logged |
| Pull mains power | Battery keeps the device logging locally with correct timestamps |
| Drop the network during an excursion | Local log continues; records sync to cloud on reconnect |
| Attempt to edit a past log line | Sequence/hash break makes the tampering detectable on audit |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
The dashboard shows each zone's live temperature, the room humidity, door state, the current MKT, and a timeline of excursions and door events; an export produces the audit trail.
seq,timestamp,door,corner,return,product,rh,door_open,mkt,exc
10432,2026-07-27 02:14:00,3.6,3.9,2.1,3.2,86,0,3.1,0
10433,2026-07-27 02:15:00,5.8,4.2,2.2,3.4,88,1,3.2,1
10434,2026-07-27 02:16:00,6.9,4.6,2.3,3.6,90,1,3.4,1
... excursion: start 02:15, peak 6.9C, cause: door open 3m
The record shows a door left open at 02:15 driving the door-zone above the 4 °C limit — the door event, the excursion and the rising MKT all captured and linked.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- A one-minute log cadence is ample for a slow thermal mass; publish alarms and excursion edges immediately.
- Keep the SD log append-only and rotate by day/month rather than rewriting, to stay fast and tamper-evident.
- Compute MKT incrementally (running sum) so the effective temperature is always available without reprocessing history.
- Ride outages on the battery and local SD; sync the backlog in batches on reconnect rather than blocking on the network.
- 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
- The monitor is an independent watchdog; it does not control the refrigeration and must not be relied on to keep the room cold.
- For regulated cold chains (e.g. pharma), validate probe placement, calibration and MKT settings against the applicable standard.
- Keep electronics and the lithium backup outside the cold, humid room to prevent condensation faults.
- Test the alarm and escalation path regularly — an alarm no one receives is no protection.
- 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.
- 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
- Periodically re-verify probe calibration in an ice bath and against a reference.
- Replace the RTC coin cell on schedule so timestamps never drift.
- Check the door reed switch and magnet alignment; a mis-sensed door corrupts the event log.
- Confirm the cloud mirror and backlog sync are current, and export/archive the audit trail per your retention policy.
- Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
- Rotate the microSD card annually and keep an image of the working system. Cards used as loggers wear out silently.
- 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 power-quality logging so a compressor failure is distinguished from a mains outage.
- Predict compressor decline from slowly rising pull-down times and warn before it fails.
- Add CO₂/ethylene sensing for controlled-atmosphere produce storage.
- Sign each record cryptographically for a stronger, court-defensible audit trail.
- 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.