Make an ESP32 sensor sleep between readings with deep sleep

Most sensors don't need to work all the time. In this lesson the ESP32 wakes up, reads a DHT11, remembers the last readings and goes back into deep sleep, where the chip itself uses only microamps. You also find out...
  • Level:Intermediate
  • Duration: 45 min
  • Ages 12+
  • Platform: ESP32

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Make an ESP32 sensor sleep between readings with deep sleep – EEMENTOR STEM™ lesson

A weather sensor in the garden only needs a new reading every few minutes. If the ESP32 stays awake in between, it wastes almost all of its energy waiting. The ESP32 has a trick for this: deep sleep. It switches off nearly everything, sets an alarm clock, and wakes up when it's time for the next reading. In this lesson you build a sensor that wakes up, reads the temperature and humidity from a DHT11, remembers the last five readings while it sleeps, and goes straight back to sleep. You'll also learn what "low power" really means on a development board, and how to check it with a multimeter.

What you'll learn

  • What deep sleep is, and what stays on while the ESP32 sleeps
  • How to wake the ESP32 up with a timer
  • Why the program starts again from setup() after every sleep
  • How to keep values while it sleeps with RTC_DATA_ATTR
  • Why a development board uses far more power in sleep than the ESP32 chip itself

What you need

  • ESP32 board, expansion board and USB cable (ESP32 IoT Starter Kit)
  • DHT11 temperature and humidity module (ESP32 IoT Starter Kit)
  • Breadboard and jumper wires (ESP32 IoT Starter Kit)
  • The free Arduino IDE with the ESP32 boards installed (see Set up the ESP32 in the Arduino IDE), and the DHT sensor library by Adafruit from the Library Manager
  • Optional: a multimeter, to measure the current (see the multimeter lesson)

Wiring

The DHT11 module has three pins: S (signal), + and −. It runs happily on the ESP32's 3.3 V. Follow the labels printed on your module.

Breadboard wiring diagram: DHT11 module with S to ESP32 GPIO 27, plus to 3V3 and minus to GND.
Breadboard view. Check each connection against the wiring table below.
From To
DHT11 S ESP32 GPIO 27
DHT11 + ESP32 3V3
DHT11 − ESP32 GND
FREE

Build this circuit in EEMENTOR Lab

Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.

The ESP32 and the parts for this lesson laid out in EEMENTOR Lab, ready to wireBuild it yourself
  1. The ESP32 and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
  2. Missing a part? Add it from the parts list on the left.
  3. Press Run, then try the inputs: click, hold or slide them under Selected.
  4. The Lab doesn’t simulate deep sleep, so use it to build and check the DHT11 wiring before you upload the real sketch.

EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab

The sketch

Choose ESP32 Dev Module as the board, select the port, upload the sketch and open the Serial Monitor at 115200 baud. If the upload doesn't start because the ESP32 is asleep, hold the BOOT button on the board while you click Upload.

// Make an ESP32 sensor sleep between readings with deep sleep
#include <DHT.h>

const int DHT_PIN = 27;
const int LED_PIN = 2;                       // the blue LED on the ESP32 board
const uint64_t SLEEP_SECONDS = 20;           // 20 s for testing; try 600 (10 minutes) later
const uint64_t MICROSECONDS_PER_SECOND = 1000000ULL;

DHT dht(DHT_PIN, DHT11);

// Kept in the ESP32's RTC memory while it sleeps (lost when the power is removed)
RTC_DATA_ATTR int wakeCount = 0;
RTC_DATA_ATTR float history[5];
RTC_DATA_ATTR int stored = 0;

void setup() {
  Serial.begin(115200);
  delay(500);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);               // the LED shows that it is awake
  wakeCount++;

  if (esp_sleep_get_wakeup_cause() == ESP_SLEEP_WAKEUP_TIMER) {
    Serial.printf("Woke up from deep sleep (wake-up number %d)\n", wakeCount);
  } else {
    Serial.println("Powered on or reset: starting fresh");
  }

  dht.begin();
  delay(1500);                               // give the DHT11 a moment
  float t = dht.readTemperature();
  float h = dht.readHumidity();
  if (isnan(t) || isnan(h)) {
    Serial.println("The DHT11 is not answering: check the wiring");
  } else {
    Serial.printf("Temperature %.1f C, humidity %.0f %%\n", t, h);
    for (int i = 4; i > 0; i--) history[i] = history[i - 1];   // move the old ones along
    history[0] = t;
    if (stored < 5) stored++;
    Serial.print("Last readings:");
    for (int i = 0; i < stored; i++) Serial.printf(" %.1f", history[i]);
    Serial.println();
  }

  Serial.printf("Going to sleep for %llu seconds...\n\n", SLEEP_SECONDS);
  Serial.flush();                            // finish sending before the power goes down
  digitalWrite(LED_PIN, LOW);
  esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * MICROSECONDS_PER_SECOND);
  esp_deep_sleep_start();                    // the program stops here
}

