Capstone: a node you can leave on a site
On this page
A node on your desk is a demo. A node on a site, a cold room across town, a pump house on a farm, a server room you visit once a month, is a promise: if something goes wrong, you will know, and the node will not be the thing that went wrong. This capstone puts every lesson of the course into one firmware, and gives you the tests and the checklist that let you leave it there and drive away.
What you will leave on the site
An ESP32 with a BME280 and a relay module, watching a room and running a fan. It:
- takes a sample every 2 seconds and sends an averaged, checked reading every 30 seconds;
- connects over TLS with the certificate checked, after setting its clock;
- never blocks: it reads and protects with or without a network;
- reconnects with a growing gap (5 to 60 seconds) and subscribes again every time;
- keeps up to 6 hours of readings during an outage and sends them later with their own time;
- restarts itself with a watchdog if the code ever gets stuck, and starts safe;
- obeys a relay command and replies, and switches the relay off by itself after 30 minutes, whatever the network says.
The live sensor node build runs this same firmware. It is the hands-on version: the parts, the wiring, a printed case, and the checks, step by step. This lesson explains why each part of the firmware is there.
Before you flash: set up the device
On siliconwit.io, our monitoring service (or a broker you run, with the same topics):
- Add Device, then Define my own device. Fields:
temperature(unit °C) andhumidity(unit %). - Set the data interval to 30 seconds.
- Add a Toggle command named
relay. - On the Automation tab, add two alerts: the temperature above your limit, held for 10 minutes; and the device not reporting. Send both to the person who can act.
- Copy the Device ID and Access Token into the firmware.
The firmware
Wire the BME280 as in the sensor lesson (3V3, GND, SDA to GPIO 21, SCL to GPIO 22) and the relay module's input to GPIO 26. Install PubSubClient, ArduinoJson (version 7) and Adafruit BME280 from the Library Manager. Fill in the five lines under "your Wi-Fi" and "your broker", and flash. The root certificate is already in it.
#include <WiFi.h>#include <WiFiClientSecure.h>#include <PubSubClient.h>#include <ArduinoJson.h>#include <Adafruit_BME280.h>#include <esp_task_wdt.h>#include <time.h>
// --- your Wi-Fi ---const char* WIFI_SSID = "your-network";const char* WIFI_PASS = "your-password";
// --- your broker (siliconwit.io shown; for your own, change these five lines) ---const char* MQTT_HOST = "mqtt.siliconwit.io";const int MQTT_PORT = 8883; // MQTT over TLSconst char* DEVICE_ID = "SWD-XXXXXX"; // client ID, username, and the topic nameconst char* MQTT_PASS = "your-access-token"; // the Access Token#define USE_TLS 1 // 0 only for a test broker on your own network: then port 1883, and no certificate// ISRG Root X1: the root certificate that the broker's certificate chain ends in.// The same text as https://letsencrypt.org/certs/isrgrootx1.pem (valid until 2035).const char* ROOT_CA = R"PEM(-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----)PEM";
// --- what the node does ---const unsigned long SAMPLE_MS = 2000; // read the sensor every 2 sconst int SAMPLES = 15; // average 15 samples: one reading every 30 sconst int RELAY_PIN = 26; // drives a fan through a relay moduleconst unsigned long RELAY_MAX_MS = 30UL * 60 * 1000; // the relay never stays on more than 30 minconst int WDT_S = 60; // restart if loop() is stuck this long
#if USE_TLSWiFiClientSecure net;#elseWiFiClient net;#endifPubSubClient mqtt(net);Adafruit_BME280 bme;bool sensorOk = false;
// readings taken while the broker could not be reached, oldest firststruct Kept { unsigned long atMs; float t, h; };const int KEEP_MAX = 720; // 6 hours of readings at one every 30 sKept kept[KEEP_MAX];int keptFirst = 0, keptCount = 0;
float sumT = 0, sumH = 0;int taken = 0, good = 0;unsigned long lastSample = 0, lastTry = 0, lastWifiTry = 0, lastBacklog = 0, relayOnAt = 0;unsigned long retryMs = 0; // wait before the next connect attemptint fails = 0; // failed attempts in a rowbool relayOn = false;
String topic(const char* channel) { return String("d/") + DEVICE_ID + "/" + channel; }bool clockSet() { return time(nullptr) > 1700000000; } // later than November 2023
void setRelay(bool on) { relayOn = on; if (on) relayOnAt = millis(); digitalWrite(RELAY_PIN, on ? HIGH : LOW);}
// a command on d/<id>/c: run it, then reply on d/<id>/k/<session>void onCommand(char* t, byte* data, unsigned int len) { JsonDocument msg; if (deserializeJson(msg, data, len)) return; // not JSON: ignore it const char* session = msg["session"] | ""; bool ran = false; if (msg["command"] == "relay") { JsonVariant v = msg["value"]; // true, 1 or "on" switches it on setRelay(v.is<bool>() ? v.as<bool>() : (v == "on" || v == 1)); ran = true; } if (*session) { mqtt.publish((topic("k/") + session).c_str(), ran ? "{\"status\":\"ok\"}" : "{\"status\":\"error\",\"message\":\"unknown command\"}"); }}
// one reading as JSON; with a time when the clock is set, so a late reading lands at the right momentbool sendReading(float t, float h, unsigned long atMs) { char payload[96]; if (clockSet()) { unsigned long ts = (unsigned long)time(nullptr) - (millis() - atMs) / 1000; snprintf(payload, sizeof(payload), "{\"temperature\":%.1f,\"humidity\":%.1f,\"ts\":%lu}", t, h, ts); } else { snprintf(payload, sizeof(payload), "{\"temperature\":%.1f,\"humidity\":%.1f}", t, h); } return mqtt.publish(topic("t").c_str(), payload);}
void keep(float t, float h) { if (keptCount == KEEP_MAX) { // full: drop the oldest keptFirst = (keptFirst + 1) % KEEP_MAX; keptCount--; } kept[(keptFirst + keptCount) % KEEP_MAX] = { millis(), t, h }; keptCount++;}
// send kept readings, oldest first, about 100 a minute (the limit is 120),// once the newest of them is over 2.5 minutes old: then none is held to the data intervalvoid sendBacklog() { if (!keptCount || !mqtt.connected() || !clockSet()) return; const Kept& newest = kept[(keptFirst + keptCount - 1) % KEEP_MAX]; if (millis() - newest.atMs < 150000UL) return; if (millis() - lastBacklog < 600) return; lastBacklog = millis(); const Kept& k = kept[keptFirst]; if (sendReading(k.t, k.h, k.atMs)) { keptFirst = (keptFirst + 1) % KEEP_MAX; keptCount--; }}
bool connectMqtt() { if (mqtt.connected()) return true; if (WiFi.status() != WL_CONNECTED || (USE_TLS && !clockSet())) return false; // TLS needs the right time if (millis() - lastTry < retryMs) return false; lastTry = millis(); if (mqtt.connect(DEVICE_ID, DEVICE_ID, MQTT_PASS)) { // no last will: the platform sees silence itself fails = 0; retryMs = 0; mqtt.subscribe(topic("c").c_str()); // again after every reconnect Serial.println("MQTT connected"); return true; } fails++; retryMs = min(5000UL << min(fails - 1, 4), 60000UL) // 5, 10, 20, 40, then 60 s + random(1000); // plus up to 1 s, so many nodes do not retry together Serial.printf("MQTT connect failed, state %d, next try in %lu s\n", mqtt.state(), retryMs / 1000); return false;}
void keepWifi() { if (WiFi.status() == WL_CONNECTED) return; if (millis() - lastWifiTry < 30000) return; // the radio also retries by itself lastWifiTry = millis(); Serial.println("Wi-Fi down, trying again"); WiFi.reconnect();}
void setup() { Serial.begin(115200); pinMode(RELAY_PIN, OUTPUT); setRelay(false); // after any restart the fan starts off
#if ESP_ARDUINO_VERSION_MAJOR >= 3 esp_task_wdt_config_t wdt = { .timeout_ms = WDT_S * 1000, .idle_core_mask = 0, .trigger_panic = true }; esp_task_wdt_reconfigure(&wdt);#else esp_task_wdt_init(WDT_S, true);#endif esp_task_wdt_add(NULL); // watch this loop
sensorOk = bme.begin(0x76) || bme.begin(0x77); // SDA = GPIO 21, SCL = GPIO 22 if (!sensorOk) Serial.println("BME280 not found: check the wires and the address"); bme.setSampling(Adafruit_BME280::MODE_FORCED, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::SAMPLING_X1, Adafruit_BME280::FILTER_OFF);
WiFi.mode(WIFI_STA); WiFi.setAutoReconnect(true); WiFi.begin(WIFI_SSID, WIFI_PASS); // no waiting here: loop() works offline configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC, set in the background
#if USE_TLS net.setCACert(ROOT_CA); net.setHandshakeTimeout(20); // seconds; well under the watchdog#endif mqtt.setServer(MQTT_HOST, MQTT_PORT); mqtt.setKeepAlive(60); mqtt.setBufferSize(512); // room for a command with all its fields mqtt.setCallback(onCommand);}
void loop() { esp_task_wdt_reset(); // "still alive" keepWifi(); connectMqtt(); mqtt.loop(); sendBacklog();
if (relayOn && millis() - relayOnAt > RELAY_MAX_MS) setRelay(false); // the local limit
if (millis() - lastSample < SAMPLE_MS) return; lastSample = millis(); if (!sensorOk) return; bme.takeForcedMeasurement(); float t = bme.readTemperature(), h = bme.readHumidity(); taken++; if (!isnan(t) && !isnan(h) && t > -40 && t < 85 && h >= 0 && h <= 100) { sumT += t; sumH += h; good++; } else Serial.println("rejected sample"); if (taken < SAMPLES) return;
if (good >= SAMPLES / 2) { // at least half the samples were sane float avgT = sumT / good, avgH = sumH / good; Serial.printf("%.1f C %.1f %% (%d of %d samples)\n", avgT, avgH, good, taken); if (!mqtt.connected() || !sendReading(avgT, avgH, millis())) keep(avgT, avgH); // kept for later } else { Serial.println("too few sane samples: no reading this time"); } sumT = sumH = 0; taken = good = 0;}How to read it
- The top holds everything that changes between sites: Wi-Fi, broker, Device ID, token. Moving the node to your own broker means changing those lines and the certificate, and nothing else.
loop()reads from the top down: feed the watchdog, look after Wi-Fi, connect if needed, handle messages, send the backlog, apply the relay's own limit, and then, every 2 seconds, take a sample. Nothing in it waits for the network.- The relay limit is local. A command can switch the fan on, but only the firmware decides it goes off after 30 minutes. If the network fails with the fan on, the fan still stops. That is the first lesson of the course, in one line of code.
- The buffer of 720 readings is 6 hours at one every 30 seconds, and uses about 8.6 KB of memory.
The site switches its router off every night from 22:00 to 06:00 to save power. Does the firmware lose readings, and what would you change?
Show the worked solution, 4 steps
- Readings in one night
8 hours × 120 readings an hour = 960 readings. ✅
- What the buffer keeps
It holds 720, so it drops the oldest 240: the first 2 hours of the night, 22:00 to 00:00, are lost. ✅
- The change
Set
KEEP_MAXto 1000: 1000 × 12 bytes = 12 KB, still small for the ESP32. The night fits, with room to spare. ✅ - The send in the morning
960 readings at 100 a minute take about 10 minutes, all within the 7 day window for
ts. By 06:15 the chart shows the whole night. Ask the site, too: a node that cannot alert anyone for 8 hours a night is a choice they should make knowingly. ✅
Test it on your desk before you leave
Run the node for at least 24 hours on your desk first. Then do each test below with the Serial Monitor open and the device page on your phone. Each one has a result you can see; if any result differs, fix it before the node goes anywhere.
| Test | You should see |
|---|---|
| Breathe on the sensor | Humidity rises in the next reading, on serial and on the chart. |
Send relay on, then off, from the Control tab | The relay clicks each time; the command history shows both as done. |
| Leave the relay on | After 30 minutes it switches off by itself. |
| Unplug the router for 15 minutes | Serial keeps printing readings; a "not reporting" alert arrives after about 5 minutes; after the router is back, the 15 minute gap fills in within a few minutes. |
| Power the board off and on, router off | Readings start on serial at once; the relay starts off. |
| Disconnect the sensor's SDA wire for a minute | "rejected sample" lines, then "too few sane samples"; no false reading is sent. If a wrong reading does go out, your sanity limits are too wide for this fault: tighten them. |
| Put a wrong token in, flash, and watch | "MQTT connect failed, state 5" (or 4) with the gap growing to 60 seconds. Then put the right one back. |
On the site
- Check the Wi-Fi where the node will sit, not at the door. If a phone shows one bar there, the node will drop often. Move it, or add an access point.
- Use a good 5 V supply of at least 1 A. The ESP32 draws short bursts when Wi-Fi transmits, and a weak supply causes random restarts that look like software faults.
- Keep the sensor in the air it measures. Outside the box, or in a vented part of it, away from the supply and out of direct sun.
- Protect the relay side. If the relay switches mains power, that wiring belongs to a qualified electrician, inside a proper enclosure, with the right fuse.
- Label the box with the Device ID and how to reach you, so the person on site can tell you which node they are looking at.
- Before you drive away, open the device on your phone: reporting, a fresh reading, and one command answered from the site.
You are done when
- The node has run for 24 hours with no gap you cannot explain.
- Every test in the table gave the result in its second column.
- The person who answers the alerts has received a test alert and knows what to do.
- You can unplug the router at the site, and both the node and the platform behave exactly as on your desk.
Check yourself
A command switches the fan on, and then the site's internet fails for an hour. What happens to the fan?
The node's buffer holds 720 readings at one every 30 seconds. How long an outage can it cover with no lost readings?
The node restarts at random every few hours. The serial log shows no error before it. What do you check first?
- One firmware: averaged and checked readings, checked TLS, no blocking, growing reconnect gap, kept readings sent with
ts, a watchdog, and a command with a reply. - Limits that protect people and equipment live in the firmware; the platform adds the record, alerts and the silence check.
- Test every failure on your desk first, with a result you can see, and run for 24 hours before the node leaves.
- On site: check the signal where it sits, use a good supply, keep the sensor in the air, label the box.
You started with a device on a bench that nobody could see. You finish with a node you can leave on a site and trust, and with the judgement to say what belongs on the device and what belongs in the cloud. When one node becomes ten, the IoT Systems course takes you from here.
Discussion
No comments yet. Ask a question, share a result from your own build, or suggest a clearer way to explain it.
Join the discussion. Anyone can read. To comment, reply or mark a comment helpful, sign in with your SiliconWit account.
My notes on this page
Kept on this device. To have them on every device, turn on keeping in My notes.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
Notes on earlier wording
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.