Siddhant Kumar
Project 089 · Automotive

Cold-Chain Truck Monitor.

Guards refrigerated cargo in transit — logging temperature the whole journey, alerting the instant it drifts, and proving the cold chain never broke.

Intermediate 12–18 hours 28 min read Cold-chainGPSSensors
Jump to source Bill of materials
Cold-Chain Truck Monitor — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Intermediate
Build time
12–18 hours
Indicative cost
₹3,000 – ₹5,000 per vehicle
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Automotive
Last updated
28 July 2026
Contents — 26 sections

Project Overview

Guards refrigerated cargo in transit — logging temperature the whole journey, alerting the instant it drifts, and proving the cold chain never broke.

A refrigerated truck carries cargo whose entire value depends on staying cold — vaccines, food, pharmaceuticals — and a single unnoticed excursion can spoil a whole load or, worse, render medicine unsafe while it still looks fine. The danger is that a temperature breach in transit is silent: a failing reefer unit, a door left ajar, or a hot-day soak can push cargo out of range for hours with no one aware until delivery, when the damage is already done. This project builds a cold-chain monitor that rides with the load, continuously logs temperature, alerts the instant it drifts out of range, and produces the tamper-evident record that proves the cold chain held.

The system places temperature sensors in the cargo space (and, where it matters, at multiple points, since a trailer is not uniform), reads them continuously, and does three things. It logs every reading with a timestamp and location (GPS), building the complete journey record. It alerts — over cellular — the moment temperature leaves the safe band, so a problem is caught in transit while there is still time to act (fix the reefer, reroute, prioritise the load), not discovered at the door. And it retains the log locally even without signal, so the record is never lost.

The value is threefold: protect the cargo (catch excursions in time to act), prove compliance (an auditable temperature-vs-time record for food-safety and pharmaceutical regulations), and assign accountability (know exactly when and where a breach happened). It is honest that cold-chain compliance is a regulated domain with validated equipment requirements, that sensor placement and calibration are critical, and that the record must be trustworthy to be worth anything. But as a journey-long, alerting, location-stamped cold-chain logger, it turns the silent, expensive risk of a broken cold chain into an early warning and a defensible proof.

The dashboard of a modern car
A cold-chain monitor rides with refrigerated cargo, logging temperature the whole journey and alerting the instant it drifts. Photograph sourced from Wikimedia Commons — Car dashboard.jpg. Reused under the licence stated on that page; please check it before republishing.

What this project does

  • Continuously logs cargo temperature with time and location
  • Alerts the instant temperature leaves the safe band
  • Monitors multiple points (a trailer is not uniform)
  • Retains the log locally even without signal
  • Records door-open and reefer events where available
  • Provides an auditable temperature-vs-time compliance record
  • Assigns accountability — when and where a breach occurred

Real-World Applications

SettingHow it is used
Food cold chainChilled/frozen food kept in range from depot to delivery, with proof.
Pharma / vaccine transportRegulated temperature control and auditable records for medicines.
Reefer fleet managementLive visibility and alerting across refrigerated vehicles.
Dispute / claims evidenceWhen and where a breach occurred, for accountability and claims.

Deployment contexts where a build of this kind earns its keep.

Features & Capabilities

  • Journey-long temperature logging (time + GPS)
  • Immediate out-of-range alerting over cellular
  • Multi-point sensing across the cargo space
  • Offline-safe local logging (never lose the record)
  • Excursion detection (duration + severity)
  • Auditable compliance report
  • Honest about regulated cold-chain and calibration requirements

Difficulty, Time & Required Skills

AttributeValue
Difficulty levelIntermediate
Estimated completion time12–18 hours
Indicative build cost₹3,000 – ₹5,000 per vehicle
Primary disciplineAutomotive
Reference platformESP32 DevKit V1 (ESP-WROOM-32)

