Siddhant Kumar
Project 037 · Agriculture

Cold Storage Monitor.

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.

Intermediate 10–16 hours 37 min read Cold-chainSensorsAlerts
Jump to source Bill of materials
Cold Storage Monitor — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
10–16 hours
Indicative cost
₹3,200 – ₹4,400
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Agriculture
Last updated
28 July 2026
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.

Pallet racking in a distribution warehouse
A cold store — the monitor represents the whole room with probes at its warmest, most variable points. 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

  • 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

SettingHow it is used
Produce and food cold roomsKeeping fruit, vegetables, dairy and meat within grade-safe temperatures and proving it to buyers who reject undocumented stock.
Pharmaceutical / vaccine storageCold-chain compliance where an undocumented excursion can legally condemn an entire batch; MKT and excursion logs are mandatory.
Restaurant and retail refrigerationAutomating the manual temperature-check logs that food-safety rules require, with alarms before stock is lost.
Agri warehouses and FPO cold storesProtecting 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

AttributeValue
Difficulty levelIntermediate
Estimated completion time10–16 hours
Indicative build cost₹3,200 – ₹4,400
Primary disciplineAgriculture
Reference platformESP32 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.

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
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 ID4₹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 heater1₹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⁷ operations1₹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 out1₹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 recommended1₹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 diameter1₹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 protection1₹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 discharge1₹450
Waterproof DS18B20 probes on cable
One 1-Wire bus, addresses mapped to locations
Stainless probes for door/corner/return/in-product placement4₹1,920
Door reed switchMagnetic contact on the cold-room door1₹120
Backup battery + charger18650 + TP4056 to ride through power cuts and keep logging1₹260
IP-rated enclosure (external mount)Electronics outside the cold, only probes inside, to avoid condensation on the board1₹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

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
DS18B20 waterproof temperature probe−55 to +125 °C, ±0.5 °C from −10 to +85 °C, 9–12-bit resolution, unique 64-bit ROM ID3.0–5.5 V1-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 heater2.4–5.5 VI²C (0x44/0x45)Datasheet
Reed switch + magnet pair (door contact)NO contact, 10–15 mm operating gap, 100 V / 0.5 A, > 10⁷ operationspassiveDigital with pull-upDatasheet
DS3231 precision RTC + CR2032 backup±2 ppm (±1 min/year), temperature-compensated crystal, alarms, 32 kHz out2.3–5.5 VI²C (0x68)Datasheet
microSD card 32 GB A1 classA1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended3.3 VSDIO / SPIDatasheet
Active piezo buzzer 5 V85 dB at 10 cm, 2.3 kHz resonance, 12 mm diameter3–5 VDigital / PWMDatasheet
TP4056 Li-ion charger + DW01 protection1 A programmable CC/CV charge to 4.2 V ±1 %, over-discharge and short protection4.5–5.5 V inmicro-USB / padsDatasheet
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.
DS18B20 waterproof temperature probe3.0–5.5 V6Dozens can share one GPIO — you address them by ROM code.
SHT31-D temperature + humidity sensor2.4–5.5 V1.5The built-in heater burns off condensation — essential for outdoor or greenhouse use.
DS3231 precision RTC + CR2032 backup2.3–5.5 V0.2Vastly better than DS1307; some boards trickle-charge a non-rechargeable cell — cut that resistor.
microSD card 32 GB A1 class3.3 V100For 24/7 loggers buy a high-endurance card — normal cards die in months.
Active piezo buzzer 5 V3–5 V30Active buzzers make tone on DC; passive ones need a PWM carrier.
TP4056 Li-ion charger + DW01 protection4.5–5.5 V in1000Buy 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.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
OneWire + DallasTemperature 2.3.x / 3.9.xBus enumeration and conversion commands for DS18B20 probes.Library Manager → "DallasTemperature" (pulls OneWire)
Adafruit Unified Sensor 1.1.xCommon sensor event abstraction; a dependency of most Adafruit drivers.Library Manager → "Adafruit Unified Sensor"
ArduinoJson 7.xZero-allocation JSON serialisation and parsing.Library Manager → "ArduinoJson" by Benoit Blanchon
Preferences (NVS) bundledWear-levelled key/value storage in ESP32 flash for settings.Bundled with the ESP32 core
NTPClient / configTime bundledWall-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.

Cold Storage Monitor — system block diagramFunctional block diagram of the Cold Storage Monitor system. The roomZone tempsDS18B20 ×4HumiditySHT31Doorreed switchRecordESP32 + RTCtimestampSD logappend-onlyMKT/excursioncomputedProtectAlarmbuzzer + escalateCloud mirroroff-device copyAuditorDashboardlive + historyExportaudit trailrightrightnone
Cold Storage Monitor — 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.

Cold Storage Monitor — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBDS18B20 ×4GPIO 41-Wire zone temps(4.7 kΩ pull-up)SHT31GPIO 21/22Humidity + temp(I²C)Reed switchGPIO 27Door open/closedDS3231 RTCGPIO 21/22Timestamp source(I²C)microSDGPIO 18/19/23/5Local append-onlylogBuzzer/relayGPIO 13Local alarm outputTP4056VIN / 3V3 regBackup-batterysupplyMains 5VTP4056 INPrimary supply +charge
Cold Storage Monitor — wiring schematic
PeripheralPeripheral pinController pinSignal
DS18B20 ×4DQGPIO 41-Wire zone temps (4.7 kΩ pull-up)
SHT31SDA/SCLGPIO 21/22Humidity + temp (I²C)
Reed switchNOGPIO 27Door open/closed
DS3231 RTCSDA/SCLGPIO 21/22Timestamp source (I²C)
microSDSPIGPIO 18/19/23/5Local append-only log
Buzzer/relayINGPIO 13Local alarm output
TP4056OUTVIN / 3V3 regBackup-battery supply
Mains 5V+/–TP4056 INPrimary 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.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module timestamping and logging every zone, the humidity and every door event. 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.

