ENع
→Capstone node
الدرس 53 · Connectivity and the capstone node

Capstone: a battery sensor node

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 53 · تفاعلي
01 / 09

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()
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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()
  2. 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 there
  3. Read 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 = 1
  4. Five 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 send
  5. Join 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 mA
  6. One 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 true
  7. Clear, 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 µA
  8. When 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 wake
  9. 146 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

اختبار يتاح بعد الخطوة الأخيرة.