Skills you should have (or will pick up)

  • Multi-point temperature sensing and calibration
  • Excursion detection (band + duration)
  • GPS/time-stamped logging and offline retention
  • Cellular alerting and reporting
  • Compliance-oriented record keeping

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 ID1₹160
u-blox NEO-6M GPS module + ceramic patch antenna
Needs clear sky view; indoors it will never get a first fix.
50 channels, −161 dBm tracking, 2.5 m CEP, 1–5 Hz update, cold start 27 s1₹550
SIM800L GSM/GPRS module
Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
Quad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP1₹550
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
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
Temperature probes
Placement/calibration are critical
Sealed DS18B20 (or validated probes), multiple points3₹1,800
GPS + cellularLocation and in-transit alerting/upload1₹1,200
Door sensorReed switch for door-open events1₹100
Rugged enclosure + batteryIn-cargo enclosure with battery backup1₹500

Estimated total: ₹6,210, 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
u-blox NEO-6M GPS module + ceramic patch antenna50 channels, −161 dBm tracking, 2.5 m CEP, 1–5 Hz update, cold start 27 s3.3–5 VUART NMEA 9600Datasheet
SIM800L GSM/GPRS moduleQuad-band 850/900/1800/1900 MHz, GPRS class 12, SMS + TCP/IP3.4–4.4 V (NOT 5 V)UART AT commandsDatasheet
microSD card 32 GB A1 classA1 rated, 10 MB/s random write, UHS-I, endurance-grade recommended3.3 VSDIO / SPIDatasheet
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 V1.5Dozens can share one GPIO — you address them by ROM code.
u-blox NEO-6M GPS module + ceramic patch antenna3.3–5 V45Needs clear sky view; indoors it will never get a first fix.
SIM800L GSM/GPRS module3.4–4.4 V (NOT 5 V)2000Transmit bursts hit 2 A — needs a 4.0 V supply and a 1000 µF bulk capacitor.
microSD card 32 GB A1 class3.3 V100For 24/7 loggers buy a high-endurance card — normal cards die in months.

Summed typical draw is 2306.5 mA. With a 1.5× design margin the supply should deliver at least 3500 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
OneWire + DallasTemperature 2.3.x / 3.9.xBus enumeration and conversion commands for DS18B20 probes.Library Manager → "DallasTemperature" (pulls OneWire)
TinyGPSPlus 1.0.3Streaming NMEA parser producing latitude, longitude, speed and time.Library Manager → "TinyGPSPlus" by Mikal Hart
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
SQLite 3.45+Zero-configuration embedded database for local logs.Bundled with Python (`import sqlite3`)
NTPClient / configTime bundledWall-clock time from an NTP server for timestamping.Bundled (`configTime()` on ESP32)

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-Chain Truck Monitor — system block diagramFunctional block diagram of the Cold-Chain Truck Monitor system. SenseMulti-point tempcargo spaceDooropen/closeGPSlocationJudgeIn safe band?per pointExcursion?band+durationLog + alertLocal logoffline-safeAlertin transitProveCompliance recordtemp vs timeAccountabilitywhen/whererightrightnone
Cold-Chain Truck 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-Chain Truck 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 USBTemp probes (bus)GPIO 4Multi-point temp(1-Wire)Door reedGPIO 34Door open/closeGPSGPIO 26/25LocationCellular modemGPIO 27/14Alert/uploadSD cardGPIO 18/23/5Offline logBatteryBATBackup powerStatus LEDGPIO 2Health
Cold-Chain Truck Monitor — wiring schematic
PeripheralPeripheral pinController pinSignal
Temp probes (bus)DATAGPIO 4Multi-point temp (1-Wire)
Door reedINGPIO 34Door open/close
GPSTX/RXGPIO 26/25Location
Cellular modemUARTGPIO 27/14Alert/upload
SD cardSPIGPIO 18/23/5Offline log
Battery+BATBackup power
Status LEDINGPIO 2Health

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

  • Place sealed temperature probes at multiple representative points in the cargo space (not just near the vent).
  • Add a door sensor to correlate excursions with door-open events.
  • Add GPS for location stamping and cellular for in-transit alerts/upload.
  • Log to SD locally so the record survives signal loss; sync when connected.
  • Calibrate probes; a compliance record is only as good as its calibration.
