Go Down

Topic: Battery With DeepSleep (Read 290 times) previous topic - next topic


Nov 14, 2020, 06:17 pm Last Edit: Nov 14, 2020, 07:34 pm by ZeroSix
I'm having some issues using the cloud example to connect with azure.
Anyone managed to used ArduinoLowPower with MKRNB.h running on battery?
Actually im using thins but the device doesnt connect properlyou doesnt wake up.
Any Recommendations?

Code: [Select]

  for (int i = 0; i < 15; i++) {
    LowPower.deepSleep(60 * 1000 * 5); // wait 5 minutes


I may be missing something but it appears that the above code won't exit until 75 minutes have elapsed, 15 5 minute sleeps before the ''loop' will continue.  Is this your intention?  My thought is that you don't need the for loop if you want to have 5 minutes between messages. Maybe you don't need the sleep in a for loop?  Other things you might consider is to disconnect from Azure and powering off the modem before the sleep.  There's a post or two here with discussing minimizing power consumption in deepsleep.  


Thanks for the answer,
The ideia is to send information in periods of 5 minutes, I also tried to use LowPower.deepSleep(300000) without  the for.
(I updated the code)

The main problem is when I unplug the usb cable I cannot connect to the nb network
I also have a 3.7V 4000mah battery on Jst port

It's quite similar to this:

Code: [Select]
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include <utility/ECCX08SelfSignedCert.h>
#include <ArduinoMqttClient.h>
#include <MKRNB.h>
#include <ArduinoLowPower.h>
#include <DHT.h>

#include "arduino_secrets.h"

/////// Enter your sensitive data in arduino_secrets.h
const char pinnumber[]   = SECRET_PINNUMBER;
const char broker[]      = SECRET_BROKER;
String     deviceId      = SECRET_DEVICE_ID;

#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

NB nbAccess;
GPRS gprs;
NBScanner scannerNetworks;
NBClient      nbClient;            // Used for the TCP socket connection
BearSSLClient sslClient(nbClient); // Used for SSL/TLS connection, integrates with ECC508
MqttClient    mqttClient(sslClient);

float hum; //= 80; //Stores humidity value
float temp; //= 23; //Stores temperature value

void setup() {
  //while (!Serial);

  if (!ECCX08.begin()) {
    Serial.println("No ECCX08 present!");
    while (1);

  // reconstruct the self signed cert
  ECCX08SelfSignedCert.beginReconstruction(0, 8);

  // Set a callback to get the current time
  // used to validate the servers certificate

  // Set the ECCX08 slot to use for the private key
  // and the accompanying public certificate for it
  sslClient.setEccSlot(0, ECCX08SelfSignedCert.bytes(), ECCX08SelfSignedCert.length());

  // Set the client id used for MQTT as the device id


  // Set the username to "<broker>/<device id>/api-version=2018-06-30" and empty password
  String username;

  username += broker;
  username += "/";
  username += deviceId;
  username += "/api-version=2018-06-30";

  mqttClient.setUsernamePassword(username, "");

  // Set the message callback, this function is
  // called when the MQTTClient receives a message

void loop() {
  if (nbAccess.status() != NB_READY || gprs.status() != GPRS_READY) {

  if (!mqttClient.connected()) {

  LowPower.deepSleep(60 * 1000 * 5); // wait 5 minutes

unsigned long getTime() {
  // get the current time from the cellular module
  return 1604872551; // Value to avoid error -2

void connectNB() {
  Serial.println("Attempting to connect to the cellular network");

  while ((nbAccess.begin(pinnumber) != NB_READY) ||
         (gprs.attachGPRS() != GPRS_READY)) {
    // failed, retry

  Serial.println("You're connected to the cellular network");

void connectMQTT() {
  Serial.print("Attempting to MQTT broker: ");
  Serial.println(" ");

  while (!mqttClient.connect(broker, 8883)) {
    // failed, retry

  Serial.println("You're connected to the MQTT broker");

  // subscribe to a topic
  mqttClient.subscribe("devices/" + deviceId + "/messages/devicebound/#");

void publishMessage() {
  Serial.println("Publishing message");
  temp = dht.readTemperature();
  hum = dht.readHumidity();
  float batVoltage = analogRead(ADC_BATTERY) * 3.3 / 1023.0 * 1.275;
  int _batVoltage = batVoltage * 100;
  int _temp = (int)(temp * 100);
  int _hum = (int)(hum);
  String _signalStrengh = scannerNetworks.getSignalStrength();
  unsigned long timestamp = getTime();

  Serial.println(_batVoltage, BIN);
  char messageBytes[10];

  messageBytes[0] = (byte)(_temp & 0xFF);
  messageBytes[1] = (byte) ((_temp >> 8) & 0xFF);
  if (_temp < 0) {
    messageBytes[1] = messageBytes[1] | 0x80;

  messageBytes[2] = (byte)(_hum & 0xFF);
  messageBytes[3] = (byte)(_batVoltage & 0xFF);
  messageBytes[4] = (byte)((_batVoltage >> 8) & 0xFF);
  messageBytes[5] = (byte)(_signalStrengh.toInt());
  messageBytes[6] = (byte)(timestamp & 0xFF);
  messageBytes[7] = (byte)((timestamp >> 8) & 0xFF);
  messageBytes[8] = (byte)((timestamp >> 16) & 0xFF);
  messageBytes[9] = (byte)((timestamp >> 24) & 0xFF);

  // send message, the Print interface can be used to set the message contents
  mqttClient.beginMessage("devices/" + deviceId + "/messages/events/");


The main problem is when I unplug the usb cable I cannot connect to the nb network
I also have a 3.7V 4000mah battery on Jst port
What is the voltage at the 3.3V pin when running on the battery?


Nov 16, 2020, 04:17 pm Last Edit: Nov 16, 2020, 04:18 pm by ZeroSix
If im doing this right (Electronics is not my field)
I connected the Vcc(Arduino)-> V(Multimeter) and Ground(Arduino) - > Ground(Multimeter) to the multimeter

Normally stand at 3.22V, and I see some spikes going to 0.75V or 2.3V


You should have a very stable 3.3v at this pin. 3.3v is regulated via a LDO regulator from the 3.8v rail that the power management IC makes for the Modem. If you do not, I would guess that the Power management IC is damaged.


Nov 17, 2020, 02:13 am Last Edit: Nov 17, 2020, 02:17 am by ZeroSix
I tested again with more care(didnt had crocodile connetors on the last test) and time. Used 2 arduinos and the voltage is stable at 3.22/3.23 with three different batteries


There's not a chance that at some point in time that code was added to one of the library modules for debug purposes to initialize Serial and has a while(!Serial) is there?  I don't expect there is but I spent many years diagnosing problems and sometimes the problem was caused by something simple and took a long time to find.  


Not the case :)
I used the internal led to debug and I fount that stops waiting to connect to network, in some few cases goes to sleep but doesn't wake up,
Thanks for the help


You have a real puzzle.  I have some code similar to yours but I'm connecting to my own MQTT broker and not using SSL and I have intermittent problems connecting to the cellular network and MQTT broker no matter how it's powered. But most of the time it works.  I've spent way too many hours trying to get the 1500 to work reliable enough to actually use for the target project.  I've not had any problem with not waking from deepSleep.

I'm not using NBScanner so I just added NBScanner scannerNetworks; and scannerNetworks.begin(); and now my code hangs connecting cellular with or without USB.  I notice NBScanner begin does a Modem(begin) so maybe the modem gets confused.  If you haven't tried without NBScanner maybe it would be worth a try to see if it makes any difference.  


Nov 17, 2020, 04:38 pm Last Edit: Nov 17, 2020, 04:43 pm by icole
I don't recall failing to connect to cellular occurring before I moved to the unreleased MKRNB libraries but it hangs fairly frequently now.  Before moving to the newer libraries most of the hangs were MQTT related which still occur.   Are you using the unreleased libraries?  I moved to these as there's problems with handling modem power and reset in the libraries that Arduino IDE installs.  It seems to fail more often during the day than at night. 


The problem I'm having with the newer library code is related to the changes for managing power.  I'd added my own poweron and poweroff functions in accordance with the information in this forum and with it I seldom (possibly never) have a problem connecting to cellular.  I changed my code to use the power functions in the new Modem.cpp modules which is causing my problem connecting.  I'm returning to my own power management.  I think the issue with the new code is that it's keeping keeping the power status of the modem which may get out of sync.  In my code I power off the modem in setup.  At the top of the loop I power on the modem and at the end before the deepSleep power it off.  This way I have a known state of the modem and don't rely on keeping track with a variable.  Reading on the forum I understand what is attempting to be done which is to emulate the status pin on the modem since the status pin isn't connected on the 1500.  Be nice if the pin on the modem was connected.  


Hi Icole, thanks for the feedback
Im using the MKRNB version 1.3.2.
Im gonna remove the scanner and make some test's with different versions.
The real time in deepsleep normally is the amount o time thay you put? Some times the real took the double to wakeup.


I've not measured the actual sleep time but it appears it's waking up as expected.  And yes that is the time in milliseconds.  I have some code that's working fairly well right now.  It disconnects from MQTT broker, closes the socket, and powers off the modem before sleeping.  At the top of the loop it powers on the modem and connects to cellular, MQTT client, and etc.  Also using the software watchdog timer code which resets the 1500 if it hangs in a loop.  There are conditions that can occur where it's waiting on 'ready' which will never ever happen so the watchdog at least keeps from hanging for ever.  A downside of needing the watchdog is that all state is lost.  Would be nice if the library code could better handle 'exception' conditions.  I could share this code with you and allow you to use my unsecured Mosquitto MQTT broker if you would like to try it.  It's derived from my work in progress and not pretty.  Currently it seems to recover from all hangs and actually recovers from some MQTT connect errors.  


Hi again,
I  will try to resolve again from zero.
I was applying this to my master degree project . I confess I was not expecting all this problems.
I did the same for Lora (Arduino 1310) without much troubles. I applied a bridge on Lora devices to create a Layer of security.
Normally I can connect easily to the network. I will focus for now to have the device simple communication with battery. 
Can you please send the code? 
I think I will remove SSL for now.

Go Up