
Hey everyone, welcome back to the Electron Parade! If you’ve ever built a portable ESP32 project, you’ve probably noticed that these powerful little microcontrollers can be quite the energy hogs. Leave it running on a standard LiPo battery, and it might be dead in a few days—or even hours!
But what if I told you there’s a way to make that same battery last for months, or even years? Enter the magic of Deep Sleep.
In this lesson, we’re going to dive into how you can put your ESP32 into a low-power hibernation state and wake it up only when it needs to do some work. This is the ultimate battery super-saver technique.
When an ESP32 is running normally (with Wi-Fi and Bluetooth on), it can consume upwards of 240mA. That drains batteries fast! But in Deep Sleep mode:
Putting the ESP32 to sleep is surprisingly simple. We use the built-in ESP-IDF functions exposed through the Arduino core.
Here’s a basic example that wakes up every 10 seconds, prints a message, and goes back to sleep:
#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 10 /* Time ESP32 will go to sleep (in seconds) */
RTC_DATA_ATTR int bootCount = 0; // Stored in RTC memory, survives deep sleep
void setup() {
Serial.begin(115200);
delay(1000); // Take some time to open up the Serial Monitor
// Increment boot number and print it every reboot
++bootCount;
Serial.println("Boot number: " + String(bootCount));
// Configure the wake up source
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + " Seconds");
// Go to sleep now
Serial.println("Going to sleep now");
Serial.flush();
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
void loop() {
// This is not going to be called
}
RTC_DATA_ATTR are saved in the RTC memory and won’t be erased when the device goes to sleep.esp_sleep_enable_timer_wakeup), but you can also wake the ESP32 using external pins (like a button press or sensor interrupt) or even the touch pins.setup() only: Notice how loop() is empty? Every time the ESP32 wakes from Deep Sleep, it reboots and runs setup() from the very beginning.Start experimenting with Deep Sleep on your battery-powered projects, and watch your uptime skyrocket! Let me know in the comments what you’re building. See you in the next lesson!
To follow along with this lesson, you’ll need the following components: