I have been trying to use LowPower.deepSleep() to extend the life of a battery pack which I have attached to a Nano 33 IoT. However, the sketch only runs for a few days before the batteries (4 x AA) get too run down to continue. (Sample size == 1 on the Nano 33 IoT. However, I consistently get a similar problem with a nearly identical sketch on a MKR1010 with LiPo.)
I've tried to guess as to where unnecessary power might be consumed, but have no clue. So I appreciate pointers or advice.
Obviously I have missed something, but specifically what I have missed eludes me. How do I go about debugging the sketch which makes frequent use of the LowPower.deepSleep() mode? The LowPower.deepSleep() mode prevents my usual debugging approach of powering it from USB and reading the output it sends to the serial monitor, as the monitor disconnects after the first deep sleep and never reconnects.
Also, am I using sodaq_wdt_enable() correctly to force a single restart? I presume the setting is no longer active once the board restarts. Or does the approach I have tip the board into a reboot loop?
One odd bit is that the epoch for the readings show 5 to 6 seconds after the 10-minute mark instead of the expected 0 to 1 second delay. At a greater wi-fi range, that delay is 12 to 13 seconds.
#include <SPI.h>
#include <WiFiNINA.h> // WiFi
#include <SSLClient.h> // TLS for MQTT
#include <PubSubClient.h> // MQTT
#include <WiFiUdp.h> // NTP is easier over UDP
#include <NTPClient.h> // network time
#include <Adafruit_SHTC3.h> // I2C temperature and humidity
#include <TimeLib.h> // min, sec, and set time
#include <RTCZero.h> // real-time clock, but no battery
#include <ArduinoLowPower.h> //
#include <Sodaq_wdt.h> // for restarting when WiFi fails completely
// For Nano 33 IoT
// Collect temperature and humidty data from an SHTc3
// every 10 minutes and transmit that via WiFi using
// MQTT over TLS
#define DEBUG 1
// custom settings
#include "wifi-secrets.h" // WiFi and MQTT credentials
#include "trust-anchors.h" // MQTT broker certificates
#include "my-certificates.h" // MQTT client certificates
/* for self-signed trust-anchors ...
* https://bearssl.org/
* python3 pycert_bearssl.py convert \
* --use-store certificate-authority.crt \
* server.crt
*/
// notes:
// https://github.com/arduino-libraries/WiFiNINA/blob/master/keywords.txt
// https://github.com/arduino-libraries/RTCZero/blob/master/keywords.txt
// https://github.com/arduino-libraries/ArduinoLowPower
// https://www.industrialshields.com/blog/arduino-industrial-1/building-an-mqtt-over-tls-connection-a-guide-for-esp32-plc-pss
// https://docs.arduino.cc/tutorials/mkr-wifi-1010/connecting-to-wifi-network/
// https://github.com/SodaqMoja/Sodaq_wdt
uint32_t WiFiStatus = WL_IDLE_STATUS; // the WiFi radio's status
const uint32_t INTERVAL = 10; // minutes to wait between readings
uint32_t epoch = 0; // current UNIX epoch time
RTCZero rtc;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, WLAN_NTP1, 0, 6000);
WiFiClient netClient;
// just in case we need to receive messages via MQTT
void callback(char* topic, byte* payload, unsigned int length) {
#ifdef DEBUG
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
#endif
for (int i = 0; i < length; i++) {
#ifdef DEBUG
Serial.print((char)payload[i]);
#endif
}
#ifdef DEBUG
Serial.println();
#endif
}
// Define MQTTS parameters
SSLClientParameters mTLS = SSLClientParameters::fromPEM(my_cert, sizeof my_cert, my_key, sizeof my_key);
SSLClient netClientSSL(netClient, TAs, (size_t)TAs_NUM, A5);
PubSubClient mqtt(MQTT_BROKER, 8883, callback, netClientSSL);
// temperature and humidity sensor
Adafruit_SHTC3 shtc3 = Adafruit_SHTC3(); // I2C address 0x70
// try to update the system clock via NTP
uint32_t timeClientLoop() {
#ifdef DEBUG
Serial.print("timeClient loop ");
#endif
timeClient.forceUpdate();
uint32_t epoch = timeClient.getEpochTime();
int i = 0;
// loop until the time has been fetched via NTP
while (!timeClient.update() && epoch < 1782232922) { // the && epoch is a kludge, update() never returns True
delay(i++ * 1000);
#ifdef DEBUG
Serial.print(".");
#endif
timeClient.forceUpdate();
epoch = timeClient.getEpochTime();
setTime(epoch);
}
#ifdef DEBUG
Serial.println(epoch);
#endif
return (epoch);
}
// try to (re-)connect to the WLAN
void attemptWiFiConnection() {
int count = 1;
while (WiFiStatus != WL_CONNECTED) {
/*
Serial.print("Attempting to connect to network: ");
Serial.println(WLAN_SSID);
Connect to WPA/WPA2 network:y
*/
WiFiStatus = WiFi.begin(WLAN_SSID, WLAN_PASS);
if (WiFiStatus != WL_CONNECTED) {
if (count++ > 50) {
// set watchdog timer to force reset
// after ~ 21 minutes have passed without success
sodaq_wdt_enable(WDT_PERIOD_1DIV64);
}
// wait with increasing intervals before new attempt
delay(500 * count);
}
}
#ifdef DEBUG
Serial.print(" ... Connected to ");
Serial.println(WLAN_SSID);
#endif
}
// one-off at the start of the script
void setup() {
#ifdef DEBUG
Serial.begin(9600);
delay(1250);
#endif
// start the onboard RTC
rtc.begin();
// attempt to connect to Wifi network:
WiFi.setHostname(WLAN_HOST);
WiFi.setDNS(WLAN_DNS1, WLAN_DNS2);
// Serial.print("Attempting Network Connection");
WiFiStatus = WiFi.begin(WLAN_SSID, WLAN_PASS);
attemptWiFiConnection();
// initialize the NTP client
timeClient.begin();
delay(250);
// attempt to connect to the MQTT broker
reconnectMQTT();
delay(250);
// try to update the time one more time
timeClient.update();
epoch = timeClientLoop();
setTime(epoch);
#ifdef DEBUG
Serial.print("Initial time: ");
Serial.println(epoch);
#endif
}
// display actual WiFi settings
void printWiFiData() {
IPAddress ip = WiFi.localIP();
Serial.print(ip);
Serial.print(", ");
Serial.print("SSID: ");
Serial.print(WiFi.SSID());
Serial.print(", ");
Serial.print("signal strength (RSSI):");
Serial.println(WiFi.RSSI());
}
// reconnect to MQTTS
void reconnectMQTT() {
// Loop until we're reconnected
#ifdef DEBUG
Serial.print("Attempting MQTT connection");
#endif
int count = 1;
while (!mqtt.connected()) {
// Attempt to (re-)connect to MQTT
if (mqtt.connect(MQTT_CLIENT, MQTT_USER, MQTT_PASS)) {
#ifdef DEBUG
Serial.println(" MQTT connected");
#endif
delay(0); // is this the best way for place holder / NOP ??
} else {
#ifdef DEBUG
Serial.print("failed, rc=");
Serial.print(mqtt.state());
Serial.println(" try again in half a second");
#endif
delay(500L * count);
attemptWiFiConnection();
if(count++ > 10) {
sodaq_wdt_enable(WDT_PERIOD_1DIV64);
}
}
}
}
// get the temperature and humidity readings and publish them via MQTT
void measure() {
// attempt to connect to Wifi network:
attemptWiFiConnection();
// reconnect to the MQTT broker if necessary
while (!mqtt.loop()) {
reconnectMQTT();
}
epoch = timeClientLoop();
String e = String(epoch);
#ifdef DEBUG
Serial.println(" ");
Serial.print("Epoch ");
Serial.println(e);
#endif
// attempt to find the SHTc3 sensor
while (!shtc3.begin()) {
delay(2000);
#ifdef DEBUG
Serial.println("Couldn't find SHTC3");
#endif
LowPower.deepSleep(12000UL);
}
sensors_event_t humidity, temperature;
// populate temp and humidity objects with fresh data
shtc3.getEvent(&humidity, &temperature);
#ifdef DEBUG
Serial.print("Formatted time ");
Serial.print(timeClient.getFormattedTime());
Serial.print(" utc ");
Serial.println(e);
#endif
String t = String(temperature.temperature);
// LLL
// t = String(WiFi.RSSI()); // LLL
String h = String(humidity.relative_humidity);
String msg1 = e + "\t8\t" + t;
String msg2 = e + "\t4\t" + h;
// check again for MQTT connectivity
while (!mqtt.loop()) {
reconnectMQTT();
}
// Serial.println("trying to publish temperature");
// try to publish the temperature via MQTT
if (mqtt.publish("sensors/temperatures", msg1.c_str(), msg1.length())) {
#ifdef DEBUG
Serial.print(" ");
Serial.println(msg1);
#endif
delay(0);
} else {
#ifdef DEBUG
Serial.println(" ... not published");
#endif
delay(0);
}
// check again for MQTT connectivity
while (!mqtt.loop()) {
reconnectMQTT();
}
// Serial.println("trying to publish humidity");
// try to publish the humidity via MQTT
if (mqtt.publish("sensors/humidity", msg2.c_str(), msg2.length())) {
#ifdef DEBUG
Serial.print(" ");
Serial.println(msg2);
#endif
delay(0);
} else {
#ifdef DEBUG
Serial.println(" ... not published");
#endif
}
// one last MQTT connectivity test to ensure publication
mqtt.loop();
while (!mqtt.loop()) {
reconnectMQTT();
}
}
// calculate the number of seconds to the next time interval
uint32_t secondsUntilNextBoundary() {
timeClient.update();
uint32_t s = timeClient.getSeconds();
uint32_t m = timeClient.getMinutes();
int32_t dm = INTERVAL - (m + INTERVAL) % INTERVAL - 1;
int32_t ds = 60L - s;
int32_t nextBoundary = 0UL;
if (dm > 0L) {
nextBoundary = dm * 60L + ds;
} else {
nextBoundary = ds;
}
#ifdef DEBUG
Serial.print("T: ");
Serial.print(m);
Serial.print(":");
Serial.print(s);
Serial.print(" ");
Serial.println(nextBoundary);
#endif
return (nextBoundary * 1000UL);
}
// main loop
void loop() {
if (sodaq_wdt_flag) {
// if the WDT interrupt was triggered
sodaq_wdt_flag = false;
// sodaq_wdt_reset();
}
#ifdef DEBUG
Serial.begin(9600);
#endif
measure();
uint32_t sleepMs = secondsUntilNextBoundary();
if (sleepMs) {
#ifdef DEBUG
Serial.print("deepSleep for ");
Serial.print(sleepMs);
Serial.print(" milliseconds");
#endif
LowPower.deepSleep(sleepMs);
}
}