What You Will Build
A weather display that you can put on a shelf and forget about. An ESP32 wakes up every 30 minutes, joins Wi-Fi, asks OpenWeatherMap for the current conditions, draws them on a 2.9-inch e-paper screen, and goes straight back into deep sleep. Because e-paper keeps its image without power, the screen stays readable while the processor is asleep.
The project is about much more than weather. It is a practical lesson in low-power design, and it is where most battery projects go wrong. A deep-sleeping ESP32 chip can draw tens of microamps, yet a typical development board can burn milliamps in the same state. This guide shows you the arithmetic, the hardware choices that decide the result, and firmware that behaves well when Wi-Fi, the API or the battery misbehaves.
What you will learn:
- How deep sleep works, what survives it and what does not
- How to calculate a battery budget, and why you must measure it
- Why a bare ESP32 with a low-quiescent regulator can outlast a dev board by a factor of ten
- How to drive a GxEPD2 e-paper display and hibernate it
- How to write a wake cycle with timeouts, retries, stale-data marking and low-battery protection
Time: a weekend, including measurement. Skill level: advanced, because the power stage matters as much as the code.
How a Deep-Sleep Cycle Works
When an ESP32 enters deep sleep, it switches off the CPU, most of the RAM and the Wi-Fi radio. Only the real-time clock (RTC) section stays alive to count down a timer, and a small block of RTC memory keeps its contents. When the timer fires, the chip restarts from the beginning: setup() runs again, ordinary variables are back to their initial values, and loop() is never reached.
Two consequences shape the whole design:
- All the work happens in
setup(). The sketch wakes, does its job, and sleeps. Theloop()function stays empty. - State must live in RTC memory. Variables marked
RTC_DATA_ATTRsurvive sleep. This sketch uses them for a boot counter, a failure counter and the last good weather reading, so a failed update can show old data marked as stale instead of a blank screen.
The flowchart shows one complete cycle, including the failure and low-battery paths.
The Power Budget, Done Honestly
Battery life is a weighted average of two very different states. The device spends a few seconds awake at a high current and the rest of the time asleep at a tiny one:
average current = (awake time × awake current + sleep time × sleep current) ÷ cycle time
battery life = usable capacity ÷ average currentTake a 3000 mAh cell, of which about 80% is realistically usable, a 30-minute cycle, and an awake period of 10 seconds at an average of about 100 mA. Those 10 seconds cost 1000 mA·s per cycle, or about 0.56 mAh per hour over two cycles. Now the sleep current decides everything:
| Hardware | Typical sleep current | Estimated life (upper bound) |
|---|---|---|
| Dev board as sold (linear regulator, USB chip, LED) | around 5 mA | about 18 days |
| Battery-oriented board | around 100 µA | about 150 days |
| Bare module with a low-quiescent regulator | around 30 µA | about 170 days |
The numbers are illustrative, and they are upper bounds before self-discharge, retries, cold weather and converter losses. They make a clear point. The chip is not the problem. The board around it is. A common development board uses a linear regulator that draws milliamps even when nothing is running, plus a USB-to-serial chip and a power LED. Those parts can use a hundred times more current than the ESP32 itself in deep sleep.
Measure your own number
Treat any runtime figure, including the table above, as a hypothesis until you measure it:
- Put a multimeter in series with the battery supply, using a range that can read tens of microamps. Many meters have a µA range, but their series resistance can cause a voltage drop when the board wakes and draws hundreds of milliamps. A bypass switch or a dedicated power profiler avoids that.
- Let the device finish a full cycle and note the sleep current after the Wi-Fi has been switched off and the display has hibernated.
- Measure the awake time and current over several wake cycles, since Wi-Fi connection time varies with signal strength.
- Use the formula above with your measured values, and leave margin for battery ageing and temperature.
If your sleep current is in the milliamp range, look at the board, not the code: remove or bypass the power LED, avoid the 5 V regulator path, and check which parts stay powered when USB is unplugged.
Components
9 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Choosing and Understanding the E-Paper Display
E-paper (e-ink) uses tiny charged pigment particles. Once an image is drawn, the particles stay put with no power at all, which is why e-paper suits a deep-sleeping device. The trade-offs are slow updates (a full refresh of a 2.9-inch black-and-white panel typically takes a couple of seconds) and a recommended minimum interval between refreshes (manufacturers commonly advise not refreshing more often than every few minutes). A 30-minute cycle is well inside that guidance.
The model gotcha
GxEPD2 supports dozens of panels, and each one has its own class. The sketch uses GxEPD2_290_T5D as an example, but a 2.9-inch module sold under the Waveshare name may have a different controller depending on its revision. If the screen stays blank or shows garbage, the most likely cause is a class that does not match the panel. Check the label on the module, then look up the correct class in the GxEPD2 library's README and examples, and confirm with the library's own minimal example before adding Wi-Fi.
Full refresh versus partial refresh
Partial refresh is faster, but it leaves ghosting that a periodic full refresh must clear, and it needs extra care after the display has been hibernated. With an update every 30 minutes, the energy saved by partial refresh is small, so this project uses a clean full refresh and then calls hibernate(), which puts the panel into its lowest-power state while it keeps showing the image.
Wiring and Power
The e-paper module connects over SPI. The data and clock lines use the ESP32's default SPI pins (CLK on GPIO18, DIN on GPIO23), and the sketch assigns the other four pins itself.
| E-paper pin | ESP32 pin |
|---|---|
| VCC | 3V3 |
| GND | GND |
| DIN (MOSI) | GPIO23 |
| CLK | GPIO18 |
| CS | GPIO5 |
| DC | GPIO17 |
| RST | GPIO16 |
| BUSY | GPIO4 |
Battery sense. To read the cell voltage, connect two 1 MΩ resistors in series from battery positive to ground and take GPIO35 from the midpoint, with a 100 nF capacitor across the lower resistor. The divider halves the voltage so a full 4.2 V cell reads about 2.1 V, safely inside the ADC range. At 1 MΩ each, the divider draws about 2 µA, which is small compared with the rest of the budget. A pair of 100 kΩ resistors would waste around 21 µA continuously and noticeably shorten battery life. The capacitor supplies the burst of charge the ADC needs, so the high-impedance divider reads accurately.
Power path. Feed the cell, through a regulator, straight into the ESP32 module's 3.3 V supply. A boost converter to 5 V followed by the dev board's own regulator wastes energy twice and keeps more parts powered than necessary. Choose an LDO that can deliver at least 500 mA, because Wi-Fi transmit peaks are much higher than the average, and keep a bulk capacitor close to the ESP32.
🚨 Danger
Lithium-ion cells need protection. Use a protected 18650 (or a charger module that includes over-discharge and short-circuit protection), check polarity twice, and never charge a swollen, dented or damaged cell. A bare TP4056 board does not protect the cell from over-discharge unless it includes the protection circuit. Never leave a charging cell unattended. Do not connect USB and a separately regulated battery supply to the same board at the same time unless the board's power path is designed for it.
💡 Tip
If you keep a standard dev board for the first build, you can still use it to prove the software. Build the firmware on USB power first, then move to the battery power path. Measure sleep current at each step, so you know exactly which change helped.
Getting Ready
- OpenWeatherMap key. Create a free account and generate an API key. New keys can take a short while to activate, so a "401" error right after signing up is normal. The free plan's rate limits are far above one request every 30 minutes.
- City ID. Find your city on openweathermap.org and copy the number from its URL into
CITY_ID. - Libraries. In the Library Manager, install GxEPD2 and ArduinoJson (version 7). The sketch uses
JsonDocument, which belongs to ArduinoJson 7. - Board. Select ESP32 Dev Module in the Arduino IDE.
Never publish your Wi-Fi password or API key. The sketch uses placeholders. Keep your real values in a local copy only.
The Firmware
The sketch below is organised around the wake cycle. It checks the battery first, connects with a timeout, fetches over HTTPS, saves a good result in RTC memory, redraws the screen only when there is something new to show, and then picks a sleep time.
// ESP32 + 2.9" e-paper weather display, built for deep sleep
// Libraries: GxEPD2, ArduinoJson 7
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <GxEPD2_BW.h>
#include <Fonts/FreeMonoBold9pt7b.h>
#include <Fonts/FreeSansBold18pt7b.h>
// ---- Your settings ----
#define WIFI_SSID "YOUR_WIFI"
#define WIFI_PASS "YOUR_PASS"
#define OWM_API_KEY "YOUR_OPENWEATHERMAP_KEY"
#define CITY_ID "1261481" // Delhi; find yours at openweathermap.org
// ---- Timing ----
const uint32_t SLEEP_MIN = 30; // normal update interval
const uint32_t RETRY_MIN = 5; // retry after a failure
const uint32_t LOW_BATT_SLEEP_MIN = 24 * 60; // very long nap when the cell is low
const uint8_t MAX_FAST_RETRIES = 5; // then fall back to SLEEP_MIN
const unsigned long WIFI_TIMEOUT_MS = 15000;
// ---- Battery sense: two 1 MOhm resistors halve the cell voltage ----
const bool USE_BATTERY_SENSE = true;
const int BATTERY_PIN = 35;
const int BATTERY_LOW_MV = 3300;
// ---- E-paper pins (SPI CLK = GPIO18, DIN = GPIO23 by default) ----
#define EPD_CS 5
#define EPD_DC 17
#define EPD_RST 16
#define EPD_BUSY 4
// The class must match YOUR panel. Check the GxEPD2 README table.
GxEPD2_BW<GxEPD2_290_T5D, GxEPD2_290_T5D::HEIGHT> epd(
GxEPD2_290_T5D(EPD_CS, EPD_DC, EPD_RST, EPD_BUSY));
struct WeatherData {
char city[24];
float tempC;
float feelsLike;
int humidity;
float windKmh;
char description[26];
bool valid;
};
// RTC memory survives deep sleep (normal RAM does not)
RTC_DATA_ATTR uint32_t bootCount = 0;
RTC_DATA_ATTR uint8_t failCount = 0;
RTC_DATA_ATTR WeatherData lastWeather = {"", 0, 0, 0, 0, "", false};
int readBatteryMv() {
uint32_t sum = 0;
for (int i = 0; i < 8; i++) {
sum += analogReadMilliVolts(BATTERY_PIN);
delay(2);
}
return (sum / 8) * 2; // undo the divider
}
bool connectWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
const unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED) {
if (millis() - start > WIFI_TIMEOUT_MS) return false;
delay(100);
}
return true;
}
bool fetchWeather(WeatherData& w) {
WiFiClientSecure client;
client.setInsecure(); // encrypts, but does not verify the server
HTTPClient http;
http.setTimeout(8000);
String url = String("https://api.openweathermap.org/data/2.5/weather?id=") +
CITY_ID + "&appid=" + OWM_API_KEY + "&units=metric";
if (!http.begin(client, url)) return false;
const int code = http.GET();
if (code != 200) {
Serial.printf("HTTP error: %d\n", code);
http.end();
return false;
}
String body = http.getString();
http.end();
JsonDocument doc;
if (deserializeJson(doc, body)) return false;
if (doc["main"]["temp"].isNull()) return false;
strlcpy(w.city, doc["name"] | "Unknown", sizeof(w.city));
strlcpy(w.description, doc["weather"][0]["description"] | "", sizeof(w.description));
w.tempC = doc["main"]["temp"] | 0.0f;
w.feelsLike = doc["main"]["feels_like"] | 0.0f;
w.humidity = doc["main"]["humidity"] | 0;
w.windKmh = (doc["wind"]["speed"] | 0.0f) * 3.6f; // m/s to km/h
w.valid = true;
return true;
}
void drawWeather(const WeatherData& w, bool stale, int battMv) {
epd.setRotation(1); // landscape: 296 x 128
epd.setFullWindow();
epd.firstPage();
do {
epd.fillScreen(GxEPD_WHITE);
epd.setTextColor(GxEPD_BLACK);
epd.setFont(&FreeMonoBold9pt7b);
epd.setCursor(4, 16);
epd.print(w.city);
if (stale) {
epd.setCursor(210, 16);
epd.print("STALE");
}
epd.setFont(&FreeSansBold18pt7b);
epd.setCursor(4, 60);
epd.printf("%.1f", w.tempC);
epd.setFont(&FreeMonoBold9pt7b);
epd.print(" C");
epd.setCursor(4, 82);
epd.printf("Feels: %.1fC Hum: %d%%", w.feelsLike, w.humidity);
epd.setCursor(4, 98);
epd.printf("Wind: %.1f km/h", w.windKmh);
epd.setCursor(4, 114);
epd.print(w.description);
epd.setCursor(200, 122);
if (USE_BATTERY_SENSE) epd.printf("%.2fV", battMv / 1000.0f);
else epd.printf("#%lu", (unsigned long)bootCount);
} while (epd.nextPage());
}
void drawMessage(const char* line1, const char* line2) {
epd.setRotation(1);
epd.setFullWindow();
epd.firstPage();
do {
epd.fillScreen(GxEPD_WHITE);
epd.setTextColor(GxEPD_BLACK);
epd.setFont(&FreeMonoBold9pt7b);
epd.setCursor(4, 50);
epd.print(line1);
epd.setCursor(4, 80);
epd.print(line2);
} while (epd.nextPage());
}
void goToSleep(uint32_t minutes) {
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
esp_sleep_enable_timer_wakeup((uint64_t)minutes * 60ULL * 1000000ULL);
Serial.flush();
esp_deep_sleep_start(); // never returns; the chip restarts on wake
}
void setup() {
Serial.begin(115200);
bootCount++;
const int battMv = USE_BATTERY_SENSE ? readBatteryMv() : 4000;
if (USE_BATTERY_SENSE && battMv < BATTERY_LOW_MV) {
epd.init(0);
drawMessage("LOW BATTERY", "Recharge the cell");
epd.hibernate();
goToSleep(LOW_BATT_SLEEP_MIN);
}
bool ok = false;
if (connectWiFi()) {
WeatherData fresh;
memset(&fresh, 0, sizeof(fresh));
if (fetchWeather(fresh)) {
lastWeather = fresh;
ok = true;
}
}
if (ok) failCount = 0;
else if (failCount < 255) failCount++;
// Refresh the screen only when it tells the reader something new
const bool redraw = ok || failCount == 1 || !lastWeather.valid;
if (redraw) {
epd.init(0);
if (lastWeather.valid) drawWeather(lastWeather, !ok, battMv);
else drawMessage("No data yet", "Check Wi-Fi and key");
epd.hibernate(); // image stays, panel stops drawing power
}
goToSleep((ok || failCount > MAX_FAST_RETRIES) ? SLEEP_MIN : RETRY_MIN);
}
void loop() {}How the Firmware Behaves
Battery first
Before it does anything expensive, the sketch measures the cell. If the voltage is below 3.3 V, it shows a LOW BATTERY message, hibernates the display and sleeps for a day. Wi-Fi transmit peaks are the moment a weak cell sags and the regulator drops out, so skipping the radio protects both the cell and the display from a repeating brown-out loop. If you have not fitted the divider, set USE_BATTERY_SENSE to false.
Timeouts on everything
Every step that waits has a limit: 15 seconds for Wi-Fi and 8 seconds for the HTTP request. A device on a battery must never wait forever, because time awake is the most expensive thing it does. If the router is down, the device gives up, records the failure and goes back to sleep.
Failure handling that does not drain the battery
After a failure the device retries in 5 minutes. After more than five consecutive failures, it falls back to the normal 30-minute interval, so an outage at 3 a.m. does not wear the cell down by retrying all night. On the first failure only, it redraws the last good reading with a STALE marker, and then stays quiet instead of refreshing the screen every five minutes.
The HTTPS trade-off
The request goes over HTTPS so the API key is not sent in clear text. The call to client.setInsecure() skips certificate verification, which keeps the sketch small and avoids certificate expiry problems, but it means the device cannot detect a fake server. For a public weather query that is a reasonable hobby trade-off, but if you want verification, load the root certificate for the API host with client.setCACert() and plan to update it when it changes.
Redraw only when useful
The e-paper screen is refreshed only after a successful update, after the first failure, or when there is no data at all. Each refresh costs time, current and panel wear, and the content would be identical anyway.
Sleeping
goToSleep() turns Wi-Fi off, arms the timer and calls esp_deep_sleep_start(). The timer is in microseconds, so the minutes are multiplied by 60 and by 1,000,000, using 64-bit arithmetic to avoid overflow. The chip restarts from setup() when the timer fires.
First Boot and Testing
Steps
- 1Test the display alone with the GxEPD2 example that matches your panel, before adding Wi-Fi or sleep. Confirm the correct class and wiring first.
- 2Put your Wi-Fi name, password, API key and city ID into the sketch. Keep a local copy that you never publish.
- 3Upload over USB with the battery disconnected, and watch the Serial Monitor at 115200 baud for any HTTP error code.
- 4Check the screen shows the temperature, conditions and a battery voltage, and that the board then goes quiet.
- 5Disconnect the router for one cycle and confirm the screen shows STALE with the old reading, not a blank panel.
- 6Move to battery power, measure sleep current, and compare it with your budget. Repeat after each hardware change.
- 7Let it run for a few days and note the battery voltage trend before you trust a runtime estimate.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Screen blank or garbled | Wrong GxEPD2 class, or SPI wiring fault | Match the class to your panel and verify BUSY, RST, DC, CS, CLK and DIN against the module's pinout. |
| Display never finishes drawing | BUSY pin not connected, or wrong polarity for the panel | Check the BUSY wire and the panel's class. |
| HTTP 401 | Key not activated yet, or typed wrongly | Wait a while after creating the key, then check it for stray spaces. |
| HTTP 404 or empty data | Wrong city ID | Copy the ID from the city's page on openweathermap.org. |
| JSON parse fails | ArduinoJson version mismatch | Use ArduinoJson 7 for JsonDocument, or use StaticJsonDocument<2048> with version 6. |
| Resets while connecting to Wi-Fi | Regulator or battery cannot supply the peaks | Use a 500 mA or larger regulator, a bulk capacitor near the ESP32, and a healthy cell. |
| Battery drains in days | Dev board draws milliamps in sleep | Measure sleep current, then bypass the regulator path or move to a battery-oriented board. |
| Always shows LOW BATTERY | Divider wrong, or no divider fitted | Check the 1 MΩ pair and GPIO35, or set USE_BATTERY_SENSE to false. |
| Screen shows STALE for hours | Wi-Fi or API failing | Check signal strength, router reachability and the API status. |
| Cannot upload after sleep is enabled | Board asleep when you try to flash | Reset, or hold BOOT while connecting. |
Ideas for Improvement
- Wake on a button. Wire a button to an RTC-capable pin and use external wake-up, so a press forces an immediate refresh. Use an external pull-up and check the board's schematic, since not every pin is usable.
- Add a forecast. The same API family offers forecast data. Draw a small trend instead of one value.
- Add an indoor sensor. A BME280 on I2C can show indoor temperature and humidity beside the outdoor values, at the cost of a little more awake time.
- Use a solar panel. A small panel and a proper charge controller can keep the cell topped up, because the average current is so low.
- Show the update time. Add NTP time during the awake period, so the screen can display when it was last refreshed.
- Over-the-air updates. OTA needs the device awake. Add a deliberate "update window" mode, for example after a button press.
Frequently Asked Questions
Can I use a standard ESP32 dev board? Yes, and it is the right way to start. Expect weeks, not months, until you address the power path.
Why not use a boost converter to 5 V? The dev board then drops the voltage back to 3.3 V, so you pay the conversion losses twice and keep extra parts powered.
Does e-paper really use no power when idle? The panel holds its image without power. The driver electronics and the module's circuitry may still draw a little, which is why the sketch hibernates the panel.
Why does the sketch restart from the beginning after sleep? Deep sleep powers down the CPU and RAM. Only RTC memory and the timer survive, so the program starts again.
Is the API key safe in the sketch? It is only as safe as your copy of the code. Do not publish it, and rotate the key if you ever do.
Summary
You built a weather display that sleeps between updates, and you learned that battery life depends on the whole board, not just the chip. The firmware checks the cell first, uses timeouts everywhere, keeps the last good data in RTC memory, marks stale readings and redraws only when it has something new to show. With a measured sleep current and the budget formula in hand, you can predict, and improve, how long your own build will run.


