Long deep sleep

Updated on 3 September 2021
dev board WeMos D1 Mini
chip ESP8266
features sleep EEPROM wakeup
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Before starting

Pre-requisites

Try these simpler or similar examples:

Buy the components

Code

Download code long-sleep.ino
#include <EEPROM.h>

const int sleepTime = 1200;  // 1200 seconds = 20 minutes

#define FINAL_SLEEP_INTERVAL 6  // 6 * sleepTime = 6 hours
#define CURRENT_SLEEP_INTERVAL_ADDR 30  // Store sleep interval
#define CURRENT_SLEEP_INTERVAL EEPROM.read(CURRENT_SLEEP_INTERVAL_ADDR)

void setup() {
  EEPROM.begin(512);
  Serial.begin(115200);
  pinMode(2, OUTPUT);
  Serial.println("[INFO] Wake up!");

  if (CURRENT_SLEEP_INTERVAL == FINAL_SLEEP_INTERVAL) {
    blink(5);
    resetSleepInterval();
    doSomething();
    goToSleep();
  } else {
    blink(5);
    increaseSleepInterval();
    goToSleep();
  }
}

void blink(int times) {
  for (int i=0; i <= times; i++) {
    digitalWrite(2, HIGH);
    delay(1000);

    digitalWrite(2, LOW);
    delay(1000);
  }
}
void loop() {}

void doSomething() {
  Serial.println("[INFO] Hey do something finally :)");
}

void goToSleep() {
  ESP.deepSleep(sleepTime * 1000000);
}

void resetSleepInterval() {
  EEPROM.write(CURRENT_SLEEP_INTERVAL_ADDR, 1);
  EEPROM.commit();
}

void increaseSleepInterval() {
  EEPROM.write(CURRENT_SLEEP_INTERVAL_ADDR, CURRENT_SLEEP_INTERVAL + 1);
  EEPROM.commit();
}

Makefile

.PHONY: lint compile upload clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright *.ino

compile:
	arduino-cli compile --fqbn esp8266com:esp8266:d1_mini ./

upload:
	arduino-cli upload -p /dev/cu.wchusbserial1410 --fqbn esp8266com:esp8266:d1_mini ./

clean:
	rm -f .*.bin
	rm -f .*.elf

flash: lint compile upload clean

Description

Sleep for more than 1 hour using EEPROM to keep the count. Technically, this is not sleeping for more than 20 minutes, the maximum possible deep sleep, but it will keep a count every time it wakes up so that at the correct count, it will possibly enable the radio and do a desired task.

If only ESP8266 is used, short pin D0 to pin RST to enable wakeup.

References