Quick answer: in MicroPython, machine.deepsleep(60000) puts the ESP32 into deep sleep for 60 seconds. When it wakes, the board restarts from scratch: boot.py and main.py run again, and all variables are lost. Check machine.reset_cause() == machine.DEEPSLEEP_RESET to know you woke from sleep, keep small data in machine.RTC().memory(), and choose a wake source: a timer (the argument to deepsleep), a button or sensor pin with esp32.wake_on_ext0() / wake_on_ext1() on RTC GPIOs (0, 2, 4, 12–15, 25–27, 32–39), or a touch pad with esp32.wake_on_touch(True). The ESP32 chip itself draws around 10 µA asleep, but most DevKit boards draw milliamps because of their USB chip and regulator, so measure your board.
| Wake source | MicroPython | Pins | Typical use |
|---|---|---|---|
| Timer | machine.deepsleep(ms) | — | Sensor reading every few minutes |
| One pin (ext0) | esp32.wake_on_ext0(pin, esp32.WAKEUP_ALL_LOW) | One RTC GPIO | Button, PIR, door contact |
| Several pins (ext1) | esp32.wake_on_ext1((p1, p2), esp32.WAKEUP_ANY_HIGH) | RTC GPIOs | Several sensors |
| Touch | TouchPad(Pin(14)).config(400) + esp32.wake_on_touch(True) | Touch GPIOs | Touch button |
| ULP co-processor | esp32.wake_on_ulp(True) | — | Advanced: monitor a sensor while asleep |
What happens in deep sleep
| Active (Wi-Fi on) | Light sleep | Deep sleep | |
|---|---|---|---|
| CPU | Running | Paused | Off |
| RAM contents | Kept | Kept | Lost (except RTC memory) |
| Wi-Fi / Bluetooth | On | Off (reconnect after) | Off |
| On wake-up | — | Continues after lightsleep() | Full restart (boot.py → main.py) |
| ESP32 chip current | ~80–260 mA | ~0.8 mA | ~10 µA |
Those are chip figures from Espressif's datasheet. A whole development board adds its regulator, power LED and USB-serial chip, often several milliamps even when the ESP32 sleeps. For battery projects use a board designed for low power, or remove the power LED and use an efficient regulator (ESP32 deep sleep and battery life).
1. Timer wake-up: a sensor that reports every 5 minutes
Save as main.py. It reads a DHT22, prints (or sends) the value, then sleeps:
import machine, time, dht
from machine import Pin
sensor = dht.DHT22(Pin(4))
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print("Woke from deep sleep")
else:
print("Power-on or reset: waiting 5 s so you can stop the script")
time.sleep(5)
# escape hatch for re-flashing (see below)
try:
sensor.measure()
print("T={:.1f} C H={:.1f} %".format(sensor.temperature(), sensor.humidity()))
# ... connect Wi-Fi and publish here (MQTT example linked below) ...
except OSError as e:
print("Sensor error:", e)
machine.deepsleep(5 * 60 * 1000)
# 5 minutes; code after this never runsThe 5-second delay matters. Once a board loops "wake → work → sleep", the USB serial connection is only alive for a moment, and Thonny can't interrupt it. The delay on a normal power-up gives you time to press Stop (Ctrl+C) and edit the files. If you ever get locked out, hold BOOT while plugging in and re-flash MicroPython.
2. Find out why the board woke
import machine
names = {}
for n in ("EXT0_WAKE", "EXT1_WAKE", "TIMER_WAKE", "TOUCHPAD_WAKE", "ULP_WAKE"):
if hasattr(machine, n):
names[getattr(machine, n)] = n
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print("Wake reason:", names.get(machine.wake_reason(), machine.wake_reason()))
else:
print("Normal boot")Use the reason to branch: a timer wake means "take a routine reading", a button wake means "the user wants something now".
3. Keep data across sleeps (RTC memory)
Normal variables vanish on every wake. The RTC slow memory survives deep sleep (not power loss) and holds about 2 KB of bytes:
import machine, json
rtc = machine.RTC()
def load_state():
raw = rtc.memory()
try:
return json.loads(raw) if raw else {"boots": 0, "last_t": None}
except ValueError:
return {"boots": 0, "last_t": None}
state = load_state()
state["boots"] += 1
print("Wake number", state["boots"])
rtc.memory(json.dumps(state)) # save before sleeping
machine.deepsleep(60000)Typical uses: a wake counter, the last reading (to send only when it changes), or a "readings since last upload" buffer so Wi-Fi only switches on every tenth wake. That last trick saves more battery than anything else, because Wi-Fi is by far the biggest energy cost.
4. Wake on a button or sensor (ext0 / ext1)
Wire a push button from GPIO33 to GND. GPIO33 is an RTC pin, so it can wake the chip:
import machine, esp32
from machine import Pin
button = Pin(33, Pin.IN, Pin.PULL_UP) # RTC pin; pull-up stays active in sleep
esp32.wake_on_ext0(pin=button, level=esp32.WAKEUP_ALL_LOW) # wake when pressed (LOW)
print("Sleeping until the button is pressed (or 1 hour)")
machine.deepsleep(60 * 60 * 1000) # timer and button both active- ext0 watches one pin for a chosen level.
- ext1 watches several pins:
esp32.wake_on_ext1(pins=(Pin(32), Pin(33)), level=esp32.WAKEUP_ANY_HIGH)wakes when any goes high (e.g. two PIR sensors). - A PIR sensor's output idles LOW and goes HIGH on motion, so use
WAKEUP_ANY_HIGH(with ext0 or ext1). - Calling
deepsleep()with no argument sleeps until a pin or touch wakes it.
Only RTC GPIOs can wake the chip: 0, 2, 4, 12–15, 25–27 and 32–39. GPIO34–39 have no internal pull-ups, so add an external 10 kΩ resistor if you use them.
5. Wake on touch
import machine, esp32
from machine import Pin, TouchPad
pad = TouchPad(Pin(14))
print("Untouched reading:", pad.read())
pad.config(300) # threshold: below this counts as touched on the classic ESP32
esp32.wake_on_touch(True)
machine.deepsleep() # sleep until touchedPick the threshold by printing pad.read() untouched and touched (a wire or foil pad on the pin works), then choose a value between them. On the classic ESP32 a touch makes the reading smaller; on the ESP32-S2/S3 it makes it larger. Touch pins on the classic ESP32: 0, 2, 4, 12, 13, 14, 15, 27, 32, 33.
6. Keep an output on (or off) while asleep
Pins normally float during deep sleep, which can switch a relay or MOSFET unexpectedly. Hold the level:
from machine import Pin
import esp32, machine
relay = Pin(26, Pin.OUT, value=0, hold=True) # held LOW through deep sleep
esp32.gpio_deep_sleep_hold(True) # also hold non-RTC pins
machine.deepsleep(60000)After waking, re-create the pin with hold=False (or relay.init(hold=False)) before changing it.
7. Estimate battery life
Average current = (awake current × awake time + sleep current × sleep time) ÷ cycle time. Example: wake every 5 minutes, 4 s awake with Wi-Fi at ~120 mA, board sleep current 0.15 mA:
| Board sleep current | Average current | 2,000 mAh battery lasts |
|---|---|---|
| 0.15 mA (low-power board) | ≈ 1.7 mA | ≈ 7 weeks |
| 5 mA (typical DevKit) | ≈ 6.6 mA | ≈ 13 days |
| 0.15 mA, Wi-Fi only every 10th wake (other wakes ~1 s at ~40 mA) | ≈ 0.4 mA | ≈ 6–7 months |
The table shows where the energy goes: the DevKit's own sleep current, and Wi-Fi time. Batch readings in RTC memory, keep Wi-Fi sessions short (static IP, no DNS lookups), and measure the real current with a multimeter or a USB power meter.
8. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Can't stop the script or upload new files | Board sleeps almost immediately after every boot | Keep the startup delay; or hold BOOT while connecting and re-flash |
| Never wakes from a button | Pin isn't an RTC GPIO, or wrong level | Use 0, 2, 4, 12–15, 25–27, 32–39; match WAKEUP_ALL_LOW/ANY_HIGH to the wiring |
| Wakes immediately, over and over | Wake pin already at the wake level, or floating | Add a pull-up/pull-down; check the button wiring |
| Variables reset after waking | Normal: deep sleep restarts the program | Store data in RTC().memory() |
| Battery dies in days | Board-level current (USB chip, LED, regulator) | Measure; use a low-power board or remove the LED |
| Relay clicks during sleep | Output floating | hold=True and esp32.gpio_deep_sleep_hold(True) |
AttributeError: wake_on_ext0 | Chip variant without ext0 (e.g. some RISC-V ESP32s) | Use the wake options your chip supports (check the port docs) |
| Touch wake triggers by itself | Threshold too close to the untouched value | Measure both states; widen the margin |
Validate a deep-sleep design before deploying it
A deep-sleep sketch can appear correct on USB power and still fail as a battery device. Test the wake path and the power budget separately before leaving it unattended.
A repeatable bench test
- Start with a timer-only sketch and a short interval such as 15 seconds. Print the reset cause and a counter at every boot.
- Confirm that the counter increases only when you deliberately save it in RTC memory. A normal Python global should return to its initial value after each deep-sleep reset.
- Add the external wake source only after the timer test works. Check the pin number against the RTC-capable pins for your exact ESP32 variant; do not assume every ESP32-family chip exposes identical wake functions.
- Test both the idle and active electrical levels. A button wired to ground with a pull-up should be inactive HIGH and active LOW. If the pin is already at the configured wake level when sleep begins, the chip may wake immediately.
- Repeat the test at least ten times and watch for a wake loop, missed presses or a sensor that remains asserted.
Measure the whole board, not just the chip
Disconnect USB and measure current in series with the battery supply using a meter with a suitable low-current range, or use a USB power meter for a first comparison. Record three readings: active current, current during Wi-Fi transmission, and steady sleep current after the board has settled. A multimeter inserted incorrectly across a supply can create a short; use its current jack and series connection, and begin on a protected range.
The battery estimate is only as good as the current assumptions. If a board draws 4 mA asleep rather than the 0.15 mA used in an example calculation, that difference dominates a long sleep interval. Also allow for regulator quiescent current, power LEDs, sensor standby current, battery self-discharge and cold-temperature capacity loss. Recalculate with measured values and keep a reserve rather than designing around the theoretical maximum.
Firmware and deployment safeguards
Keep a reliable recovery route while developing: a short first-boot delay, a known BOOT-button procedure for entering the ROM downloader, and a saved copy of the working script. Before deployment, confirm that outputs such as relay controls have a safe hardware default during reset and sleep. Software pin hold is not a substitute for a pull resistor or a driver circuit that guarantees a safe state while the ESP32 is unpowered.
Finally, verify the exact MicroPython firmware build and chip variant. Wake APIs, touch support and RTC pin availability differ across classic ESP32, S2, S3, C-series and board designs. If an API is missing, check the port's quick reference rather than copying a classic-ESP32 example unchanged.
FAQ
Does main.py run again after deep sleep? Yes, from the top. Deep sleep ends with a reset.
What's the difference between lightsleep and deepsleep? Light sleep pauses and resumes your program (RAM kept, about 1 mA); deep sleep powers almost everything off and restarts (~10 µA chip current).
Can Wi-Fi stay connected during deep sleep? No. The board reconnects on every wake, typically in 1–3 seconds.
How long can the ESP32 deep sleep? Many hours or days on the timer; with only a pin or touch wake source, indefinitely.
Next steps
- MicroPython DHT22 on ESP32 and MicroPython MQTT: the reading and sending parts of a sleeping sensor node.
- ESP32 deep sleep and battery life (Arduino).
- MicroPython boot.py and main.py explained.
- ESP32 pinout guide: RTC and touch pins.
Official references: MicroPython ESP32 quick reference and esp32 module.