A GPS navigation satellite in orbit
Multiple probes catch the worst point in a non-uniform trailer, not just the average near the vent. Photograph sourced from Wikimedia Commons — GPS satellite.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-Chain Truck Monitor — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · DS18B20 waterproof temperature probe ·u-blox NEO-6M GPS module + ceramic patch antennaDriver layerwifi · onewire · tinygps · pubsubApplication logicsampling loop · filtering · thresholds · state machineTransport layerCellular → cold-chain platform (offline-safe local log) · TLS · retry andbackoffPresentation layerdashboard · mobile notifications · historical charts
Cold-Chain Truck Monitor — architecture stack

Working Principle

The cold chain is a chain, and its integrity is only as good as its weakest, least-watched link — which in practice is transit. In a depot there are alarms and staff; on the road the cargo is sealed in a moving box, and a temperature breach there is silent. A reefer compressor can fail, a thermostat can drift, a door can be left ajar at a stop, or the load can soak up heat on a long hot leg — and unless something is actively watching, the cargo can sit out of range for hours and arrive looking fine while being spoiled or, for medicines, unsafe. Continuous, in-transit monitoring exists precisely to make that silent failure loud and early.

The first job is honest measurement, and the subtlety is that a trailer is not thermally uniform. Cold air enters at the vent and warms as it circulates; the load near the doors, in corners, or deep in a full pallet stack can be well outside the range the single factory sensor near the vent reports. So the monitor places probes at multiple representative points and judges each — because the cargo that spoils is the cargo at the worst point, not the average. Probes must be calibrated, because a compliance record built on an inaccurate sensor is worthless (and potentially dangerous, if it reassures falsely).

The second job is catching excursions in time to act. An excursion is not just an instantaneous reading out of band — it is temperature outside the safe range for a meaningful duration, since brief blips (a door opening) may be tolerable while sustained breaches are not, and different cargoes tolerate different exposures. The moment a genuine excursion is detected, the monitor alerts over cellular so someone can act while the load can still be saved: restart or repair the reefer, close the door, reroute to the nearest facility, or prioritise delivery. Catching it in transit is the entire difference between a recoverable incident and a written-off load.

The third job is proof and accountability. Cold-chain cargo lives in a regulated world — food safety and pharmaceutical rules require demonstrable temperature control — so the monitor keeps a complete, time-and-location-stamped record of the whole journey, retained locally even without signal so it is never lost, and syncable to a platform. That record does two things: it proves compliance (an auditable temperature-vs-time trace showing the chain held), and it assigns accountability when it did not (exactly when and where the breach happened, correlated with door events and location — depot, driver, route, or equipment). The design is candid that this is a regulated domain with validated-equipment expectations, that placement and calibration are critical, and that the record must be trustworthy to have value. Within that frame it delivers what cold-chain transit fundamentally needs: continuous watch, timely alerts, and a defensible proof that the cold never broke.

The maths behind it

Excursion detection (band + duration)

plainExcursion detection (band + duration)
For each monitored point p with safe band [T_lo, T_hi]:

  out(p) = T_p < T_lo  OR  T_p > T_hi
  excursion(p) if out(p) sustained for > t_tol

Brief blips (door open) tolerated; sustained breaches alerted.
Judge the WORST point, not the average.

Mean-kinetic-temperature (pharma)

plainMean-kinetic-temperature (pharma)
For thermal-load assessment over a journey:

  MKT = −(E/R) / ln( (1/n) Σ e^(−E/(R·T_i)) )

(a temperature that weights higher excursions more heavily —
used in pharma cold-chain to judge cumulative exposure.)

Record integrity

