Power draining on Nano 33 IoT

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);
  }
}

Have you considered a serial-to-usb adapter connected to the Rx and Tx pins. You will need to change the sketch so it prints to something like Serial1 (I'm not that familiar with your boards to know for sure).

Alternatively you can hack a USB cable and disconnect the power.

A arduino nano iot has other stuff on the pcb which consumes power and that might be why you cannot get the result you want.

wifi , gyro, power supply etc etc.

schematic

At this point I do not even know where to start guessing because I do not have enough information to know exactly what you are working with.

Please post an annotated schematic showing how everything is connected. Include all power sources, battery connections, regulators, grounds, and any peripheral devices connected to the Nano 33 IoT.

Also post links to the technical information for each hardware device you are using, and a link to the exact Arduino Nano 33 IoT schematic or board documentation that applies to your board.

With that information, we can determine what is actually consuming power and whether LowPower.deepSleep() is addressing the major loads or only a small part of the total current draw. Note any modifications you may have made.

I think the main issue is the NINA WiFi module. LowPower.deepSleep() sleeps the SAMD21, but the WiFi hardware might still be drawing significant current. I would measure the actual sleep current and compare it with WiFi connected versus disconnected or powered down.

The 5 to 13 second offset also looks expected. You wake at the boundary, then spend several seconds on WiFi, NTP, MQTT, and sensor work. Poorer WiFi means a larger delay.

For debugging, temporarily use a short sleep interval while running from USB, or log values somewhere other than Serial.

I would also double-check the watchdog behavior. Once sodaq_wdt_enable() fires, make sure you are not ending up in an unintended reset loop.

Thanks. What tool (if any) is recommend for the drawing?

When the Nano 33 IoT is not on battery, and is plugged in via USB instead, I have the USB cable, plus the SHTc3 (see below)

When I had it connected to the 6V battery pack, and not on USB, the pack was connected by +6V on VIN and GND on the opposite side, plus the SHTc3.

The SHTc3 remains connected whether powered from battery pack or from USB.

It is connected to +3V3, A4 (SDA), A5 (SCL), and the GND on the same side.

Thanks. I have added WiFi.end(); after the measurements are taken and have been sent.

I have also added a sodaq_wdt_disable(); to the beginning of the main loop(). I suspect it is the absence of that which caused the problem.

I'll also wire up the board for Serial1 use, but that may take a few days to arrange.

I had expected that those are all off until specifically activated. Is that assumption correct?

That you need to research , I wouldn’t have thought you could stop them taking power - there is a gyro , wi fi , IC2 pull-ups ? etc on that board . ChatGPT suggests these/some? parts can be turned off , but are on by default.

If low power is your need , then you might. Be better using a bare bones processor with out the add ons on a custom board , it’s under your control then - Google or AI can help, and Nick Gammon has done great stuff for other processors .

Without knowing how the battery is connected, what voltage it supplies, what regulator is being used, and what peripherals remain powered during sleep, his battery consumption can't really be diagnosed. The Nano 33 IoT processor could be sleeping correctly while something else is consuming most of the current. This cannot be accurately determined without an annotated schematic. Good Luck!

I have a diagram in Fritzing, exported to both PNG (55kB) and GIF (29kB) but the forum won't let me upload either one — either with the upload button or by pasting the image into the editor. :confused:

"Sorry, there was an error uploading image.png. Please try again."

The battery pack has 4 x 1.5 V LR6 measured at 6.45V when fresh.

Sorry a frizzy does not contain the needed information, it is just a wiring diagram.

Could you please link to

Would you be able to link to a positive example from another post either here or elsewhere?

You need to get to Trust level 1 to upload

Requirements for Trust Level 1
Get to trust level 1 by completing these exact steps:

  • Go to at least 5 topics and read them
  • Read at least 30 posts
  • Spend a total of 10 minutes reading posts

You do not need to reply, like, or create posts to reach this level

Fritzing diagrams are OK

With trust level 0 (TL0) you should be able to drag-and-drop a file in the composer or paste a screenshot in the composer.

I've had it running from a USB power supply for a few days now. The modified sketch seems to survive WLAN hiccoughs with those modifications, unlike before.

I tried it on battery briefly with an ammeter wired in for some current measurements. While supposedly idling, the current draw rotated continuously between a number of values with the upper being ~ 55mA and the lower being ~ 25mA. I would have expected lower, steadier current draw for LowPower.deepSleep(). And it looks like I'll have to find a different battery arrangement to get the longevity I hope for.

Perhaps there is still something further to turn off. The [url=https://docs.arduino.cc/resources/datasheets/ABX00027-datasheet.pdf\]power tree on page 8[/url] of the documentation shows the SAMD21G18 and Nina-102 and the user sketch as potential hogs. I would have thought that LowPower.deepSleep() takes care of the SAMD21G18 and the activities of the sketch, and that WiFi.end() would have dealt with the Nina-102.

Well the Nano 33iot was a poor choice if you need to conserve battery power. You might consider using a TPL5110 to cut power to everything.

Thanks. Well at least it was fun and I have learned at least a little. I can use the Nano 33 IoT board in another project soon anyway, one with a wall wart for a power supply.

Which board(s) would be more appropriate for very low power? My requirements are I²C plus either WiFi or LoRa. The Nano ESP32 looks like it might be one option. Is there something even stingier with the electricity?

I don't think any official arduino board is really optimized for battery power.
Seed Studio claims 15uA deep sleep for their Esp32-S3 and -C6 boards and they have lithium battery management onboard.

Depends, how do you plan on waking up the board?