void loop() {
  // Never reached: after every sleep the ESP32 starts again from setup()
}

Try it

  1. Upload the sketch and open the Serial Monitor. It says "Powered on or reset", prints a reading and goes to sleep. The blue LED goes out.
  2. Wait 20 seconds. The LED flashes on, the Serial Monitor says "Woke up from deep sleep (wake-up number 2)", and there are now two readings in the list.
  3. After a few wake-ups the list holds the last five readings, even though the program started again each time.
  4. Press the EN (reset) button. The count starts again at 1 and the list is empty: a reset clears the RTC memory too.
  5. Change SLEEP_SECONDS to 600, so the sensor wakes up every 10 minutes like a real weather station.

What you should see

Serial Monitor at 115200 baud: the first start with one reading, then a wake-up from deep sleep 20 seconds later with two readings remembered in RTC memory.
Each wake-up remembers the readings before it.

How it works

How it works: short awake moments between long deep sleeps, which parts stay on (only the RTC timer and RTC memory), and current: 20 to 68 milliamps awake, about 10 microamps for the chip asleep, a few milliamps for a development board asleep.
Sleep, wake, read, sleep again.

In deep sleep, the ESP32 switches off its processors, its main memory, Wi-Fi and Bluetooth. Only a tiny part called the RTC (real-time clock) keeps running, with its own timer and a few kilobytes of memory. esp_sleep_enable_timer_wakeup() sets that timer in microseconds (that's why 20 seconds becomes 20,000,000), and esp_deep_sleep_start() goes to sleep. When the timer runs out, the ESP32 wakes up and starts the program from the very beginning, just like after pressing reset. That's why everything happens in setup() and loop() stays empty.

Normal variables are lost when the ESP32 sleeps, because the main memory is switched off. Variables marked RTC_DATA_ATTR are stored in the RTC memory instead, which stays powered, so wakeCount and history survive. esp_sleep_get_wakeup_cause() tells the program whether it woke up from the timer or was just switched on.

How much does this save? According to Espressif's datasheet, the ESP32 chip uses about 10 µA in deep sleep with the RTC timer running, compared with 20–68 mA when the processor is awake, and more when Wi-Fi is sending. But your development board has other parts that don't sleep: the power LED, the USB-to-serial chip and the voltage regulator keep drawing current. On many boards that adds up to a few milliamps or more. That's still far less than staying awake, but for months on batteries, makers use a bare ESP32 module with an efficient regulator and no power LED.

Try this next

  • Measure the current: power the board through a USB power meter, or through a multimeter in series with a battery pack, and compare awake and asleep.
  • Send each reading to the cloud before going back to sleep, using what you learned in the ThingSpeak weather logger. Keep the Wi-Fi part short: every second awake costs energy.
  • Wake up with a button instead of the timer, using esp_sleep_enable_ext0_wakeup() on an RTC-capable pin.
  • Only print a message when the temperature changes by more than 0.5 °C since the last reading.

Troubleshooting

  • The upload fails with "Failed to connect": the ESP32 was asleep. Hold the BOOT button, click Upload, and let go when the IDE says "Connecting...".
  • The Serial Monitor shows nothing after a wake-up: some computers need a moment to reconnect the USB port after the board wakes up. The first line may be missed; wait for the next wake-up.
  • The count always says 1: the board is being reset, not woken up. Check that the USB cable is good and that nothing presses the EN button.
  • "The DHT11 is not answering": check that S goes to GPIO 27, + to 3V3 and − to GND, and that the DHT sensor library is installed.
  • The power LED stays on during sleep: that's normal. It is wired straight to the power supply, not to the ESP32.