Cold Storage Monitor — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · DS18B20 waterproof temperature probe ·SHT31-D temperature + humidity sensorDriver layerwifi · pubsub · onewire · unifiedApplication logicsampling loop · filtering · thresholds · state machineTransport layerWi-Fi + MQTT with escalation; local SD is the source of truth · TLS ·retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Cold Storage Monitor — architecture stack

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)

plainMean 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

plainExcursion 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

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

Cold Storage Monitor — firmware flowchartControl flow through the main program loop. Sample zones + humidity + doorTimestamp and append to logAny zone above limit?Start/continue excursion; alarmClear excursion stateStart/continue excursion;alarmDoor open too long?Door alarmUpdate MKTDoor alarmUpdate MKTMirror to cloud; wait interval
Cold Storage Monitor — 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. 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".

  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.

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

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

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

cppcold-storage-monitor.ino
/* ═══════════════════════════════════════════════════════════════
   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;
}
void logLine(Every record is appended — never overwritten — with an incrementing sequence number, so a deleted or altered line breaks the sequence and is detectable on audit.
if (z[i] > tRep) tRep = z[i]The warmest of the four zones represents the room's risk; compliance is judged against the hottest spot the product could be sitting in, not an average that hides it.
logLine(t, z, rh, doorOpen); // append-only, alwaysLogging happens whether or not the network is up, so a power cut or outage — exactly when incidents happen — never leaves a gap in the local record.
raiseAlarm("door open too long"The commonest real-world cause of an excursion, a propped or forgotten door, is alarmed proactively before the room even breaches its limit.
mqtt.publish("cold/room1/alarm"Alarms are published to a topic the server watches for escalation, so an unacknowledged 2 a.m. failure can be pushed onward to SMS or a call.

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.

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

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

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

Cold Storage Monitor — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsRoom monitorESP32 + SDOther roomsmore nodesWi-Fi 2.4 GHzRouteror cellular backupMQTT/TLS 8883Broker + compliancestoreimmutable mirrorDashboardlive + auditPhone/SMSescalation
Cold Storage Monitor — network topology

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 / endpointDirectionPayload
cold/room1/livenode → brokerper-zone temps, RH, door, MKT
cold/room1/alarmnode → brokerexcursion / door alarm for escalation
cold/room1/excursionnode → brokerexcursion 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.

TestWhat you should see
Warm the door-zone probe above T_LIMIT briefly then recoverExcursion opens and closes; logged with duration and peak; no alarm if within grace
Hold above limit past the grace periodAlarm fires locally and publishes for escalation
Open the door and leave it openDoor-open alarm after the threshold; opening logged
Pull mains powerBattery keeps the device logging locally with correct timestamps
Drop the network during an excursionLocal log continues; records sync to cloud on reconnect
Attempt to edit a past log lineSequence/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.

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

A Grafana time-series dashboard
A dashboard turns the compliance log into a live view and an exportable audit trail. Photograph sourced from Wikimedia Commons — Grafana dashboard.png. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Log looks fine but product spoiled

Likely cause. Probes clustered at the cold spot, missing the warm zones

Fix. Relocate probes to the door, top corner and product; judge compliance on the warmest zone

Timestamps wrong after a power cut

Likely cause. RTC coin cell missing/dead

Fix. Fit a fresh coin cell; re-sync from NTP; verify time survives power-off

Frequent nuisance excursion alarms

Likely cause. Grace period too short, or normal defrost cycles

Fix. Lengthen the grace period; mask known defrost windows; ensure the limit matches the product

Gaps in the record

Likely cause. Device stopped logging during an outage

Fix. Verify the backup battery carries the logger; confirm offline logging to SD is enabled

Humidity reads saturated

Likely cause. Condensation on the SHT31 in the cold, humid air

Fix. Mount the sensor to shed condensation; allow warm-up; keep electronics outside the room

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

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

  • 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

Why several probes instead of one?

A cold room varies from the cold evaporator to the warm door and corners. One probe reads the best spot and hides excursions; several placed at the warm, variable spots represent what the product actually experienced.

What is mean kinetic temperature and why not just an average?

MKT weights warm periods exponentially, because spoilage accelerates with temperature. A brief spike affects product more than a plain average implies, and MKT captures that — which is why regulated cold chains use it.

What makes the log "tamper-evident"?

It is append-only with sequence numbers (optionally hashes) and mirrored to the cloud. You can add readings but not silently rewrite them, and deleting a line breaks the sequence.

Does it keep working during a power cut?

Yes. A backup battery keeps it logging locally with correct timestamps, and it syncs the backlog to the cloud when power and network return — outages are exactly when the record matters most.

Can it control the fridge to fix an excursion?

By design it is a watchdog, not the control system. It alarms and escalates so a person or the refrigeration's own controls act; keeping it independent is what lets it honestly judge the room.

References & Learning Resources

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

  1. Mean kinetic temperature — definition and useReference
  2. Cold chain and temperature monitoring — overviewReference
  3. WHO — temperature monitoring of vaccine cold chainWHO
  4. DS18B20 1-Wire digital thermometer (datasheet)Analog Devices
  5. DS3231 extremely accurate RTC (datasheet)Analog Devices