plainRecord integrity
Every reading logged: {t, location, point, temp}

  connected  → sync to platform
  offline    → retain locally, sync later (never lose it)

A compliance record must be complete and trustworthy.

Program Flowchart

The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.

Cold-Chain Truck Monitor — firmware flowchartControl flow through the main program loop. Read multi-point temp, door,GPSLog reading (time + location)Out of safe band?Excursion: alert in transitContinue loggingExcursion: alert in transitContinue loggingConnected?Sync log to platformRetain locallySync log to platformRetain locally
Cold-Chain Truck 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 and calibrate the probes

    Place sealed probes at multiple representative points (including likely worst points near doors/corners), not just at the vent, and calibrate them.

    Add a door sensor to correlate excursions with door-open events.

  2. Add location, alerting and offline logging

    Add GPS for location stamping and cellular for in-transit alerts/upload; log to SD so the record survives signal loss.

  3. Set bands, tolerances and the compliance report

    Configure the safe band and excursion tolerance per cargo, and produce an auditable temperature-vs-time report.

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. Detect a real excursion (band + duration)

    Judge each monitored point against its safe band, and treat it as an excursion only when out of range for longer than the tolerated duration — alerting on the worst point.

    pythonexcursion.py
    class PointMonitor:
        def __init__(self, name, t_lo, t_hi, tol_s):
            self.name = name; self.lo = t_lo; self.hi = t_hi
            self.tol = tol_s; self.out_since = None
    
        def update(self, temp, now):
            out = temp < self.lo or temp > self.hi     # outside safe band
            if out:
                if self.out_since is None:
                    self.out_since = now               # start timing the breach
                dur = now - self.out_since
                if dur >= self.tol:                    # sustained -> excursion
                    return {"point": self.name, "temp": temp,
                            "duration_s": int(dur), "excursion": True}
            else:
                self.out_since = None                  # back in band; blip tolerated
            return None
    
    def worst_excursion(points, temps, now):
        hits = [m.update(temps[m.name], now) for m in points]
        hits = [h for h in hits if h]
        # alert on the most severe (longest/most out-of-band) point
        return max(hits, key=lambda h: h["duration_s"], default=None)
    out = temp < self.lo or temp > self.hi # outside safe bandEach point is judged against its own safe band — the cargo that spoils is at the worst point, not the average.
    if dur >= self.tol: # sustained -> excursionAn excursion requires the breach to persist beyond a tolerance, so a brief door-opening blip does not cry wolf while a sustained failure does.
    self.out_since = None # back in band; blip toleratedReturning to band resets the timer — only sustained breaches alert, matching how cargo actually tolerates brief exposure.
    return max(hits, key=lambda h: h["duration_s"], default=None)The alert is driven by the most severe point, so the worst-affected cargo governs the response.
  2. Alert in transit and keep the record

    On a real excursion, alert over cellular immediately (with location and duration) so the load can be saved, and retain the full log locally so the compliance record is never lost.

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.

pythoncoldchain_monitor.py
#!/usr/bin/env python3
"""
Cold-Chain Truck Monitor

Continuously logs multi-point cargo temperature with time and location,
alerts in transit the instant a real excursion occurs (band + duration),
retains the record locally even without signal, and produces an auditable
compliance report. Placement and calibration are critical.
"""
import json, time

class ColdChainMonitor:
    def __init__(self, points, uplink, logfile="coldchain.jsonl"):
        self.points = points            # list[PointMonitor]
        self.uplink = uplink            # cellular
        self.logfile = logfile

    def log(self, record):
        with open(self.logfile, "a") as f:     # offline-safe: always log locally
            f.write(json.dumps(record) + "\n")

    def sync(self, record):
        try:
            self.uplink.publish("coldchain/telemetry", record)   # if connected
        except Exception:
            pass                                # retained locally; sync later

    def tick(self, temps, gps, door_open, now):
        record = {"t": now, "loc": gps, "door": door_open,
                  "temps": temps}
        self.log(record)                        # complete journey record
        self.sync(record)

        # excursion detection on the worst point
        worst = worst_excursion(self.points, temps, now)
        if worst:
            alert = {**worst, "loc": gps, "door": door_open, "t": now}
            self.log({"alert": alert})
            try:
                self.uplink.publish("coldchain/alert", alert)     # in-transit alert
            except Exception:
                pass                            # will re-send when connected

    def compliance_report(self):
        # auditable temperature-vs-time trace for food-safety / pharma
        with open(self.logfile) as f:
            return [json.loads(l) for l in f]

