Search code examples
arduinoesp8266arduino-esp8266esp32

Precise timing with DeepSleep on an ESP8266


I have a ESP8266, which I use to log weather data over MQTT. Because I want to save some power, I decided to use DeepSleep. Since I want to log the data, it would be good if I could send new entries every minute.

This used to work with my old sketch, where I had all data acquisition tasks in the loop section, and where I kept the connection to WiFi and the MQTT-Server open.

But this does not work with DeepSleep. I need to reconnect after every wake-up and after every wake-up, the ESP8266 basically reboots.

Because this does not take exactly the same time on every wake-up, I wanted to know if there is a way to let the ESP8266 log on exactly the same timestamps and go to DeepSleep in between?

This is a code sample of the DeepSleep algorithm:

String JSON = "{\"sensor\": \"Outdoor Sensor\", \"data\":[" + String(temp) + "," + String(hum) + "," + String(brightness) + "]}";
client.publish(topic, JSON.c_str(), true); //publish data as JSON to MQTT
delay(10); //somehow if this is not added, the data does not get logged.
Serial.println("Going into deep sleep for 60 seconds");
ESP.deepSleep(56e6); // because of microseconds - processing data takes about 4sec, but this is very unprecise

This is from PhpMyAdmin, in order to better visualize the problem:

enter image description here

If it can not be done with an ESP8266, might a ESP32 help?


Solution

  • It is suggested using an external RTC if time tracking is of importance. Using the internal RTC, improving meassurement of time passage during sleep apparently includes guessing at the sleeping chip's temperature:

    Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, while it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly once in deep sleep mode, calibration performed while the chip was active becomes useless mere moments after the chip has gone to sleep.

    http://arduino.stackexchange.com/questions/65530/ddg#65532

    Where high accuracy isn't required I would suggest to take a few samples and calculate the average interval error.

    example with 5 minutes intervals:

    excel calculation screenshot

    int32_t deep_sleep_time_compensation = -145000000; // chip temperature dependant deep sleep duration error compensation in μs
    ESP.deepSleep(300e6-micros()-deep_sleep_time_compensation); // because of microseconds; micros() is reset on wake-up