Capstone: a battery sensor node
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Put the course together in one device: an ESP32 soil sensor on a 3,000 mAh battery that reports to an MQTT broker over Wi-Fi. Follow one hour of its life: the RTC timer wakes it every 600 s, each wake is a fresh boot that keeps one reading in RTC memory and sleeps again, and every sixth wake the radio joins Wi-Fi and publishes all six readings in one message. Then see what happens when the router is down, and why using the radio once an hour stretches the battery from about 146 to 642 days. The Networking lessons on Wi-Fi and IoT with MQTT explain the protocols; "Joining Wi-Fi from an ESP32", "Publishing sensor data with MQTT", "Power budgets and battery life" and "Sleep modes and wake-up sources" cover each piece on its own.
One node, one cycle
Our capstone: an ESP32 on a 3,000 mAh battery reads a soil sensor and reports over Wi-Fi to an MQTT broker. It must last a long time, so its life is one cycle: sleep, wake, read, sometimes send, sleep.
board ESP32 DevKitC, Arduino-ESP32 core 3.x
sensor soil probe on GPIO34
battery 3,000 mAh lithium-ion cell
network Wi-Fi -> MQTT broker, topic garden/node-1/soil
cycle sleep -> wake -> read -> (send) -> sleep
// ESP32 DevKitC, Arduino-ESP32 core 3.x. Soil sensor on GPIO34 (ADC1).
// Wakes every 600 s; publishes 6 readings at a time over MQTT + TLS.
#include <WiFi.h>
#include <NetworkClientSecure.h>
#include <PubSubClient.h>
#include "secrets.h" // WIFI_SSID, WIFI_PASS, BROKER, CA_CERT
const int MAXN = 12;
RTC_DATA_ATTR int n = 0; // kept in RTC memory
RTC_DATA_ATTR int buf[MAXN]; // through deep sleep
NetworkClientSecure net;
PubSubClient mqtt(net);
void save(int v) {
if (n == MAXN) { // full: drop the oldest
memmove(buf, buf + 1, (MAXN - 1) * sizeof(int));
n--;
}
buf[n++] = v;
}
bool sendAll() {
WiFi.begin(WIFI_SSID, WIFI_PASS);
for (int i = 0; i < 100 && WiFi.status() != WL_CONNECTED; i++)
delay(100); // at most 10 s
if (WiFi.status() != WL_CONNECTED) return false;
net.setCACert(CA_CERT);
mqtt.setServer(BROKER, 8883);
if (!mqtt.connect("node-1")) return false;
String msg = "[";
for (int i = 0; i < n; i++) {
if (i) msg += ',';
msg += buf[i];
}
msg += "]";
bool ok = mqtt.publish("garden/node-1/soil", msg.c_str());
mqtt.disconnect();
return ok;
}
void sleepFor(uint64_t s) {
WiFi.disconnect(true); // radio off
esp_sleep_enable_timer_wakeup(s * 1000000ULL);
esp_deep_sleep_start(); // never returns
}
void setup() {
setCpuFrequencyMhz(80);
save(analogRead(34));
if (n >= 6 && sendAll())
n = 0;
sleepFor(600);
}
void loop() {} // never reached: every wake boots into setup()اقرأ الدرس خطوة بخطوة
One node, one cycle
Our capstone: an ESP32 on a 3,000 mAh battery reads a soil sensor and reports over Wi-Fi to an MQTT broker. It must last a long time, so its life is one cycle: sleep, wake, read, sometimes send, sleep.
board ESP32 DevKitC, Arduino-ESP32 core 3.x sensor soil probe on GPIO34 battery 3,000 mAh lithium-ion cell network Wi-Fi -> MQTT broker, topic garden/node-1/soil cycle sleep -> wake -> read -> (send) -> sleep // ESP32 DevKitC, Arduino-ESP32 core 3.x. Soil sensor on GPIO34 (ADC1). // Wakes every 600 s; publishes 6 readings at a time over MQTT + TLS. #include <WiFi.h> #include <NetworkClientSecure.h> #include <PubSubClient.h> #include "secrets.h" // WIFI_SSID, WIFI_PASS, BROKER, CA_CERT const int MAXN = 12; RTC_DATA_ATTR int n = 0; // kept in RTC memory RTC_DATA_ATTR int buf[MAXN]; // through deep sleep NetworkClientSecure net; PubSubClient mqtt(net); void save(int v) { if (n == MAXN) { // full: drop the oldest memmove(buf, buf + 1, (MAXN - 1) * sizeof(int)); n--; } buf[n++] = v; } bool sendAll() { WiFi.begin(WIFI_SSID, WIFI_PASS); for (int i = 0; i < 100 && WiFi.status() != WL_CONNECTED; i++) delay(100); // at most 10 s if (WiFi.status() != WL_CONNECTED) return false; net.setCACert(CA_CERT); mqtt.setServer(BROKER, 8883); if (!mqtt.connect("node-1")) return false; String msg = "["; for (int i = 0; i < n; i++) { if (i) msg += ','; msg += buf[i]; } msg += "]"; bool ok = mqtt.publish("garden/node-1/soil", msg.c_str()); mqtt.disconnect(); return ok; } void sleepFor(uint64_t s) { WiFi.disconnect(true); // radio off esp_sleep_enable_timer_wakeup(s * 1000000ULL); esp_deep_sleep_start(); // never returns } void setup() { setCpuFrequencyMhz(80); save(analogRead(34)); if (n >= 6 && sendAll()) n = 0; sleepFor(600); } void loop() {} // never reached: every wake boots into setup()Waking is a fresh boot
After 600 s the RTC timer wakes the chip. Deep sleep had switched off the processors and most RAM, so the chip boots again and setup() runs from line 1. Only RTC memory kept its values.
RTC timer 600 s are up -> wake deep sleep powered off: both CPUs, most RAM so: boot again, setup() from line 1 kept: RTC memory (8 KB slow), n and buf[] RTC_DATA_ATTR int n; // lives thereRead and keep: 2210
The CPU drops to 80 MHz to save current. analogRead(34) gives 2210, out of 0 to 4095. GPIO34 is on ADC1 on purpose: Wi-Fi also uses ADC2. save() puts the reading in buf[0] in RTC memory; n becomes 1.
line 2 setCpuFrequencyMhz(80); awake about 31 mA line 3 analogRead(34) -> 2210 (12 bits: 0..4095) GPIO34 = ADC1_CH6; ADC2 is shared with Wi-Fi save(2210) -> buf[0] = 2210, n = 1Five more wakes, radio off
n is 1, not 6, so line 4 skips the radio and the chip goes straight back to sleep. Every 10 minutes the same: wake, read, save, sleep, about a second awake. After one hour n reaches 6.
line 4 n >= 6? no -> skip sendAll() line 6 sleepFor(600) wake 2 buf[1] = 2224 n = 2 wake 3 buf[2] = 2239 n = 3 wake 4 buf[3] = 2251 n = 4 wake 5 buf[4] = 2266 n = 5 wake 6 buf[5] = 2280 n = 6 n = 6: time to sendJoin Wi-Fi, with a deadline
Now n is 6, so sendAll() runs. WiFi.begin() joins the router: a fresh join every time, because deep sleep dropped the connection. The loop waits at most 10 seconds. The radio draws the most current of anything here.
line 4 n >= 6 -> sendAll() WiFi.begin(WIFI_SSID, WIFI_PASS); wait for WL_CONNECTED, at most 10 s radio receive 95..100 mA, transmit up to 240 mAOne message, six readings
The node connects to the broker over TLS on port 8883, checking its certificate, and publishes all 6 readings as one message to garden/node-1/soil. One radio session carries an hour of data.
TLS port 8883, server checked against CA_CERT topic garden/node-1/soil payload [2210,2224,2239,2251,2266,2280] (31 bytes) QoS 0 at most once: no reply from the broker mqtt.disconnect(); sendAll() returns trueClear, then sleep at 10 µA
sendAll() returned true, so n = 0 empties the buffer. sleepFor(600) turns the radio off, sets the RTC timer and enters deep sleep. The current falls to about 10 µA until the next wake.
line 5 n = 0 buffer empty line 6 sleepFor(600) WiFi.disconnect(true); radio off esp_sleep_enable_timer_wakeup(600 * 1000000); esp_deep_sleep_start(); never returns deep sleep about 10 µAWhen the router is down
Next hour the router is off. The join gives up after 10 s and sendAll() returns false, so n is not cleared: the readings wait in RTC memory for the next try. Never wait forever on a battery.
line 4 sendAll() -> no WL_CONNECTED in 10 s -> false line 5 skipped: n stays 6 line 6 sleep; the next wake tries again (n = 7) buffer room for 12; when full, the oldest is dropped cost n stays >= 6: every wake now tries Wi-Fi, up to 10 s at the radio current; a real node backs off, e.g. retries only every 6th wake146 days or 642 days
Sending on every wake averages 0.86 mA: the battery lasts about 146 days. Sending every sixth wake averages 0.19 mA: about 642 days, 4.4 times longer. Same chip, same sensor: only the radio plan changed.
per hour 6 sleeps x 6 + 6 wakes x 31 mA·s + radio 240 mA x 2 s = 480 mA·s each time every wake 3102 mA·s / 3618 s = 0.86 mA -> 146 days every 6th 702 mA·s / 3608 s = 0.19 mA -> 642 days 3,000 mAh / avg mA = hours; / 24 = days
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01An ESP32 wakes from deep sleep on its RTC timer. Where does the program carry on?
Deep sleep powers off the CPUs and most of the RAM, so waking is a boot. esp_deep_sleep_start() never returns, and setup() runs again from line 1.
02Why is the reading counter n declared RTC_DATA_ATTR?
Ordinary variables are lost when deep sleep powers RAM off. RTC_DATA_ATTR places the variable in RTC slow memory, which ESP-IDF keeps powered, so n and buf[] survive from one wake to the next.
03The soil sensor is wired to GPIO34, an ADC1 pin. Why not an ADC2 pin?
Espressif's ADC documentation lists it as a hardware limitation: ADC2 is also used by Wi-Fi. A node that uses Wi-Fi keeps its analog sensors on ADC1.
04The router is off. What does this firmware do?
sendAll() waits at most 10 s for WL_CONNECTED and returns false, so n is not cleared. The readings wait (up to 12, oldest dropped first) and the chip sleeps. A battery device must never wait forever.
05With the same parts, sending on every wake lasts about 146 days. Why does sending every sixth wake last about 642 days?
One radio session (240 mA for 2 s) costs 480 mA·s, far more than a 1 s wake (31 mA·s) or 600 s of sleep (6 mA·s). Batching cuts the hourly charge from 3102 to 702 mA·s: the average falls from 0.86 to 0.19 mA.
المسرد
- TLS
- Transport Layer Security: encrypts a network connection and lets the device check the server's certificate.
- Deep sleep
- An ESP32 mode where the processors and most RAM are powered off; only the RTC part stays on. Waking is a fresh boot.
- RTC timer
- A low-power clock inside the ESP32 that keeps counting in deep sleep and wakes the chip.
- RTC memory
- A small memory (8 KB of RTC slow memory on the ESP32) that stays powered in deep sleep. RTC_DATA_ATTR puts a variable there.
- ADC
- Analog-to-digital converter: turns a voltage into a number. The ESP32 has two, ADC1 and ADC2; ADC2 cannot be used while Wi-Fi is on.
- Batching
- Collecting several readings and sending them together, so the costly radio is used less often.
- MQTT broker
- A server that receives messages published to a topic and passes them on to subscribers.
- Timeout
- A limit on how long code waits for something, so a failure cannot stall the device or drain its battery.
الملاحظات والمصادر
- The card shows only setup(). The whole sketch adds save(), which keeps up to 12 readings in RTC memory and drops the oldest when full, sendAll(), and sleepFor(). loop() is empty: every wake from deep sleep boots into setup() again.
- Currents are from the ESP32 datasheet v5.3: about 31 mA awake at 80 MHz (dual-core, radio off), 240 mA transmitting 802.11b at +19.5 dBm, 10 µA in deep sleep with the RTC timer and RTC memory on. The 1 s awake and 2 s radio times are assumptions, as in the lesson "Power budgets and battery life"; measure your own board.
- A DevKitC board also powers a USB chip, a regulator and an LED, which can draw far more than the ESP32 in deep sleep. A real battery node uses a bare module or a board designed for low sleep current.
- PubSubClient can only publish at QoS 0, "at most once": publish() returning true means the message left the node, not that the broker stored it. For an acknowledgement use a client with QoS 1, such as ESP-IDF's esp-mqtt.
- The 642-day figure ignores self-discharge: Battery University gives 1 to 2 percent per month for Li-ion, plus about 3 percent per month for a protection circuit. Over that long, it matters.
- After a failed send, n stays at 6 or more, so every later wake runs sendAll() again and may spend up to 10 s with the radio on while the router is down. That costs more than any normal wake. A real node adds a back-off, for example trying only every 6th wake, or waiting longer after each failure.
- secrets.h holds the Wi-Fi password and the CA certificate. Keep it out of version control; the lesson "Securing a device: TLS, secrets and secure boot" shows how to protect them on the chip.
- Espressif ESP32 Series Datasheet v5.3 (power modes, RF current, RTC memory, pin list)
- ESP-IDF Programming Guide (ESP32): Sleep Modes
- ESP-IDF Programming Guide (ESP32): Deep-sleep Wake Stubs (RTC_DATA_ATTR)
- ESP-IDF Programming Guide (ESP32): ADC Oneshot Mode Driver (ADC2 and Wi-Fi)
- Arduino-ESP32 documentation: ADC API
- Arduino-ESP32 documentation: Wi-Fi API
- Arduino-ESP32: NetworkClientSecure README (setCACert)
- Arduino-ESP32: esp32-hal-cpu.h (setCpuFrequencyMhz)
- PubSubClient (Arduino MQTT client) README
- OASIS MQTT Version 3.1.1 (ports 1883 and 8883, QoS levels)
- Battery University BU-802b: What does elevated self-discharge do?
اختبار يتاح بعد الخطوة الأخيرة.