if __name__ == "__main__":
    pts = [PointMonitor("front", 2, 8, 600),
           PointMonitor("mid",   2, 8, 600),
           PointMonitor("doors", 2, 8, 300)]    # doors: tighter tolerance
    mon = ColdChainMonitor(pts, uplink=Cellular())
    while True:
        mon.tick(read_probes(), read_gps(), read_door(), time.time())
        time.sleep(30)
with open(self.logfile, "a") as f: # offline-safe: always log locallyEvery reading is logged locally first, so the compliance record survives signal loss and is never incomplete.
self.uplink.publish("coldchain/telemetry", record) # if connectedReadings sync to the platform when connected, giving live visibility without depending on constant signal.
worst = worst_excursion(self.points, temps, now)Excursion detection runs on the worst monitored point, so the most-affected cargo governs the alert.
self.uplink.publish("coldchain/alert", alert) # in-transit alertA real excursion alerts in transit, with location and duration, so the load can be saved while there is still time to act.
def compliance_report(self):The full local log becomes the auditable temperature-vs-time record that proves the cold chain held — or shows exactly when and where it did not.

Configuration & Calibration

Configuration steps

  • Configure probe placement/IDs, safe bands and excursion tolerances per cargo type.
  • Configure GPS/location stamping and cellular alerting/upload.
  • Configure offline logging retention and sync-on-reconnect.
  • Configure the compliance report format for audit.

Calibration procedure

An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.

  1. Probe calibration

    Calibrate each probe against a reference at the relevant temperatures; a compliance record depends on it.

  2. Placement

    Verify probes represent the real worst points (doors/corners), not just the vent.

  3. Tolerances

    Set excursion durations so brief door-opens are tolerated while real breaches alert.

Network Architecture & Connectivity

Cold-Chain Truck Monitor — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsCargo monitorESP32Reefer fleetall vehiclesCellularCarrierto platformMQTT/HTTPSCold-chain platformtemp records + alertsOpslive + alertsAuditcompliance record
Cold-Chain Truck Monitor — network topology

Communication protocol

Monitors stream temperature/location and alert on excursions; the full record is retained locally and synced, so signal loss never breaks the audit trail.

Topic / endpointDirectionPayload
coldchain/<veh>/telemetrymonitor → platformmulti-point temp, location, door
coldchain/<veh>/alertmonitor → opsexcursion: point, temp, duration, location
coldchain/<veh>/reportmonitor → audittemperature-vs-time compliance record

Message contract between the device and the broker.

Cloud platform configuration

A platform gives live reefer visibility, in-transit excursion alerts, and auditable compliance records across the fleet.

Dashboard setup

Live per-vehicle temperatures/location, excursion alerts, and downloadable compliance reports.

Mobile app integration

Immediate excursion alerts (where, how bad, how long) so the load can be saved.

Security considerations

  • Authenticate monitors; secure and tamper-evidence the temperature record.
  • Retain locally so signal loss never breaks the audit trail.
  • Calibrated, trustworthy records are a compliance requirement.

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 the door brieflyBlip logged; no false excursion (within tolerance)
Disable coolingSustained rise → in-transit excursion alert with location
Lose cellular signalReadings retained locally; sync on reconnect
Heat one point onlyWorst point flagged, not masked by the average
Complete a journeyAuditable temperature-vs-time compliance record
Miscalibrate a probe (test)Detected in calibration check — record trustworthy

