Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Microcontrollers and Boards

MicroPython and Low-Power Design

Program microcontrollers in MicroPython, then design for battery life: sleep modes, duty cycling, wake sources and energy budgets, with simulations.

C++ is the traditional language of microcontrollers, but MicroPython brings a lean version of Python 3 to chips such as the ESP32, RP2040 and STM32. You type code into a live prompt (the REPL), change it and run it again without compiling. This lesson introduces MicroPython and then moves to the most important skill in battery-powered IoT: low-power design.

MicroPython in five minutes

You flash the MicroPython firmware once, then talk to the board over USB with a tool such as Thonny, mpremote or rshell. Files on the board's file system run at boot: boot.py first, then main.py.

Python
# main.py on an ESP32 or Pico W (read-only listing)
from machine import Pin, ADC, PWM
import time

led = Pin(2, Pin.OUT)
button = Pin(0, Pin.IN, Pin.PULL_UP)
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)          # ESP32: measure up to about 3.3 V

while True:
    if button.value() == 0:
        led.value(1)
    else:
        led.value(0)
    raw = adc.read()              # 0..4095 on ESP32
    print("raw:", raw)
    time.sleep_ms(500)

Useful modules: machine (Pin, ADC, PWM, I2C, SPI, UART, Timer, RTC, deep sleep), network (Wi-Fi), time, json, urequests/requests, umqtt and neopixel. A quick Wi-Fi connection:

Python
import network, time

sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("my-network", "my-password")
for _ in range(20):
    if sta.isconnected():
        break
    time.sleep(0.5)
print(sta.ifconfig())

MicroPython versus C++

MicroPython Arduino C++
Speed 10 to 100 times slower Fast, near the hardware
RAM use Higher (interpreter, garbage collector) Minimal
Development Interactive REPL, no compile Compile and upload cycle
Learning curve Gentle Steeper
Best for Prototypes, glue code, education Timing-critical, tiny, mass-produced devices

Many products use C/C++ in production but prototype in MicroPython. CircuitPython (Adafruit's fork) is similar with extra friendliness.

Trying MicroPython-style code in the browser

A browser cannot run a board, but we can imitate machine.Pin with a small Python stand-in and run MicroPython-looking logic on it. This is a stand-in, not the real firmware.

Python A stand-in for machine.Pin and a sensor loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why low power matters

A battery-powered device is only as good as its battery life. The golden rules:

  1. Sleep as much as possible. Sleep currents are thousands of times lower than active currents.
  2. Keep the radio off except when sending. Radio transmission is the largest drain.
  3. Do work fast and go back to sleep ("race to sleep").
  4. Transmit less: batch data, send only changes, compress.
  5. Use efficient components: low quiescent regulators, sensors with their own sleep modes.

Power states of a microcontroller

State CPU RAM Radio Typical ESP32 current Wakes from
Active with Wi-Fi TX On On On 160 to 260 mA peak n/a
Active, radio off On On Off 20 to 60 mA n/a
Light sleep Paused Kept Off about 0.8 mA Timer, GPIO, UART
Deep sleep Off Lost (RTC memory kept) Off 10 to 150 microamps Timer, GPIO, touch
Hibernation Off Lost Off a few microamps Limited sources

In deep sleep, program memory restarts from the beginning on wake-up, so you keep important values in RTC memory or flash. MicroPython uses machine.deepsleep(ms) and Arduino uses esp_deep_sleep_start():

Python
import machine, time

# read, send, then sleep for 10 minutes
def main():
    value = read_sensor()
    send(value)
    machine.deepsleep(10 * 60 * 1000)   # board restarts main.py after wake-up

main()

Energy budgets

To design for a lifetime, convert each phase into charge (milliamp-hours or microamp-hours): charge = current * time. Sum the phases for one cycle, divide by the cycle time to get average current, and divide the battery capacity by that. Also derate the battery: temperature, self-discharge and ageing reduce usable capacity by 20% or more.

Python Energy budget of one wake-up cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The surprise in most budgets is that Wi-Fi connect dominates. Remedies: store the access point's channel and BSSID in RTC memory for fast reconnects, use a static IP instead of DHCP, or choose a lower-power protocol such as BLE or LoRa. Compare with connectivity choices.

Python What one saving is worth: faster Wi-Fi reconnect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical low-power techniques

  • Use light sleep when you must keep RAM and wake quickly; use deep sleep for long gaps.
  • Disable unused peripherals and power sensors through a GPIO (or MOSFET) only when measuring.
  • Lower the CPU clock if you can, and avoid busy-waiting loops.
  • Remove always-on LEDs and USB-serial chips on the board for final products; development boards waste 1 mA or more in idle chips.
  • Wake on events (a button or a motion interrupt) instead of polling on a timer, when events are rare.
  • Measure real current with a power profiler or a shunt resistor and oscilloscope. Estimates are rarely right the first time.

A multimeter averages and misses short spikes. A Nordic PPK2, Joulescope or a small shunt measured with a scope shows the true profile of each wake-up.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the REPL in MicroPython?

    The Read-Eval-Print Loop lets you type commands and see results immediately.
  2. 2. What happens to program state in deep sleep on an ESP32?

    Deep sleep powers down most of the chip; only RTC memory and special peripherals remain.
  3. 3. Which phase usually dominates energy use in a Wi-Fi sensor cycle?

    Radio phases draw hundreds of times more current than sleeping or measuring.
  4. 4. How do you compute battery life from phases?

    Sum current times duration for each phase, divide by the period, then capacity divided by that average.

Summary

  • MicroPython runs Python on microcontrollers with a REPL; it trades speed and RAM for convenience.
  • Battery life depends on sleeping most of the time, short active bursts and fewer transmissions.
  • Deep sleep restarts the program on wake, so store state in RTC memory or flash.
  • Build an energy budget per phase, find the dominant cost (often Wi-Fi connect) and measure the real current.

Next: Serial Buses: UART, I2C and SPI