MicroPython uasyncio: A Practical Async Programming Guide
Microcontrollers rarely do one thing at a time: a board may blink status LEDs, poll a sensor, keep a network connection alive, and react to button presses all at once. Writing that as one long polling loop gets messy fast, and spinning up threads on a few hundred kilobytes of RAM is not much better. That is exactly the problem MicroPython uasyncio solves — it brings cooperative, async/await-style concurrency to bare-metal targets with a tiny memory footprint and fast task switching. This guide explains how the library works, what its current API looks like, and how to use it well in real firmware, including the parts many tutorials skip: cancellation semantics, interrupt-safe signaling, TCP streams, and concurrency limits without a built-in semaphore.
Table of Contents#
- What Is MicroPython uasyncio?
- The Event Loop, Coroutines, and Tasks
- MicroPython uasyncio vs. CPython asyncio
- Core API Tour
- Synchronizing Tasks: Event, ThreadSafeFlag, and Lock
- Async TCP with Streams
- Real-World Firmware Patterns
- Timing Discipline: ticks_ms and Wraparound
- Best Practices and Common Pitfalls
- When to Choose Something Else
- Conclusion
- References
What Is MicroPython uasyncio?#
uasyncio is MicroPython's asynchronous I/O scheduler: a compact reimplementation of a subset of CPython's asyncio, tuned for microcontrollers. It lets many coroutines share a single thread cooperatively — each task runs until it hits an await, then yields so other tasks can make progress while it waits on a timer, a socket, or a hardware response.
A few facts worth knowing up front:
- The module is now called
asyncio. The nameuasynciodates from the era when MicroPython prefixed modules withu(for "micro"). Modern firmware documents and exports the module asasyncio;uasynciosurvives only as a thin backwards-compatibility shim that forwards attribute lookups toasyncio, so oldimport uasynciocode keeps working. New code shouldimport asyncio. - It ships with the firmware. The library lives in MicroPython's
extmod/asynciopackage and is frozen into standard firmware builds, soimport asyncioworks on a freshly flashed board with no package install step. - It is version 3.x of the library. The in-tree library reports version
(3, 0, 0), and the API described here matches current stable MicroPython (v1.29.0, released August 2026). - It is a subset of CPython asyncio, not a clone. Anything you already know about
async/await, coroutines, and tasks transfers directly; anything that depends on large parts of the CPython standard library may not.
Why bother on a microcontroller? Concurrency here is not about parallel CPU work — a Cortex-M has one core and little RAM. It is about keeping the system responsive while operations wait. A cooperative scheduler avoids the RAM cost of per-thread stacks, avoids locking hazards of preemptive multitasking, and still lets a sensor poll, an LED animation, and a socket handler run "at the same time."
The Event Loop, Coroutines, and Tasks#
Three concepts make up the whole model.
Coroutines are functions declared with async def. Calling one does not run it — it returns a coroutine object that the scheduler drives. Inside a coroutine, await marks a suspension point: the coroutine pauses there, and the event loop is free to run other tasks until the awaited operation finishes.
The event loop is the scheduler. It keeps queues of ready and sleeping tasks, polls sockets when I/O is involved, wakes tasks whose timers expired, and runs each task until its next await. MicroPython has exactly one loop per interpreter; asyncio.new_event_loop() does not create a second one, it only resets the existing loop's state.
Tasks wrap a coroutine so the loop can schedule it. asyncio.create_task(coro) registers a task and starts it on the next scheduling pass; asyncio.run(coro) is the usual entry point that creates a task from your main() coroutine and runs the loop until it completes.
A minimal complete program — two independent heartbeats plus a stop condition:
import asyncio
async def heartbeat(name, interval_ms):
while True:
print(name, "beat")
await asyncio.sleep_ms(interval_ms)
async def main():
asyncio.create_task(heartbeat("A", 250))
asyncio.create_task(heartbeat("B", 400))
await asyncio.sleep_ms(2000)
print("done")
asyncio.run(main())Both heartbeats run concurrently even though there is one thread: while task A waits for its next 250 ms tick, task B gets scheduled. Note that asyncio.sleep_ms() is a MicroPython extension that avoids float arithmetic and heap allocation; asyncio.sleep(seconds) exists too and accepts a float.
Because scheduling is cooperative, a task runs uninterrupted until it awaits. That is the single most important property of the whole system, and most bugs come from forgetting it.
MicroPython uasyncio vs. CPython asyncio#
If you are coming from desktop Python, expect a familiar surface with deliberate omissions and a few MicroPython-specific extras.
| Area | CPython asyncio | MicroPython uasyncio/asyncio |
|---|---|---|
| Import name | asyncio | asyncio (uasyncio works as a legacy alias) |
| Scope | Full framework: threads, subprocesses, TLS helpers, task groups | Compact subset for a single-threaded interpreter |
| Event loops | Multiple loops, per-thread policies | One global loop; new_event_loop() merely resets it |
| Millisecond helpers | — | sleep_ms(), wait_for_ms() extensions |
| Timeout exception | asyncio.TimeoutError (aliased to the builtin TimeoutError on 3.11+) | A distinct asyncio.TimeoutError class defined by the library |
| Cancellation exception | asyncio.CancelledError (a BaseException) | asyncio.CancelledError (also a BaseException) |
| Sync primitives | Event, Lock, Semaphore, Queue, Condition, … | Event, Lock, ThreadSafeFlag only |
| Networking | Transports/protocols, streams, executors | TCP streams only (open_connection, start_server) |
| IRQ / thread bridging | Threads and call_soon_threadsafe | ThreadSafeFlag |
Two consequences matter in practice:
- There is no
asyncio.Semaphoreorasyncio.Queuein stock MicroPython. If you port desktop code that uses them, you must supply your own (see Real-World Firmware Patterns) or install an optional community library. - Timeouts use the library's own exception type, so always catch
asyncio.TimeoutError(orException) rather than assuming the builtinTimeoutErrorwill match.
Core API Tour#
Starting and scheduling work#
asyncio.run(main()) # create a task from main() and run to completion
task = asyncio.create_task(coro) # schedule coro, return a Task
me = asyncio.current_task() # the Task executing right nowcreate_task() expects a coroutine object (anything with a send method); passing a plain function raises TypeError: coroutine expected. A Task can be awaited (await task yields the coroutine's return value) or cancelled (task.cancel() injects asyncio.CancelledError into it). The task may trap that exception or ignore it; try/finally is the reliable way to release pins, close sockets, or turn outputs off during cancellation.
Delays#
await asyncio.sleep(t)— pausetseconds (float allowed).await asyncio.sleep_ms(t)— pausetmilliseconds (MicroPython extension, integer-friendly).
Both re-suspend the task and let the loop run everything else. Never use time.sleep() inside a coroutine; it freezes every task.
Running several tasks together: gather#
asyncio.gather(*awaitables, return_exceptions=False) runs awaitables concurrently and returns their results as a list:
async def read_sensor():
await asyncio.sleep_ms(30) # simulate acquisition time
return 21.5
async def read_battery():
await asyncio.sleep_ms(50)
return 3.87
async def main():
temps = await asyncio.gather(read_sensor(), read_battery())
print(temps) # [21.5, 3.87]Behavior details worth remembering:
- Non-task awaitables are promoted to tasks automatically.
- With
return_exceptions=False(the default), the first sub-task exception is re-raised in the caller andgatherstops waiting; the other sub-tasks are not cancelled and keep running. - With
return_exceptions=True, exceptions come back inside the result list instead of being raised. - If the
gatheritself is cancelled, all its sub-tasks are cancelled too. - Gathering a task that some other code is already waiting on raises
RuntimeError("can't gather")— give each awaiter its own task.
Timeouts and cancellation#
async def poll_wifi():
await asyncio.sleep_ms(1500) # slow operation
return "connected"
async def main():
try:
status = await asyncio.wait_for_ms(poll_wifi(), 500)
print("wifi:", status)
except asyncio.TimeoutError:
print("wifi poll timed out")wait_for(awaitable, timeout) measures timeout in seconds and wait_for_ms(awaitable, timeout) in milliseconds. When the deadline passes, the awaited task is cancelled and asyncio.TimeoutError is raised in the caller. The doomed task itself sees asyncio.CancelledError, so its finally blocks still run — that is where cleanup belongs:
async def transfer(sock):
try:
await asyncio.sleep_ms(2000)
finally:
sock.close() # runs on timeout and on normal exitNote that wait_for cancels the task on timeout; it does not merely stop waiting for it.
The event loop object#
asyncio.get_event_loop() returns the loop used for scheduling. Its most useful knobs:
def report(loop, context):
print("unhandled task error:", context["exception"])
asyncio.get_event_loop().set_exception_handler(report)Any task that raises an uncaught exception and is never awaited ends up in this handler (context keys: message, exception, future). The default handler prints Task exception wasn't retrieved and the traceback to stderr — fine at the REPL, too silent in deployed firmware, so set your own handler that logs or blinks an error LED. Loop.run_forever(), Loop.run_until_complete(), and Loop.stop() are available if you need to drive the loop manually instead of using asyncio.run().
Synchronizing Tasks: Event, ThreadSafeFlag, and Lock#
Event#
asyncio.Event is a one-shot flag for task-to-task signaling. await ev.wait() suspends until ev.set(); ev.clear() resets it. One hard rule from the docs: set() must be called from inside a task — it is not safe from an IRQ, a scheduler callback, or another thread.
import asyncio
event = asyncio.Event()
async def producer():
await asyncio.sleep_ms(500)
event.set() # unblock the consumer
async def consumer():
print("waiting for data")
await event.wait()
print("data arrived")
async def main():
await asyncio.gather(producer(), consumer())
asyncio.run(main())ThreadSafeFlag#
For anything outside the loop — hardware interrupts, _thread threads, micropython.schedule callbacks — use asyncio.ThreadSafeFlag. Setting it is safe from an IRQ handler, wait() auto-resets the flag on return, and only one task may wait on a given flag at a time.
from machine import Pin
import asyncio
flag = asyncio.ThreadSafeFlag()
pressed = 0
def on_press(pin):
global pressed
pressed += 1
flag.set() # IRQ-safe
async def button_task():
button = Pin(0, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
while True:
await flag.wait()
print("button pressed", pressed, "times")
asyncio.run(button_task())This is the idiomatic bridge between interrupt-driven hardware and asyncio tasks, and it is one of the most valuable MicroPython-specific features of the library.
Lock#
asyncio.Lock gives mutual exclusion around shared resources (an I2C bus, a display, a flash file). It supports async with:
async def write_display(lock, text):
async with lock:
print("draw", text) # exclusive access to the display
await asyncio.sleep_ms(10) # placeholder for real I/OAsync TCP with Streams#
Networking is built on two coroutines and one stream class:
await asyncio.open_connection(host, port, ssl=None)returns a reader/writer pair; passssl=Truefor a default TLS context or anssl.SSLContextfor custom settings. DNS resolution goes throughsocket.getaddrinfo, which is still a blocking call — prefer literal IPs in latency-critical code, or resolve once at startup.await asyncio.start_server(callback, host, port, backlog=5, ssl=None)accepts connections and invokescallback(reader, writer)per client. The returnedServerobject can be used withasync with, which closes it on exit.StreamReader/StreamWriterare aliases of a singleStreamclass. Reads:read(n),readexactly(n),readline(),readinto(buf). Writes:write(buf)only buffers, andawait writer.drain()actually flushes — calldrain()right after everywrite().
A complete echo server:
import asyncio
async def handle_client(reader, writer):
peer = writer.get_extra_info("peername")
print("connection from", peer)
try:
while True:
data = await reader.read(64)
if not data: # EOF
break
writer.write(data)
await writer.drain()
finally:
writer.close()
await writer.wait_closed()
print("closed", peer)
async def main():
async with await asyncio.start_server(handle_client, "0.0.0.0", 8080):
print("echo server on :8080")
await asyncio.Event().wait() # park forever
asyncio.run(main())Each accepted connection is handled by its own task state machine; idle clients stay cheap because only ready tasks are scheduled.
Real-World Firmware Patterns#
Hardware tasks that never block each other#
Combine the pieces into a typical application skeleton — a status LED, a periodic sensor read, and a network keep-alive — each in its own coroutine:
from machine import Pin
import asyncio
led = Pin(2, Pin.OUT) # or your board's LED pin
async def blink():
while True:
led.toggle()
await asyncio.sleep_ms(400)
async def sample():
while True:
value = 21.5 # replace with a real sensor read
print("temp", value)
await asyncio.sleep_ms(1000)
async def main():
asyncio.create_task(blink())
asyncio.create_task(sample())
await asyncio.Event().wait()
asyncio.run(main())Keep each coroutine small and single-purpose: one waits on hardware, one on time, one on the network. Compose them with gather, events, and timeouts rather than nesting everything in one giant loop.
Bounded concurrency without Semaphore#
Stock MicroPython has no asyncio.Semaphore, so unbounded create_task fan-out (for example, resolving many sockets at once) can exhaust RAM. Two portable fixes.
A fixed worker pool — spawn exactly N workers that pull jobs from a shared list:
import asyncio
async def do_job(n):
await asyncio.sleep_ms(50) # replace with real work
return n * n
async def worker(jobs, results):
while jobs:
job = jobs.pop(0)
results.append(await do_job(job))
async def main():
jobs = list(range(10))
results = []
await asyncio.gather(
*[worker(jobs, results) for _ in range(3)] # at most 3 in flight
)
print(sorted(results))
asyncio.run(main())Or a small custom semaphore built from Event, if you prefer the async with style:
class Semaphore:
def __init__(self, limit):
self._limit = limit
self._active = 0
self._free = asyncio.Event()
self._free.set()
async def acquire(self):
while self._active >= self._limit:
self._free.clear()
await self._free.wait()
self._active += 1
def release(self):
self._active -= 1
self._free.set()
async def __aenter__(self):
await self.acquire()
async def __aexit__(self, *exc):
self.release()The re-check loop in acquire() matters: after the shared flag wakes the waiters, another task may already have taken the free slot, so each waiter must re-test the count rather than assume a slot is its own. A single shared event (rather than one event per waiter) also keeps the class robust when waiting tasks are cancelled.
Error handling that survives deployment#
Wrap fallible awaits in try/except inside the coroutine where recovery is possible, and use the loop's exception handler as a backstop for everything else:
async def safe_upload():
try:
await asyncio.wait_for_ms(upload(), 2000)
except asyncio.TimeoutError:
print("upload timed out, will retry")
except OSError as e:
print("network error:", e)Remember the cancellation contract: asyncio.CancelledError is a BaseException, so except Exception will not swallow it — which is exactly what you want.
Timing Discipline: ticks_ms and Wraparound#
MicroPython timers use time.ticks_ms(), a small integer that wraps around periodically (the wrap point is a power of two that varies by port). Direct arithmetic and comparison on these values is invalid across a wrap:
import time
start = time.ticks_ms()
# ... later ...
elapsed = time.ticks_diff(time.ticks_ms(), start) # wrap-safe difference
deadline = time.ticks_add(start, 5000) # wrap-safe deadline
if time.ticks_diff(time.ticks_ms(), deadline) > 0:
print("overdue")asyncio.sleep_ms() already accounts for wraparound internally, so scheduling sleeps is safe. Hand-rolled deadline loops (state machines, debounce timers, protocol timeouts) must use ticks_diff/ticks_add instead of now - start > limit. Devices that run for weeks will hit the wrap; devices tested for ten minutes often will not.
Best Practices and Common Pitfalls#
- Never block the loop. Any call that does not
awaitfreezes every task:time.sleep(), synchronous socket I/O, longwhileloops, slow flashes of a display. If a driver is blocking, wrap it in its own task with generousawait asyncio.sleep_ms(0)yields, or run it on a second thread and bridge withThreadSafeFlag. awaitevery async operation you care about. Forgettingawait writer.drain()afterwriter.write()silently defers transmission; forgettingawaiton a coroutine schedules nothing at all.- Put cleanup in
finally. Timeouts andtask.cancel()deliverasyncio.CancelledErrorat the currentawaitpoint;try/finallyis the only reliable place to de-energize outputs and close files. - Handle task exceptions deliberately. An unawaited task that dies does not crash the program — it reports through the loop's exception handler. Set a handler that logs, and prefer awaiting tasks you spawn when you need their result or their error.
- Cap concurrency. Every task costs RAM (its coroutine frame and any buffers). Use worker pools, semaphores, or batching instead of spawning one task per item on large lists.
- Reuse
sleep_ms/wait_for_msfor integer timing. They are cheaper than the float-based second variants and express intent better for hardware timing. - Keep coroutines small. One responsibility per coroutine (read one sensor, serve one connection, drive one LED) keeps
awaitpoints obvious and makes tasks easy to start, stop, and test. - Mind the REPL state. Because MicroPython has a single loop, state can persist between runs in the same session;
asyncio.new_event_loop()resets the loop's state when you want a clean slate without rebooting the board. - Watch memory pressure.
print()debugging allocates; prefersys.print_exceptionfor errors and remove logging from hot loops once code is stable.
When to Choose Something Else#
uasyncio is not a universal answer:
- Hard real-time work (bit-banging protocols, sub-millisecond timing) belongs in interrupts, PIO state machines, or dedicated peripherals, with
ThreadSafeFlagused only to hand results back to the async world. - CPU-bound computation gains nothing from
awaits; a second core or a C module is a better tool. - Truly blocking libraries (some sensor drivers that spin on I/O) will stall the loop no matter how they are scheduled — isolate them in
_threadand signal across withThreadSafeFlag. - Missing primitives. If you want
Queue,Semaphore,Barrier,Message, or ready-made async drivers for common sensors, the communitymicropython-asyncproject packages them as optional, installable primitives; the stock module deliberately stays minimal.
Conclusion#
MicroPython uasyncio gives microcontroller firmware the same async/await ergonomics as desktop Python, in a library small enough for bare metal. The essentials are few: coroutines that suspend at await, one event loop that schedules them, and tasks you create, join, gather, or cancel. Beyond that, the MicroPython-specific pieces — sleep_ms, wait_for_ms, ThreadSafeFlag for interrupts, wraparound-safe ticks_* arithmetic, and TCP streams — are what make it practical on real hardware. Remember that concurrency is cooperative (one blocking call ruins it), that stock asyncio ships without semaphores and queues, and that cancellation plus finally is your cleanup story. Get those right and a $5 board can juggle sensors, LEDs, buttons, and sockets as cleanly as any server framework.
References#
- MicroPython
asyncio— asynchronous I/O scheduler (module documentation): https://docs.micropython.org/en/latest/library/asyncio.html - MicroPython
timemodule —ticks_ms,ticks_add,ticks_diff(wraparound rules): https://docs.micropython.org/en/latest/library/time.html - MicroPython source,
extmod/asynciopackage (library implementation anduasynciocompatibility module): https://github.com/micropython/micropython/tree/master/extmod/asyncio - MicroPython v1.29.0 release notes (current stable release, August 2026): https://github.com/micropython/micropython/releases/tag/v1.29.0
- CPython
asynciodocumentation (reference model for the MicroPython subset): https://docs.python.org/3/library/asyncio.html micropython-asyncproject (optional Semaphore, Queue, and device-driver primitives): https://github.com/peterhinch/micropython-async