Bench-test checklist. If a row fails, stop and fix it before moving on.

Expected output

A complete, location-stamped temperature record with in-transit excursion alerts and an auditable compliance report.

jsoncoldchain-alert.json
{
  "point": "doors",
  "temp": 11.4,
  "duration_s": 420,
  "loc": { "lat": 26.9124, "lon": 75.7873 },
  "door": false,
  "excursion": true
}

A sustained breach at the door-end (11.4 °C for 7 minutes, doors closed — a cooling fault, not a door-open) flagged in transit with location, so the load can be saved and the cause pinned to equipment.

Automated machinery on a factory production line
The location-stamped record proves the cold chain held — or pins exactly when and where it broke. Photograph sourced from Wikimedia Commons — Factory automation.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Excursion missed

Likely cause. Single/poorly-placed sensor

Fix. Monitor multiple representative points; judge the worst

False excursions on stops

Likely cause. No door tolerance

Fix. Tolerate brief blips by duration; correlate with door events

Record lost in a dead zone

Likely cause. No offline logging

Fix. Log locally always; sync on reconnect

Record not trusted

Likely cause. Uncalibrated probes

Fix. Calibrate against a reference; document calibration

Alert too late to act

Likely cause. Post-hoc only

Fix. Alert in transit the instant a real excursion is detected

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.

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

  • Monitor multiple points; judge the worst, not the average.
  • Detect excursions by band and duration to avoid false alarms on door-opens.
  • Log locally always; alert in transit; sync when connected.
  • Keep the record complete and calibrated for audit.
  • 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

  • Cold-chain compliance is regulated (food safety, pharma) — use validated equipment and calibrated probes where required.
  • A false-reassuring record is dangerous — trustworthiness (calibration, placement, integrity) is paramount.
  • For medicines especially, treat excursions as potential safety events, not just quality issues.
  • Mount sensors and enclosure so they do not obstruct loading or damage cargo.
  • 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.
  • Never power an RF module without its antenna fitted — the reflected power destroys the output stage. Check your local licence-free band and duty-cycle limits before transmitting.
  • 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

  • Re-calibrate probes on a schedule; document it.
  • Verify placement still represents worst points after load-pattern changes.
  • Check battery, GPS and cellular health.
  • Review excursion alerts and reports for recurring causes.
  • 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 mean-kinetic-temperature and cargo-specific stability budgets.
  • Add predictive alerts (trend toward breach before it happens).
  • Add tamper-evident/signed records for stronger audit.
  • Add humidity and shock monitoring for sensitive cargo.
  • 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 monitor in transit rather than just at delivery?

Because a breach caught at delivery is a written-off load, but a breach caught in transit can often be saved — restart the reefer, close a door, reroute. In-transit alerting is the difference between a recoverable incident and a loss.

Why multiple sensors?

A trailer is not thermally uniform — the load near doors or in corners can be well out of range while the vent sensor reads fine. The cargo that spoils is at the worst point, so you monitor several and judge the worst.

What counts as an excursion?

Temperature outside the safe band for longer than a tolerated duration. A brief door-opening blip may be fine; a sustained breach is not. Judging band and duration together avoids both false alarms and missed failures.

What if there is no signal?

The full record is logged locally and synced when the connection returns, so the compliance trail is never lost in a dead zone. Alerts are re-sent on reconnect.

Why does calibration matter so much?

Because the record's whole value is trust. An uncalibrated probe can falsely reassure that cargo stayed safe when it did not — worse than no record at all, especially for medicines. Cold-chain is a regulated domain for exactly this reason.

References & Learning Resources

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

  1. Cold chainReference
  2. Temperature excursion / mean kinetic temperatureReference
  3. Vaccine / pharma cold chainReference
  4. DS18B20 temperature sensorAnalog Devices
  5. Food safety temperature controlReference