Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: A Temperature Monitoring System

Build a complete IoT monitor step by step: firmware sketch, simulated sensors, validation, aggregation, alerts with duration and hysteresis, and a status report.

In this project you build the software side of a cold-room temperature monitor, the kind used to protect food or vaccines. Several sensors report temperatures; the system must reject bad data, notice a sensor that went silent, and raise an alarm only when the temperature stays too high for a while (so that opening the door for a minute does not wake anyone up at night).

You will use ideas from earlier lessons: MQTT topics, the data pipeline, edge rules and time-series queries. The hardware is simulated so everything runs in the editor.

Requirements

  1. Three sensors publish coldroom/<id>/temp every minute as JSON { "c": number, "ts": seconds }.
  2. Readings outside -40..60 C are errors and are ignored.
  3. High alarm: if the average of the last 5 minutes is above 8 C, raise HIGH. Clear it when the average is back below 7 C (hysteresis).
  4. Silent sensor alarm: if a sensor sends nothing for 3 minutes, raise SILENT.
  5. At the end print a summary per sensor.
flowchart LR
  S1["sensor a"] --> B(("Broker"))
  S2["sensor b"] --> B
  S3["sensor c"] --> B
  B --> M["Monitor:<br/>validate, window, alarms"]
  M --> R["Report / notifications"]

The device side (read-only)

On a real ESP32 with a DS18B20 temperature probe the firmware is short. It cannot run here, but it shows what the simulation stands in for:

C++
#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire oneWire(4);                 // data pin
DallasTemperature probe(&oneWire);
WiFiClient net;
PubSubClient mqtt(net);

void loop() {
  if (!mqtt.connected()) mqtt.connect("cold-a", nullptr, nullptr,
      "coldroom/a/status", 1, true, "offline");       // last will, retained
  mqtt.loop();
  probe.requestTemperatures();
  float c = probe.getTempCByIndex(0);
  if (c > -55 && c < 125) {                           // -127 means probe error
    char buf[64];
    snprintf(buf, sizeof buf, "{\"c\":%.1f,\"ts\":%lu}", c, (unsigned long)(millis() / 1000));
    mqtt.publish("coldroom/a/temp", buf);
  }
  delay(60000);
}

Notice the Last Will and the sanity check of the probe's error value (-127).

Step 1: simulate sensors

A seeded random generator makes the data repeatable. Sensor a is healthy, sensor b drifts upward when the door is left open from minute 10 to 20, and sensor c dies at minute 14 and also sends one impossible reading.

Node.js Generate the sensor events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step 2: the monitor

The monitor keeps, for each sensor, a window of recent valid readings, the time of the last message and the alarm state. It checks silence on every minute tick using the simulation clock. Read the code from top to bottom; each requirement from the list is a labelled block.

Node.js Complete monitor with alarms and report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the log: sensor b is flagged HIGH a few minutes after the door opens, not immediately, because the window average needs to climb. It clears with hysteresis after the door closes. Sensor c produced one rejected reading and then went silent. Sensor a produced no alarms.

Step 3: ideas to extend

  • Persist the readings in a SQL table like the one in the time-series lesson and plot hourly min/avg/max.
  • Notify: replace alarm() with a call to an email, SMS or chat webhook, and re-notify every 30 minutes until acknowledged.
  • Escalate: a HIGH alarm lasting more than 30 minutes calls a second contact.
  • Calibrate: store a per-sensor offset in a device registry.
  • Secure the project: per-sensor credentials and topic ACLs from the identity lesson.
  • Battery sensors: lower the publish rate while the temperature is stable (dead band) and publish faster when it changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the HIGH alarm use the average of five readings instead of a single reading?

    A window smooths short events so alarms reflect sustained problems.
  2. 2. Why are the on and off thresholds different (8 and 7 degrees)?

    Switching on at 8 and off at 7 keeps the state stable when the temperature hovers near the limit.
  3. 3. How does the monitor notice a dead sensor?

    A silent sensor sends nothing, so the monitor must watch the clock. A Last Will can also report it, but only for connection loss.
  4. 4. What does the -127 reading in the example represent?

    DS18B20 probes return -127 when disconnected, so values outside the plausible range are discarded.

Summary

  • A monitoring system combines device, transport, validation, rules and reporting.
  • Use windows and hysteresis for stable alarms and a silence timer for dead sensors.
  • Sanity-check readings at the device and again on the server.
  • Keep the simulation: it lets you test alarm logic repeatably before touching hardware.

Next: Project: A Smart Home Rules Engine