0% found this document useful (0 votes)
88 views608 pages

Micropython Docs

The MicroPython Documentation for release v1.22.0 provides comprehensive information on MicroPython libraries, including standard and MicroPython-specific libraries, as well as port-specific libraries. It also covers the MicroPython language and implementation details, including the interactive interpreter mode (REPL) and various features. The document is authored by Damien P. George, Paul Sokolovsky, and contributors, and was released on December 27, 2023.

Uploaded by

samuelcarre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views608 pages

Micropython Docs

The MicroPython Documentation for release v1.22.0 provides comprehensive information on MicroPython libraries, including standard and MicroPython-specific libraries, as well as port-specific libraries. It also covers the MicroPython language and implementation details, including the interactive interpreter mode (REPL) and various features. The document is authored by Damien P. George, Paul Sokolovsky, and contributors, and was released on December 27, 2023.

Uploaded by

samuelcarre
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 608

MicroPython Documentation

Release v1.22.0

Damien P. George, Paul Sokolovsky, and contributors

Dec 27, 2023


CONTENTS

1 MicroPython libraries 1
1.1 Python standard libraries and micro-libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.1 array – arrays of numeric data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.2 asyncio — asynchronous I/O scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.3 binascii – binary/ASCII conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.1.4 builtins – builtin functions and exceptions . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.1.5 cmath – mathematical functions for complex numbers . . . . . . . . . . . . . . . . . . . . 12
1.1.6 collections – collection and container types . . . . . . . . . . . . . . . . . . . . . . . . 13
1.1.7 errno – system error codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.1.8 gc – control the garbage collector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.1.9 gzip – gzip compression & decompression . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.1.10 hashlib – hashing algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.1.11 heapq – heap queue algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.1.12 io – input/output streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.1.13 json – JSON encoding and decoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.1.14 math – mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.1.15 os – basic “operating system” services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.1.16 platform – access to underlying platform’s identifying data . . . . . . . . . . . . . . . . . 27
1.1.17 random – generate random numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.1.18 re – simple regular expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.1.19 select – wait for events on a set of streams . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.1.20 socket – socket module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.1.21 ssl – SSL/TLS module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.1.22 struct – pack and unpack primitive data types . . . . . . . . . . . . . . . . . . . . . . . . 41
1.1.23 sys – system specific functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.1.24 time – time related functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.1.25 zlib – zlib compression & decompression . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
1.1.26 _thread – multithreading support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.2 MicroPython-specific libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.2.1 bluetooth — low-level Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
1.2.2 btree – simple BTree database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
1.2.3 cryptolib – cryptographic ciphers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
1.2.4 deflate – deflate compression & decompression . . . . . . . . . . . . . . . . . . . . . . . 64
1.2.5 framebuf — frame buffer manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
1.2.6 machine — functions related to the hardware . . . . . . . . . . . . . . . . . . . . . . . . . 69
1.2.7 micropython – access and control MicroPython internals . . . . . . . . . . . . . . . . . . 100
1.2.8 neopixel — control of WS2812 / NeoPixel LEDs . . . . . . . . . . . . . . . . . . . . . . 102
1.2.9 network — network configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
1.2.10 uctypes – access binary data in a structured way . . . . . . . . . . . . . . . . . . . . . . . 115
1.2.11 WM8960 – Driver for the WM8960 codec . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

i
1.3 Port-specific libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
1.3.1 Libraries specific to the pyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
1.3.2 Libraries specific to the WiPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
1.3.3 Libraries specific to the ESP8266 and ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . 181
1.3.4 Libraries specific to the RP2040 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
1.3.5 Libraries specific to Zephyr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
1.4 Extending built-in libraries from Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

2 MicroPython language and implementation 215


2.1 Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
2.2 The MicroPython Interactive Interpreter Mode (aka REPL) . . . . . . . . . . . . . . . . . . . . . . . 218
2.2.1 Auto-indent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
2.2.2 Auto-completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
2.2.3 Interrupting a running program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
2.2.4 Paste mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
2.2.5 Soft reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
2.2.6 The special variable _ (underscore) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
2.2.7 Raw mode and raw-paste mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
2.3 MicroPython remote control: mpremote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
2.3.1 Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
2.3.2 Auto connection and soft-reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
2.3.3 Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
2.3.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
2.4 MicroPython .mpy files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
2.4.1 Versioning and compatibility of .mpy files . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
2.4.2 Binary encoding of .mpy files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
2.5 Writing interrupt handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
2.5.1 Tips and recommended practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
2.5.2 MicroPython issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
2.5.3 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
2.5.4 Interfacing to asyncio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
2.5.5 General issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
2.6 Maximising MicroPython speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
2.6.1 Designing for speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
2.6.2 Identifying the slowest section of code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
2.6.3 MicroPython code improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
2.6.4 The Native code emitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
2.6.5 The Viper code emitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
2.6.6 Accessing hardware directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
2.7 MicroPython on microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
2.7.1 Flash memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
2.7.2 RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
2.7.3 The heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
2.7.4 String operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
2.7.5 Postscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
2.8 MicroPython manifest files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
2.8.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
2.8.2 Writing manifest files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
2.8.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
2.9 Package management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
2.9.1 Installing packages with mip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
2.9.2 Installing packages with mpremote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
2.9.3 Installing packages manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
2.9.4 Writing & publishing packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258

ii
2.9.5 Freezing packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
2.10 Inline assembler for Thumb2 architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
2.10.1 Document conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
2.10.2 Instruction categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
2.10.3 Usage examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
2.10.4 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
2.11 Working with filesystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
2.11.1 VFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
2.11.2 Block devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
2.11.3 Filesystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
2.12 The pyboard.py tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
2.12.1 Running a command on the device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
2.12.2 Running a script on the device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
2.12.3 Filesystem access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
2.12.4 Using the pyboard library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
2.13 MicroPython 2.0 Migration Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
2.13.1 Hardware and peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
2.13.2 OS & filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
2.13.3 CPython compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

3 MicroPython differences from CPython 283


3.1 Python 3.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
3.2 Python 3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
3.3 Python 3.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
3.4 Python 3.8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
3.5 Python 3.9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
3.6 Python 3.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
3.7 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
3.7.1 Argument unpacking does not work if the argument being unpacked is the nth or greater argu-
ment where n is the number of bits in an MP_SMALL_INT. . . . . . . . . . . . . . . . . . . 296
3.7.2 MicroPython allows using := to assign to the variable of a comprehension, CPython raises a
SyntaxError. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
3.7.3 uPy requires spaces between literal numbers and keywords, CPy doesn’t . . . . . . . . . . . . 297
3.7.4 Unicode name escapes are not implemented . . . . . . . . . . . . . . . . . . . . . . . . . . 298
3.8 Core language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
3.8.1 f-strings don’t support concatenation with adjacent literals if the adjacent literals contain braces
or are f-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
3.8.2 f-strings cannot support expressions that require parsing to resolve unbalanced nested braces
and brackets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
3.8.3 Raw f-strings are not supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
3.8.4 f-strings don’t support !a conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
3.8.5 Special method __del__ not implemented for user-defined classes . . . . . . . . . . . . . . . 300
3.8.6 Method Resolution Order (MRO) is not compliant with CPython . . . . . . . . . . . . . . . 300
3.8.7 When inheriting from multiple classes super() only calls one class . . . . . . . . . . . . . . . 301
3.8.8 Calling super() getter property in subclass will return a property object, not the value . . . . . 301
3.8.9 Error messages for methods may display unexpected argument counts . . . . . . . . . . . . . 302
3.8.10 Function objects do not have the __module__ attribute . . . . . . . . . . . . . . . . . . . 302
3.8.11 User-defined attributes for functions are not supported . . . . . . . . . . . . . . . . . . . . . 303
3.8.12 Context manager __exit__() not called in a generator which does not run to completion . . . . 303
3.8.13 Local variables aren’t included in locals() result . . . . . . . . . . . . . . . . . . . . . . . . . 304
3.8.14 Code running in eval() function doesn’t have access to local variables . . . . . . . . . . . . . 304
3.8.15 __all__ is unsupported in __init__.py in MicroPython. . . . . . . . . . . . . . . . . . . . . . 305
3.8.16 __path__ attribute of a package has a different type (single string instead of list of strings) in
MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

iii
3.8.17 MicroPython doesn’t support namespace packages split across filesystem. . . . . . . . . . . . 306
3.9 Builtin types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
3.9.1 Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
3.9.2 bytearray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
3.9.3 bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
3.9.4 dict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
3.9.5 float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
3.9.6 int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
3.9.7 list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
3.9.8 str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
3.9.9 tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
3.10 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
3.10.1 array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
3.10.2 builtins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
3.10.3 deque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
3.10.4 json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
3.10.5 os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
3.10.6 random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
3.10.7 struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
3.10.8 sys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

4 MicroPython Internals 325


4.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
4.1.1 Source control with git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
4.1.2 Get the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
4.1.3 Compile and build the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
4.1.4 Building the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
4.1.5 Running the tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
4.1.6 Folder structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
4.2 Writing tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
4.3 The Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
4.3.1 Adding a grammar rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
4.3.2 Adding a lexical token . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
4.3.3 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
4.3.4 Compiler passes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
4.3.5 Emitting bytecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
4.3.6 Emitting native code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
4.4 Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
4.4.1 The object model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
4.4.2 Allocation of objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
4.5 Implementing a Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
4.5.1 Implementing a core module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
4.6 Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
4.6.1 Frozen bytecode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
4.6.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
4.6.3 Allocation of memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
4.7 MicroPython string interning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
4.7.1 Compile-time QSTR generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
4.7.2 Run-time QSTR generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
4.8 Maps and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
4.8.1 Open addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
4.8.2 Linear probing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
4.9 The public C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
4.10 Extending MicroPython in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

iv
4.10.1 MicroPython external C modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
4.10.2 Native machine code in .mpy files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
4.11 Porting MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
4.11.1 Minimal MicroPython firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
4.11.2 MicroPython Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
4.11.3 Support for standard input/output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
4.11.4 Building and running . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
4.11.5 Adding a module to the port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356

5 MicroPython license information 359

6 Quick reference for the pyboard 361


6.1 General information about the pyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
6.1.1 Local filesystem and SD card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
6.1.2 Boot modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
6.1.3 Errors: flashing LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
6.1.4 Guide for using the pyboard with Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
6.1.5 The pyboard hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
6.1.6 Datasheets for the components on the pyboard . . . . . . . . . . . . . . . . . . . . . . . . . 363
6.1.7 Datasheets for other components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
6.2 MicroPython tutorial for the pyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
6.2.1 Introduction to the pyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
6.2.2 Running your first script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
6.2.3 Getting a MicroPython REPL prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
6.2.4 Turning on LEDs and basic Python concepts . . . . . . . . . . . . . . . . . . . . . . . . . . 370
6.2.5 Switches, callbacks and interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
6.2.6 The accelerometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
6.2.7 Safe mode and factory reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
6.2.8 Making the pyboard act as a USB mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
6.2.9 The Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
6.2.10 Inline assembler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
6.2.11 Power control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
6.2.12 Tutorials requiring extra components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
6.2.13 Tips, tricks and useful things to know . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
6.3 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
6.4 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
6.5 Internal LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
6.6 Internal switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
6.7 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
6.8 Servo control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
6.9 External interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
6.10 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
6.11 RTC (real time clock) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
6.12 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
6.13 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
6.14 DAC (digital to analog conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
6.15 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
6.16 SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
6.17 I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
6.18 I2S bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
6.19 CAN bus (controller area network) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
6.20 Internal accelerometer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400

7 Quick reference for the ESP8266 401

v
7.1 General information about the ESP8266 port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
7.1.1 Multitude of boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
7.1.2 Technical specifications and SoC datasheets . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
7.1.3 Scarcity of runtime resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
7.1.4 Boot process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
7.1.5 Known Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
7.2 MicroPython tutorial for ESP8266 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
7.2.1 Getting started with MicroPython on the ESP8266 . . . . . . . . . . . . . . . . . . . . . . . 405
7.2.2 Getting a MicroPython REPL prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
7.2.3 The internal filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
7.2.4 Network basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
7.2.5 Network - TCP sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
7.2.6 GPIO Pins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
7.2.7 Pulse Width Modulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
7.2.8 Analog to Digital Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
7.2.9 Power control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
7.2.10 Controlling 1-wire devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
7.2.11 Controlling NeoPixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
7.2.12 Controlling APA102 LEDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
7.2.13 Temperature and Humidity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
7.2.14 Using a SSD1306 OLED display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
7.2.15 Next steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
7.3 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
7.4 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
7.5 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
7.6 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
7.7 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
7.8 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
7.9 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
7.10 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
7.11 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
7.12 Software SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
7.13 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
7.14 I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
7.15 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
7.16 WDT (Watchdog timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
7.17 Deep-sleep mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
7.18 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
7.19 NeoPixel driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
7.20 APA102 driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
7.21 DHT driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
7.22 SSD1306 driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
7.23 WebREPL (web browser interactive prompt) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434

8 Quick reference for the ESP32 435


8.1 General information about the ESP32 port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
8.1.1 Multitude of boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
8.1.2 Technical specifications and SoC datasheets . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
8.2 MicroPython tutorial for ESP32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
8.2.1 Getting started with MicroPython on the ESP32 . . . . . . . . . . . . . . . . . . . . . . . . 437
8.2.2 Pulse Width Modulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
8.2.3 Accessing peripherals directly via registers . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
8.3 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
8.4 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444

vi
8.5 Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
8.5.1 WLAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
8.5.2 LAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
8.6 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
8.7 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
8.8 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
8.9 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
8.10 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
8.11 DAC (digital to analog conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
8.12 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
8.13 Software SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
8.14 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
8.15 Software I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
8.16 Hardware I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
8.17 I2S bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
8.18 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
8.19 WDT (Watchdog timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
8.20 Deep-sleep mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
8.21 SD card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
8.22 RMT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
8.23 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
8.24 NeoPixel and APA106 driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
8.25 Capacitive touch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
8.26 DHT driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
8.27 WebREPL (web browser interactive prompt) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457

9 Quick reference for the RP2 459


9.1 General information about the RP2xxx port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
9.1.1 Technical specifications and SoC datasheets . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
9.2 Getting started with MicroPython on the RP2xxx . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
9.2.1 Programmable IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
9.3 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
9.4 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
9.5 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
9.6 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
9.7 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
9.8 Programmable IO (PIO) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
9.9 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
9.10 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
9.11 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
9.12 Software SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
9.13 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
9.14 Software I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
9.15 Hardware I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
9.16 I2S bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
9.17 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
9.18 WDT (Watchdog timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
9.19 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
9.20 NeoPixel and APA106 driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468

10 Quick reference for the i.MXRT family 471


10.1 General information about the MIMXRT port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.1.1 Multitude of boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
10.1.2 Supported MCUs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472

vii
10.1.3 Technical specifications and SoC datasheets . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
10.2 Getting started with MicroPython on the i.MXRT . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
10.2.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
10.2.2 Powering the board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
10.2.3 Getting the firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
10.2.4 Deploying the firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
10.2.5 Serial prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
10.2.6 Troubleshooting installation problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
10.3 Pinout for the i.MXRT machine modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
10.3.1 UART pin assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
10.3.2 PWM pin assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
10.3.3 Hardware SPI pin assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
10.3.4 Hardware I2C pin assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
10.3.5 Hardware I2S pin assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
10.4 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
10.5 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
10.6 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.7 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.8 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
10.9 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
10.10 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
10.10.1 PWM Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
10.10.2 PWM Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
10.10.3 PWM Pin Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
10.11 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
10.12 Software SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
10.13 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
10.14 Software I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
10.15 Hardware I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
10.16 I2S bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
10.17 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
10.18 SD card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
10.19 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
10.20 DHT driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
10.21 Ethernet driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
10.22 Transferring files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495

11 Quick reference for the WiPy 497


11.1 General information about the WiPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
11.1.1 No floating point support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
11.1.2 Before applying power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
11.1.3 WLAN default behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
11.1.4 Telnet REPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
11.1.5 Local file system and FTP access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
11.1.6 FileZilla settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
11.1.7 Upgrading the firmware Over The Air . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
11.1.8 Boot modes and safe boot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
11.1.9 The heartbeat LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
11.1.10 Details on sleep modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
11.1.11 Additional details for machine.Pin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
11.1.12 Additional details for machine.I2C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
11.1.13 Known issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
11.2 WiPy tutorials and examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
11.2.1 Introduction to the WiPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504

viii
11.2.2 Getting a MicroPython REPL prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
11.2.3 Getting started with Blynk and the WiPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
11.2.4 WLAN step by step . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
11.2.5 Hardware timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
11.2.6 Reset and boot modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
11.3 General board control (including sleep modes) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
11.4 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
11.5 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
11.6 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
11.7 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
11.8 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
11.9 SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
11.10 I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
11.11 Watchdog timer (WDT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
11.12 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
11.13 SD card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
11.14 WLAN (WiFi) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
11.15 Telnet and FTP server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
11.16 Heart beat LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

12 Quick reference for the UNIX and Windows ports 517


12.1 Command line options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
12.2 Environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518

13 Quick reference for the Zephyr port 519


13.1 General information about the Zephyr port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
13.1.1 Multitude of boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
13.2 MicroPython tutorial for the Zephyr port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
13.2.1 Getting started with MicroPython on the Zephyr port . . . . . . . . . . . . . . . . . . . . . . 519
13.2.2 Getting a MicroPython REPL prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
13.2.3 Filesystems and Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
13.2.4 GPIO Pins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
13.3 Running MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
13.4 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
13.5 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
13.6 Hardware I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
13.7 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
13.8 Disk Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
13.9 Flash Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
13.10 Sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526

14 Quick reference for the Renesas RA 527


14.1 General information about Renesas RA port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
14.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
14.2 MicroPython tutorial for Renesas RA port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
14.2.1 Getting started with MicroPython on the Renesas RA . . . . . . . . . . . . . . . . . . . . . 528
14.2.2 Using peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
14.2.3 Write a program in internal file system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
14.2.4 Reset and boot mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
14.2.5 Trouble Shooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
14.3 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
14.4 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
14.5 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
14.6 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534

ix
14.7 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
14.8 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
14.9 Real time clock (RTC) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
14.10 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
14.11 SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
14.12 I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
14.13 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
14.14 WDT (Watchdog timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
14.15 SDCard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
14.16 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
14.17 NeoPixel and APA106 driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540

15 Quick reference for the SAMD21/SAMD51 family 541


15.1 General information about the SAMD port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
15.1.1 Multitude of boards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
15.1.2 Technical specifications and SoC data sheets . . . . . . . . . . . . . . . . . . . . . . . . . . 542
15.2 Getting started with MicroPython on the SAMD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
15.2.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
15.2.2 Powering the board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
15.2.3 Getting the firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
15.2.4 Deploying the firmware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
15.2.5 Serial prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
15.2.6 Troubleshooting installation problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
15.3 Pinout for the SAMD machine modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
15.3.1 Adafruit ItsyBitsy M0 Express pin assignment table . . . . . . . . . . . . . . . . . . . . . . . 545
15.3.2 Adafruit ItsyBitsy M4 Express pin assignment table . . . . . . . . . . . . . . . . . . . . . . . 549
15.3.3 Adafruit Feather M4 Express pin assignment table . . . . . . . . . . . . . . . . . . . . . . . 553
15.3.4 Adafruit Metro M4 Airlift pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . 556
15.3.5 SEEED XIAO pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
15.3.6 Adafruit Feather M0 Express pin assignment table . . . . . . . . . . . . . . . . . . . . . . . 562
15.3.7 Adafruit Trinket M0 pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
15.3.8 SAMD21 Xplained PRO pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . 567
15.3.9 Minisam M4 pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
15.3.10 Seeed WIO Terminal pin assignment table . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
15.3.11 Sparkfun SAMD51 Thing Plus pin assignment table . . . . . . . . . . . . . . . . . . . . . . 579
15.3.12 Scripts for creating the pin assignment tables . . . . . . . . . . . . . . . . . . . . . . . . . . 582
15.4 Installing MicroPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
15.5 General board control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
15.6 Delay and timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
15.7 Clock and time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
15.8 Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
15.9 Pins and GPIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
15.10 UART (serial bus) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
15.11 PWM (pulse width modulation) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
15.11.1 PWM Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
15.11.2 PWM Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
15.11.3 PWM Pin Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
15.12 ADC (analog to digital conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
15.12.1 ADC Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
15.12.2 ADC Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
15.13 DAC (digital to analog conversion) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
15.13.1 DAC Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
15.13.2 DAC Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
15.14 Software SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589

x
15.15 Hardware SPI bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
15.16 Software I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
15.17 Hardware I2C bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
15.18 OneWire driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
15.19 DHT driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
15.20 Driving an APA102 LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
15.21 Driving a Neopixel LED . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
15.22 Transferring files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592

Python Module Index 593

xi
xii
CHAPTER

ONE

MICROPYTHON LIBRARIES

Warning: Important summary of this section


• MicroPython provides built-in modules that mirror the functionality of the Python standard library (e.g. os,
time), as well as MicroPython-specific modules (e.g. bluetooth, machine).
• Most Python standard library modules implement a subset of the functionality of the equivalent Python module,
and in a few cases provide some MicroPython-specific extensions (e.g. array, os)
• Due to resource constraints or other limitations, some ports or firmware versions may not include all the func-
tionality documented here.
• To allow for extensibility, some built-in modules can be extended from Python code loaded onto the device
filesystem.

This chapter describes modules (function and class libraries) which are built into MicroPython. This documentation in
general aspires to describe all modules and functions/classes which are implemented in the MicroPython project. However,
MicroPython is highly configurable, and each port to a particular board/embedded system may include only a subset of
the available MicroPython libraries.
With that in mind, please be warned that some functions/classes in a module (or even the entire module) described in this
documentation may be unavailable in a particular build of MicroPython on a particular system. The best place to find
general information of the availability/non-availability of a particular feature is the “General Information” section which
contains information pertaining to a specific MicroPython port.
On some ports you are able to discover the available, built-in libraries that can be imported by entering the following at
the REPL:

help('modules')

Beyond the built-in libraries described in this documentation, many more modules from the Python standard library, as
well as further MicroPython extensions to it, can be found in micropython-lib.

1
MicroPython Documentation, Release v1.22.0

1.1 Python standard libraries and micro-libraries

The following standard Python libraries have been “micro-ified” to fit in with the philosophy of MicroPython. They
provide the core functionality of that module and are intended to be a drop-in replacement for the standard Python
library.

1.1.1 array – arrays of numeric data

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: array.
Supported format codes: b, B, h, H, i, I, l, L, q, Q, f, d (the latter 2 depending on the floating-point support).

Classes

class array.array(typecode[, iterable ])


Create array with elements of given type. Initial contents of the array are given by iterable. If it is not provided, an
empty array is created.
append(val)
Append new element val to the end of array, growing it.
extend(iterable)
Append new elements as contained in iterable to the end of array, growing it.
__getitem__(index)
Indexed read of the array, called as a[index] (where a is an array). Returns a value if index is an int
and an array if index is a slice. Negative indices count from the end and IndexError is thrown if the
index is out of range.
Note: __getitem__ cannot be called directly (a.__getitem__(index) fails) and is not present in
__dict__, however a[index] does work.
__setitem__(index, value)
Indexed write into the array, called as a[index] = value (where a is an array). value is a single value
if index is an int and an array if index is a slice. Negative indices count from the end and IndexError
is thrown if the index is out of range.
Note: __setitem__ cannot be called directly (a.__setitem__(index, value) fails) and is not
present in __dict__, however a[index] = value does work.
__len__()
Returns the number of items in the array, called as len(a) (where a is an array).
Note: __len__ cannot be called directly (a.__len__() fails) and the method is not present in
__dict__, however len(a) does work.
__add__(other)
Return a new array that is the concatenation of the array with other, called as a + other (where a and
other are both arrays).
Note: __add__ cannot be called directly (a.__add__(other) fails) and is not present in __dict__,
however a + other does work.

2 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

__iadd__(other)
Concatenates the array with other in-place, called as a += other (where a and other are both arrays).
Equivalent to extend(other).
Note: __iadd__ cannot be called directly (a.__iadd__(other) fails) and is not present in
__dict__, however a += other does work.
__repr__()
Returns the string representation of the array, called as str(a) or repr(a)` (where a is an array).
Returns the string "array(<type>, [<elements>])", where <type> is the type code letter for
the array and <elements> is a comma separated list of the elements of the array.
Note: __repr__ cannot be called directly (a.__repr__() fails) and is not present in __dict__,
however str(a) and repr(a) both work.

1.1.2 asyncio — asynchronous I/O scheduler

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: asyncio
Example:

import asyncio

async def blink(led, period_ms):


while True:
led.on()
await asyncio.sleep_ms(5)
led.off()
await asyncio.sleep_ms(period_ms)

async def main(led1, led2):


asyncio.create_task(blink(led1, 700))
asyncio.create_task(blink(led2, 400))
await asyncio.sleep_ms(10_000)

# Running on a pyboard
from pyb import LED
asyncio.run(main(LED(1), LED(2)))

# Running on a generic board


from machine import Pin
asyncio.run(main(Pin(1), Pin(2)))

Core functions

asyncio.create_task(coro)
Create a new task from the given coroutine and schedule it to run.
Returns the corresponding Task object.
asyncio.current_task()
Return the Task object associated with the currently running task.

1.1. Python standard libraries and micro-libraries 3


MicroPython Documentation, Release v1.22.0

asyncio.run(coro)
Create a new task from the given coroutine and run it until it completes.
Returns the value returned by coro.
asyncio.sleep(t)
Sleep for t seconds (can be a float).
This is a coroutine.
asyncio.sleep_ms(t)
Sleep for t milliseconds.
This is a coroutine, and a MicroPython extension.

Additional functions

asyncio.wait_for(awaitable, timeout)
Wait for the awaitable to complete, but cancel it if it takes longer than timeout seconds. If awaitable is not a task
then a task will be created from it.
If a timeout occurs, it cancels the task and raises asyncio.TimeoutError: this should be trapped by the caller.
The task receives asyncio.CancelledError which may be ignored or trapped using try...except or
try...finally to run cleanup code.
Returns the return value of awaitable.
This is a coroutine.
asyncio.wait_for_ms(awaitable, timeout)
Similar to wait_for but timeout is an integer in milliseconds.
This is a coroutine, and a MicroPython extension.
asyncio.gather(*awaitables, return_exceptions=False)
Run all awaitables concurrently. Any awaitables that are not tasks are promoted to tasks.
Returns a list of return values of all awaitables.
This is a coroutine.

class Task

class asyncio.Task
This object wraps a coroutine into a running task. Tasks can be waited on using await task, which will wait
for the task to complete and return the return value of the task.
Tasks should not be created directly, rather use create_task to create them.
Task.cancel()
Cancel the task by injecting asyncio.CancelledError into it. The task may ignore this exception. Cleanup
code may be run by trapping it, or via try ... finally.

4 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class Event

class asyncio.Event
Create a new event which can be used to synchronise tasks. Events start in the cleared state.
Event.is_set()
Returns True if the event is set, False otherwise.
Event.set()
Set the event. Any tasks waiting on the event will be scheduled to run.
Note: This must be called from within a task. It is not safe to call this from an IRQ, scheduler callback, or other
thread. See ThreadSafeFlag.
Event.clear()
Clear the event.
Event.wait()
Wait for the event to be set. If the event is already set then it returns immediately.
This is a coroutine.

class ThreadSafeFlag

class asyncio.ThreadSafeFlag
Create a new flag which can be used to synchronise a task with code running outside the asyncio loop, such as other
threads, IRQs, or scheduler callbacks. Flags start in the cleared state. The class does not currently work under the
Unix build of MicroPython.
ThreadSafeFlag.set()
Set the flag. If there is a task waiting on the flag, it will be scheduled to run.
ThreadSafeFlag.clear()
Clear the flag. This may be used to ensure that a possibly previously-set flag is clear before waiting for it.
ThreadSafeFlag.wait()
Wait for the flag to be set. If the flag is already set then it returns immediately. The flag is automatically reset upon
return from wait.
A flag may only be waited on by a single task at a time.
This is a coroutine.

class Lock

class asyncio.Lock
Create a new lock which can be used to coordinate tasks. Locks start in the unlocked state.
In addition to the methods below, locks can be used in an async with statement.
Lock.locked()
Returns True if the lock is locked, otherwise False.

1.1. Python standard libraries and micro-libraries 5


MicroPython Documentation, Release v1.22.0

Lock.acquire()
Wait for the lock to be in the unlocked state and then lock it in an atomic way. Only one task can acquire the lock
at any one time.
This is a coroutine.
Lock.release()
Release the lock. If any tasks are waiting on the lock then the next one in the queue is scheduled to run and the
lock remains locked. Otherwise, no tasks are waiting an the lock becomes unlocked.

TCP stream connections

asyncio.open_connection(host, port, ssl=None)


Open a TCP connection to the given host and port. The host address will be resolved using socket.
getaddrinfo, which is currently a blocking call. If ssl is a ssl.SSLContext object, this context is used to
create the transport; if ssl is True, a default context is used.
Returns a pair of streams: a reader and a writer stream. Will raise a socket-specific OSError if the host could
not be resolved or if the connection could not be made.
This is a coroutine.
asyncio.start_server(callback, host, port, backlog=5, ssl=None)
Start a TCP server on the given host and port. The callback will be called with incoming, accepted connections,
and be passed 2 arguments: reader and writer streams for the connection.
If ssl is a ssl.SSLContext object, this context is used to create the transport.
Returns a Server object.
This is a coroutine.
class asyncio.Stream
This represents a TCP stream connection. To minimise code this class implements both a reader and a writer, and
both StreamReader and StreamWriter alias to this class.
Stream.get_extra_info(v)
Get extra information about the stream, given by v. The valid values for v are: peername.
Stream.close()
Close the stream.
Stream.wait_closed()
Wait for the stream to close.
This is a coroutine.
Stream.read(n=-1)
Read up to n bytes and return them. If n is not provided or -1 then read all bytes until EOF. The returned value
will be an empty bytes object if EOF is encountered before any bytes are read.
This is a coroutine.
Stream.readinto(buf)
Read up to n bytes into buf with n being equal to the length of buf.
Return the number of bytes read into buf.
This is a coroutine, and a MicroPython extension.

6 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Stream.readexactly(n)
Read exactly n bytes and return them as a bytes object.
Raises an EOFError exception if the stream ends before reading n bytes.
This is a coroutine.
Stream.readline()
Read a line and return it.
This is a coroutine.
Stream.write(buf)
Accumulated buf to the output buffer. The data is only flushed when Stream.drain is called. It is recommended
to call Stream.drain immediately after calling this function.
Stream.drain()
Drain (write) all buffered output data out to the stream.
This is a coroutine.
class asyncio.Server
This represents the server class returned from start_server. It can be used in an async with statement to
close the server upon exit.
Server.close()
Close the server.
Server.wait_closed()
Wait for the server to close.
This is a coroutine.

Event Loop

asyncio.get_event_loop()
Return the event loop used to schedule and run tasks. See Loop.
asyncio.new_event_loop()
Reset the event loop and return it.
Note: since MicroPython only has a single event loop this function just resets the loop’s state, it does not create a
new one.
class asyncio.Loop
This represents the object which schedules and runs tasks. It cannot be created, use get_event_loop instead.
Loop.create_task(coro)
Create a task from the given coro and return the new Task object.
Loop.run_forever()
Run the event loop until stop() is called.
Loop.run_until_complete(awaitable)
Run the given awaitable until it completes. If awaitable is not a task then it will be promoted to one.
Loop.stop()
Stop the event loop.

1.1. Python standard libraries and micro-libraries 7


MicroPython Documentation, Release v1.22.0

Loop.close()
Close the event loop.
Loop.set_exception_handler(handler)
Set the exception handler to call when a Task raises an exception that is not caught. The handler should accept two
arguments: (loop, context).
Loop.get_exception_handler()
Get the current exception handler. Returns the handler, or None if no custom handler is set.
Loop.default_exception_handler(context)
The default exception handler that is called.
Loop.call_exception_handler(context)
Call the current exception handler. The argument context is passed through and is a dictionary containing keys:
'message', 'exception', 'future'.

1.1.3 binascii – binary/ASCII conversions

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: binascii.
This module implements conversions between binary data and various encodings of it in ASCII form (in both directions).

Functions

binascii.hexlify(data[, sep ])
Convert the bytes in the data object to a hexadecimal representation. Returns a bytes object.
If the additional argument sep is supplied it is used as a separator between hexadecimal values.
binascii.unhexlify(data)
Convert hexadecimal data to binary representation. Returns bytes string. (i.e. inverse of hexlify)
binascii.a2b_base64(data)
Decode base64-encoded data, ignoring invalid characters in the input. Conforms to RFC 2045 s.6.8. Returns a
bytes object.
binascii.b2a_base64(data, *, newline=True)
Encode binary data in base64 format, as in RFC 3548. Returns the encoded data followed by a newline character
if newline is true, as a bytes object.

1.1.4 builtins – builtin functions and exceptions

All builtin functions and exceptions are described here. They are also available via builtins module.

8 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Functions and types

abs()

all()

any()

bin()

class bool

class bytearray

class bytes
See CPython documentation: bytes.
callable()

chr()

classmethod()

compile()

class complex

delattr(obj, name)
The argument name should be a string, and this function deletes the named attribute from the object given by obj.
class dict

dir()

divmod()

enumerate()

eval()

exec()

filter()

class float

class frozenset

getattr()

globals()

hasattr()

hash()

hex()

id()

1.1. Python standard libraries and micro-libraries 9


MicroPython Documentation, Release v1.22.0

input()

class int

classmethod from_bytes(bytes, byteorder)


In MicroPython, byteorder parameter must be positional (this is compatible with CPython).
to_bytes(size, byteorder)
In MicroPython, byteorder parameter must be positional (this is compatible with CPython).
isinstance()

issubclass()

iter()

len()

class list

locals()

map()

max()

class memoryview

min()

next()

class object

oct()

open()

ord()

pow()

print()

property()

range()

repr()

reversed()

round()

class set

setattr()

class slice
The slice builtin is the type that slice objects have.

10 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

sorted()

staticmethod()

class str

sum()

super()

class tuple

type()

zip()

Exceptions

exception AssertionError

exception AttributeError

exception Exception

exception ImportError

exception IndexError

exception KeyboardInterrupt

exception KeyError

exception MemoryError

exception NameError

exception NotImplementedError

exception OSError

exception RuntimeError

exception StopIteration

exception SyntaxError

exception SystemExit
See CPython documentation: SystemExit.
exception TypeError
See CPython documentation: TypeError.
exception ValueError

exception ZeroDivisionError

1.1. Python standard libraries and micro-libraries 11


MicroPython Documentation, Release v1.22.0

1.1.5 cmath – mathematical functions for complex numbers

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: cmath.
The cmath module provides some basic mathematical functions for working with complex numbers.
Availability: not available on WiPy and ESP8266. Floating point support required for this module.

Functions

cmath.cos(z)
Return the cosine of z.
cmath.exp(z)
Return the exponential of z.
cmath.log(z)
Return the natural logarithm of z. The branch cut is along the negative real axis.
cmath.log10(z)
Return the base-10 logarithm of z. The branch cut is along the negative real axis.
cmath.phase(z)
Returns the phase of the number z, in the range (-pi, +pi].
cmath.polar(z)
Returns, as a tuple, the polar form of z.
cmath.rect(r, phi)
Returns the complex number with modulus r and phase phi.
cmath.sin(z)
Return the sine of z.
cmath.sqrt(z)
Return the square-root of z.

Constants

cmath.e
base of the natural logarithm
cmath.pi
the ratio of a circle’s circumference to its diameter

12 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

1.1.6 collections – collection and container types

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: collections.
This module implements advanced collection and container types to hold/accumulate various objects.

Classes

class collections.deque(iterable, maxlen[, flags ])


Deques (double-ended queues) are a list-like container that support O(1) appends and pops from either side of the
deque. New deques are created using the following arguments:
• iterable must be the empty tuple, and the new deque is created empty.
• maxlen must be specified and the deque will be bounded to this maximum length. Once the deque is full, any
new items added will discard items from the opposite end.
• The optional flags can be 1 to check for overflow when adding items.
As well as supporting bool and len, deque objects have the following methods:
append(x)
Add x to the right side of the deque. Raises IndexError if overflow checking is enabled and there is no more
room left.
popleft()
Remove and return an item from the left side of the deque. Raises IndexError if no items are present.
collections.namedtuple(name, fields)
This is factory function to create a new namedtuple type with a specific name and set of fields. A namedtuple is a
subclass of tuple which allows to access its fields not just by numeric index, but also with an attribute access syntax
using symbolic field names. Fields is a sequence of strings specifying field names. For compatibility with CPython
it can also be a a string with space-separated field named (but this is less efficient). Example of use:

from collections import namedtuple

MyTuple = namedtuple("MyTuple", ("id", "name"))


t1 = MyTuple(1, "foo")
t2 = MyTuple(2, "bar")
print(t1.name)
assert t2.name == t2[1]

class collections.OrderedDict(...)
dict type subclass which remembers and preserves the order of keys added. When ordered dict is iterated over,
keys/items are returned in the order they were added:

from collections import OrderedDict

# To make benefit of ordered keys, OrderedDict should be initialized


# from sequence of (key, value) pairs.
d = OrderedDict([("z", 1), ("a", 2)])
# More items can be added as usual
d["w"] = 5
d["b"] = 3
for k, v in d.items():
print(k, v)

1.1. Python standard libraries and micro-libraries 13


MicroPython Documentation, Release v1.22.0

Output:

z 1
a 2
w 5
b 3

1.1.7 errno – system error codes

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: errno.
This module provides access to symbolic error codes for OSError exception. A particular inventory of codes depends
on MicroPython port.

Constants

EEXIST, EAGAIN, etc.


Error codes, based on ANSI C/POSIX standard. All error codes start with “E”. As mentioned above, inventory of
the codes depends on MicroPython port. Errors are usually accessible as exc.errno where exc is an instance
of OSError. Usage example:

try:
os.mkdir("my_dir")
except OSError as exc:
if exc.errno == errno.EEXIST:
print("Directory already exists")

errno.errorcode
Dictionary mapping numeric error codes to strings with symbolic error code (see above):

>>> print(errno.errorcode[errno.EEXIST])
EEXIST

1.1.8 gc – control the garbage collector

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: gc.

Functions

gc.enable()
Enable automatic garbage collection.
gc.disable()
Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be
initiated manually using gc.collect().
gc.collect()
Run a garbage collection.

14 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

gc.mem_alloc()
Return the number of bytes of heap RAM that are allocated by Python code.

Difference to CPython
This function is MicroPython extension.

gc.mem_free()
Return the number of bytes of heap RAM that is available for Python code to allocate, or -1 if this amount is not
known.

Difference to CPython
This function is MicroPython extension.

gc.threshold([amount ])
Set or query the additional GC allocation threshold. Normally, a collection is triggered only when a new allocation
cannot be satisfied, i.e. on an out-of-memory (OOM) condition. If this function is called, in addition to OOM,
a collection will be triggered each time after amount bytes have been allocated (in total, since the previous time
such an amount of bytes have been allocated). amount is usually specified as less than the full heap size, with
the intention to trigger a collection earlier than when the heap becomes exhausted, and in the hope that an early
collection will prevent excessive memory fragmentation. This is a heuristic measure, the effect of which will vary
from application to application, as well as the optimal value of the amount parameter.
Calling the function without argument will return the current value of the threshold. A value of -1 means a disabled
allocation threshold.

Difference to CPython
This function is a MicroPython extension. CPython has a similar function - set_threshold(), but due to
different GC implementations, its signature and semantics are different.

1.1.9 gzip – gzip compression & decompression

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: gzip.
This module allows compression and decompression of binary data with the DEFLATE algorithm used by the gzip file
format.

Note: Prefer to use deflate.DeflateIO instead of the functions in this module as it provides a streaming interface
to compression and decompression which is convenient and more memory efficient when working with reading or writing
compressed data to a file, socket, or stream.

Availability:
• This module is not present by default in official MicroPython firmware releases as it duplicates functionality
available in the deflate module.
• A copy of this module can be installed (or frozen) from micropython-lib (source). See Package management for
more information. This documentation describes that module.

1.1. Python standard libraries and micro-libraries 15


MicroPython Documentation, Release v1.22.0

• Compression support will only be available if compression support is enabled in the built-in deflate module.

Functions

gzip.open(filename, mode, / )
Wrapper around built-in open() returning a GzipFile instance.
gzip.decompress(data, / )
Decompresses data into a bytes object.
gzip.compress(data, / )
Compresses data into a bytes object.

Classes

class gzip.GzipFile(*, fileobj, mode)


This class can be used to wrap a fileobj which is any stream-like object such as a file, socket, or stream (including
io.BytesIO). It is itself a stream and implements the standard read/readinto/write/close methods.
When the mode argument is "rb", reads from the GzipFile instance will decompress the data in the underlying
stream and return decompressed data.
If compression support is enabled then the mode argument can be set to "wb", and writes to the GzipFile instance
will be compressed and written to the underlying stream.
By default the GzipFile class will read and write data using the gzip file format, including a header and footer with
checksum and a window size of 512 bytes.
The file, compresslevel, and mtime arguments are not supported. fileobj and mode must always be specified as
keyword arguments.

Examples

A typical use case for gzip.GzipFile is to read or write a compressed file from storage:
import gzip

# Reading:
with open("data.gz", "rb") as f:
with gzip.GzipFile(fileobj=f, mode="rb") as g:
# Use g.read(), g.readinto(), etc.

# Same, but using gzip.open:


with gzip.open("data.gz", "rb") as f:
# Use f.read(), f.readinto(), etc.

# Writing:
with open("data.gz", "wb") as f:
with gzip.GzipFile(fileobj=f, mode="wb") as g:
# Use g.write(...) etc

# Same, but using gzip.open:


with gzip.open("data.gz", "wb") as f:
# Use f.write(...) etc

(continues on next page)

16 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)


# Write a dictionary as JSON in gzip format, with a
# small (64 byte) window size.
config = { ... }
with gzip.open("config.gz", "wb") as f:
json.dump(config, f)

For guidance on working with gzip sources and choosing the window size see the note at the end of the deflate documen-
tation.

1.1.10 hashlib – hashing algorithms

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: hashlib.
This module implements binary data hashing algorithms. The exact inventory of available algorithms depends on a board.
Among the algorithms which may be implemented:
• SHA256 - The current generation, modern hashing algorithm (of SHA2 series). It is suitable for cryptographically-
secure purposes. Included in the MicroPython core and any board is recommended to provide this, unless it has
particular code size constraints.
• SHA1 - A previous generation algorithm. Not recommended for new usages, but SHA1 is a part of number of
Internet standards and existing applications, so boards targeting network connectivity and interoperability will try
to provide this.
• MD5 - A legacy algorithm, not considered cryptographically secure. Only selected boards, targeting interoperability
with legacy applications, will offer this.

Constructors

class hashlib.sha256([data ])
Create an SHA256 hasher object and optionally feed data into it.
class hashlib.sha1([data ])
Create an SHA1 hasher object and optionally feed data into it.
class hashlib.md5([data ])
Create an MD5 hasher object and optionally feed data into it.

Methods

hash.update(data)
Feed more binary data into hash.
hash.digest()
Return hash for all data passed through hash, as a bytes object. After this method is called, more data cannot be
fed into the hash any longer.
hash.hexdigest()
This method is NOT implemented. Use binascii.hexlify(hash.digest()) to achieve a similar effect.

1.1. Python standard libraries and micro-libraries 17


MicroPython Documentation, Release v1.22.0

1.1.11 heapq – heap queue algorithm

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: heapq.
This module implements the min heap queue algorithm.
A heap queue is essentially a list that has its elements stored in such a way that the first item of the list is always the
smallest.

Functions

heapq.heappush(heap, item)
Push the item onto the heap.
heapq.heappop(heap)
Pop the first item from the heap, and return it. Raise IndexError if heap is empty.
The returned item will be the smallest item in the heap.
heapq.heapify(x)
Convert the list x into a heap. This is an in-place operation.

1.1.12 io – input/output streams

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: io.
This module contains additional types of stream (file-like) objects and helper functions.

Conceptual hierarchy

Difference to CPython
Conceptual hierarchy of stream base classes is simplified in MicroPython, as described in this section.

(Abstract) base stream classes, which serve as a foundation for behaviour of all the concrete classes, adhere to few di-
chotomies (pair-wise classifications) in CPython. In MicroPython, they are somewhat simplified and made implicit to
achieve higher efficiencies and save resources.
An important dichotomy in CPython is unbuffered vs buffered streams. In MicroPython, all streams are currently un-
buffered. This is because all modern OSes, and even many RTOSes and filesystem drivers already perform buffering on
their side. Adding another layer of buffering is counter- productive (an issue known as “bufferbloat”) and takes precious
memory. Note that there still cases where buffering may be useful, so we may introduce optional buffering support at a
later time.
But in CPython, another important dichotomy is tied with “bufferedness” - it’s whether a stream may incur short
read/writes or not. A short read is when a user asks e.g. 10 bytes from a stream, but gets less, similarly for writes.
In CPython, unbuffered streams are automatically short operation susceptible, while buffered are guarantee against them.
The no short read/writes is an important trait, as it allows to develop more concise and efficient programs - something
which is highly desirable for MicroPython. So, while MicroPython doesn’t support buffered streams, it still provides
for no-short-operations streams. Whether there will be short operations or not depends on each particular class’ needs,
but developers are strongly advised to favour no-short-operations behaviour for the reasons stated above. For example,

18 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

MicroPython sockets are guaranteed to avoid short read/writes. Actually, at this time, there is no example of a short-
operations stream class in the core, and one would be a port-specific class, where such a need is governed by hardware
peculiarities.
The no-short-operations behaviour gets tricky in case of non-blocking streams, blocking vs non-blocking behaviour being
another CPython dichotomy, fully supported by MicroPython. Non-blocking streams never wait for data either to arrive
or be written - they read/write whatever possible, or signal lack of data (or ability to write data). Clearly, this conflicts with
“no-short-operations” policy, and indeed, a case of non-blocking buffered (and this no-short-ops) streams is convoluted
in CPython - in some places, such combination is prohibited, in some it’s undefined or just not documented, in some
cases it raises verbose exceptions. The matter is much simpler in MicroPython: non-blocking stream are important for
efficient asynchronous operations, so this property prevails on the “no-short-ops” one. So, while blocking streams will
avoid short reads/writes whenever possible (the only case to get a short read is if end of file is reached, or in case of error
(but errors don’t return short data, but raise exceptions)), non-blocking streams may produce short data to avoid blocking
the operation.
The final dichotomy is binary vs text streams. MicroPython of course supports these, but while in CPython text streams
are inherently buffered, they aren’t in MicroPython. (Indeed, that’s one of the cases for which we may introduce buffering
support.)
Note that for efficiency, MicroPython doesn’t provide abstract base classes corresponding to the hierarchy above, and it’s
not possible to implement, or subclass, a stream class in pure Python.

Functions

io.open(name, mode='r', **kwargs)


Open a file. Builtin open() function is aliased to this function. All ports (which provide access to file system) are
required to support mode parameter, but support for other arguments vary by port.

Classes

class io.StringIO([string ])

class io.BytesIO([string ])
In-memory file-like objects for input/output. StringIO is used for text-mode I/O (similar to a normal file opened
with “t” modifier). BytesIO is used for binary-mode I/O (similar to a normal file opened with “b” modifier). Initial
contents of file-like objects can be specified with string parameter (should be normal string for StringIO or bytes
object for BytesIO). All the usual file methods like read(), write(), seek(), flush(), close() are
available on these objects, and additionally, a following method:
getvalue()
Get the current contents of the underlying buffer which holds data.
class io.StringIO(alloc_size)

class io.BytesIO(alloc_size)
Create an empty StringIO/BytesIO object, preallocated to hold up to alloc_size number of bytes. That means
that writing that amount of bytes won’t lead to reallocation of the buffer, and thus won’t hit out-of-memory situation
or lead to memory fragmentation. These constructors are a MicroPython extension and are recommended for usage
only in special cases and in system-level libraries, not for end-user applications.

Difference to CPython
These constructors are a MicroPython extension.

1.1. Python standard libraries and micro-libraries 19


MicroPython Documentation, Release v1.22.0

1.1.13 json – JSON encoding and decoding

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: json.
This modules allows to convert between Python objects and the JSON data format.

Functions

json.dump(obj, stream, separators=None)


Serialise obj to a JSON string, writing it to the given stream.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (',
', ': '). To get the most compact JSON representation, you should specify (',', ':') to eliminate
whitespace.
json.dumps(obj, separators=None)
Return obj represented as a JSON string.
The arguments have the same meaning as in dump.
json.load(stream)
Parse the given stream, interpreting it as a JSON string and deserialising the data to a Python object. The resulting
object is returned.
Parsing continues until end-of-file is encountered. A ValueError is raised if the data in stream is not correctly
formed.
json.loads(str)
Parse the JSON str and return an object. Raises ValueError if the string is not correctly formed.

1.1.14 math – mathematical functions

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: math.
The math module provides some basic mathematical functions for working with floating-point numbers.
Note: On the pyboard, floating-point numbers have 32-bit precision.
Availability: not available on WiPy. Floating point support required for this module.

Functions

math.acos(x)
Return the inverse cosine of x.
math.acosh(x)
Return the inverse hyperbolic cosine of x.
math.asin(x)
Return the inverse sine of x.
math.asinh(x)
Return the inverse hyperbolic sine of x.

20 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

math.atan(x)
Return the inverse tangent of x.
math.atan2(y, x)
Return the principal value of the inverse tangent of y/x.
math.atanh(x)
Return the inverse hyperbolic tangent of x.
math.ceil(x)
Return an integer, being x rounded towards positive infinity.
math.copysign(x, y)
Return x with the sign of y.
math.cos(x)
Return the cosine of x.
math.cosh(x)
Return the hyperbolic cosine of x.
math.degrees(x)
Return radians x converted to degrees.
math.erf(x)
Return the error function of x.
math.erfc(x)
Return the complementary error function of x.
math.exp(x)
Return the exponential of x.
math.expm1(x)
Return exp(x) - 1.
math.fabs(x)
Return the absolute value of x.
math.floor(x)
Return an integer, being x rounded towards negative infinity.
math.fmod(x, y)
Return the remainder of x/y.
math.frexp(x)
Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m, e) such
that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the relation 0.5
<= abs(m) < 1 holds.
math.gamma(x)
Return the gamma function of x.
math.isfinite(x)
Return True if x is finite.
math.isinf(x)
Return True if x is infinite.

1.1. Python standard libraries and micro-libraries 21


MicroPython Documentation, Release v1.22.0

math.isnan(x)
Return True if x is not-a-number
math.ldexp(x, exp)
Return x * (2**exp).
math.lgamma(x)
Return the natural logarithm of the gamma function of x.
math.log(x)
Return the natural logarithm of x.
math.log10(x)
Return the base-10 logarithm of x.
math.log2(x)
Return the base-2 logarithm of x.
math.modf(x)
Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same sign as
x.
math.pow(x, y)
Returns x to the power of y.
math.radians(x)
Return degrees x converted to radians.
math.sin(x)
Return the sine of x.
math.sinh(x)
Return the hyperbolic sine of x.
math.sqrt(x)
Return the square root of x.
math.tan(x)
Return the tangent of x.
math.tanh(x)
Return the hyperbolic tangent of x.
math.trunc(x)
Return an integer, being x rounded towards 0.

Constants

math.e
base of the natural logarithm
math.pi
the ratio of a circle’s circumference to its diameter

22 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

1.1.15 os – basic “operating system” services

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: os.
The os module contains functions for filesystem access and mounting, terminal redirection and duplication, and the
uname and urandom functions.

General functions

os.uname()
Return a tuple (possibly a named tuple) containing information about the underlying machine and/or its operating
system. The tuple has five fields in the following order, each of them being a string:
• sysname – the name of the underlying system
• nodename – the network name (can be the same as sysname)
• release – the version of the underlying system
• version – the MicroPython version and build date
• machine – an identifier for the underlying hardware (eg board, CPU)
os.urandom(n)
Return a bytes object with n random bytes. Whenever possible, it is generated by the hardware random number
generator.

Filesystem access

os.chdir(path)
Change current directory.
os.getcwd()
Get the current directory.
os.ilistdir([dir ])
This function returns an iterator which then yields tuples corresponding to the entries in the directory that it is
listing. With no argument it lists the current directory, otherwise it lists the directory given by dir.
The tuples have the form (name, type, inode[, size]):
• name is a string (or bytes if dir is a bytes object) and is the name of the entry;
• type is an integer that specifies the type of the entry, with 0x4000 for directories and 0x8000 for regular files;
• inode is an integer corresponding to the inode of the file, and may be 0 for filesystems that don’t have such a
notion.
• Some platforms may return a 4-tuple that includes the entry’s size. For file entries, size is an integer repre-
senting the size of the file or -1 if unknown. Its meaning is currently undefined for directory entries.
os.listdir([dir ])
With no argument, list the current directory. Otherwise list the given directory.
os.mkdir(path)
Create a new directory.

1.1. Python standard libraries and micro-libraries 23


MicroPython Documentation, Release v1.22.0

os.remove(path)
Remove a file.
os.rmdir(path)
Remove a directory.
os.rename(old_path, new_path)
Rename a file.
os.stat(path)
Get the status of a file or directory.
os.statvfs(path)
Get the status of a filesystem.
Returns a tuple with the filesystem information in the following order:
• f_bsize – file system block size
• f_frsize – fragment size
• f_blocks – size of fs in f_frsize units
• f_bfree – number of free blocks
• f_bavail – number of free blocks for unprivileged users
• f_files – number of inodes
• f_ffree – number of free inodes
• f_favail – number of free inodes for unprivileged users
• f_flag – mount flags
• f_namemax – maximum filename length
Parameters related to inodes: f_files, f_ffree, f_avail and the f_flags parameter may return 0 as
they can be unavailable in a port-specific implementation.
os.sync()
Sync all filesystems.

Terminal redirection and duplication

os.dupterm(stream_object, index=0, / )
Duplicate or switch the MicroPython terminal (the REPL) on the given stream-like object. The stream_object
argument must be a native stream object, or derive from io.IOBase and implement the readinto() and
write() methods. The stream should be in non-blocking mode and readinto() should return None if there
is no data available for reading.
After calling this function all terminal output is repeated on this stream, and any input that is available on the stream
is passed on to the terminal input.
The index parameter should be a non-negative integer and specifies which duplication slot is set. A given port
may implement more than one slot (slot 0 will always be available) and in that case terminal input and output is
duplicated on all the slots that are set.
If None is passed as the stream_object then duplication is cancelled on the slot given by index.
The function returns the previous stream-like object in the given slot.

24 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Filesystem mounting

Some ports provide a Virtual Filesystem (VFS) and the ability to mount multiple “real” filesystems within this VFS.
Filesystem objects can be mounted at either the root of the VFS, or at a subdirectory that lives in the root. This allows
dynamic and flexible configuration of the filesystem that is seen by Python programs. Ports that have this functionality
provide the mount() and umount() functions, and possibly various filesystem implementations represented by VFS
classes.
os.mount(fsobj, mount_point, *, readonly)
Mount the filesystem object fsobj at the location in the VFS given by the mount_point string. fsobj can be a a VFS
object that has a mount() method, or a block device. If it’s a block device then the filesystem type is automatically
detected (an exception is raised if no filesystem was recognised). mount_point may be '/' to mount fsobj at the
root, or '/<name>' to mount it at a subdirectory under the root.
If readonly is True then the filesystem is mounted read-only.
During the mount process the method mount() is called on the filesystem object.
Will raise OSError(EPERM) if mount_point is already mounted.
os.umount(mount_point)
Unmount a filesystem. mount_point can be a string naming the mount location, or a previously-mounted filesystem
object. During the unmount process the method umount() is called on the filesystem object.
Will raise OSError(EINVAL) if mount_point is not found.
class os.VfsFat(block_dev)
Create a filesystem object that uses the FAT filesystem format. Storage of the FAT filesystem is provided by
block_dev. Objects created by this constructor can be mounted using mount().
static mkfs(block_dev)
Build a FAT filesystem on block_dev.
class os.VfsLfs1(block_dev, readsize=32, progsize=32, lookahead=32)
Create a filesystem object that uses the littlefs v1 filesystem format. Storage of the littlefs filesystem is provided by
block_dev, which must support the extended interface. Objects created by this constructor can be mounted using
mount().
See Working with filesystems for more information.
static mkfs(block_dev, readsize=32, progsize=32, lookahead=32)
Build a Lfs1 filesystem on block_dev.

Note: There are reports of littlefs v1 failing in certain situations, for details see littlefs issue 347.

class os.VfsLfs2(block_dev, readsize=32, progsize=32, lookahead=32, mtime=True)


Create a filesystem object that uses the littlefs v2 filesystem format. Storage of the littlefs filesystem is provided by
block_dev, which must support the extended interface. Objects created by this constructor can be mounted using
mount().
The mtime argument enables modification timestamps for files, stored using littlefs attributes. This option can be
disabled or enabled differently each mount time and timestamps will only be added or updated if mtime is enabled,
otherwise the timestamps will remain untouched. Littlefs v2 filesystems without timestamps will work without
reformatting and timestamps will be added transparently to existing files once they are opened for writing. When
mtime is enabled os.stat on files without timestamps will return 0 for the timestamp.
See Working with filesystems for more information.

1.1. Python standard libraries and micro-libraries 25


MicroPython Documentation, Release v1.22.0

static mkfs(block_dev, readsize=32, progsize=32, lookahead=32)


Build a Lfs2 filesystem on block_dev.

Note: There are reports of littlefs v2 failing in certain situations, for details see littlefs issue 295.

Block devices

A block device is an object which implements the block protocol. This enables a device to support MicroPython filesys-
tems. The physical hardware is represented by a user defined class. The AbstractBlockDev class is a template
for the design of such a class: MicroPython does not actually provide that class, but an actual block device class must
implement the methods described below.
A concrete implementation of this class will usually allow access to the memory-like functionality of a piece of hardware
(like flash memory). A block device can be formatted to any supported filesystem and mounted using os methods.
See Working with filesystems for example implementations of block devices using the two variants of the block protocol
described below.

Simple and extended interface

There are two compatible signatures for the readblocks and writeblocks methods (see below), in order to support
a variety of use cases. A given block device may implement one form or the other, or both at the same time. The second
form (with the offset parameter) is referred to as the “extended interface”.
Some filesystems (such as littlefs) that require more control over write operations, for example writing to sub-block regions
without erasing, may require that the block device supports the extended interface.
class os.AbstractBlockDev(...)
Construct a block device object. The parameters to the constructor are dependent on the specific block device.
readblocks(block_num, buf)
readblocks(block_num, buf, offset)
The first form reads aligned, multiples of blocks. Starting at the block given by the index block_num, read
blocks from the device into buf (an array of bytes). The number of blocks to read is given by the length of
buf, which will be a multiple of the block size.
The second form allows reading at arbitrary locations within a block, and arbitrary lengths. Starting at block
index block_num, and byte offset within that block of offset, read bytes from the device into buf (an array of
bytes). The number of bytes to read is given by the length of buf.
writeblocks(block_num, buf)
writeblocks(block_num, buf, offset)
The first form writes aligned, multiples of blocks, and requires that the blocks that are written to be first erased
(if necessary) by this method. Starting at the block given by the index block_num, write blocks from buf (an
array of bytes) to the device. The number of blocks to write is given by the length of buf, which will be a
multiple of the block size.
The second form allows writing at arbitrary locations within a block, and arbitrary lengths. Only the bytes
being written should be changed, and the caller of this method must ensure that the relevant blocks are erased
via a prior ioctl call. Starting at block index block_num, and byte offset within that block of offset, write
bytes from buf (an array of bytes) to the device. The number of bytes to write is given by the length of buf.
Note that implementations must never implicitly erase blocks if the offset argument is specified, even if it is
zero.

26 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

ioctl(op, arg)

Control the block device and query its parameters. The operation to perform is given by op which
is one of the following integers:
• 1 – initialise the device (arg is unused)
• 2 – shutdown the device (arg is unused)
• 3 – sync the device (arg is unused)
• 4 – get a count of the number of blocks, should return an integer (arg is unused)
• 5 – get the number of bytes in a block, should return an integer, or None in which case the
default value of 512 is used (arg is unused)
• 6 – erase a block, arg is the block number to erase
As a minimum ioctl(4, ...) must be intercepted; for littlefs ioctl(6, ...) must also be inter-
cepted. The need for others is hardware dependent.
Prior to any call to writeblocks(block, ...) littlefs issues ioctl(6, block). This enables
a device driver to erase the block prior to a write if the hardware requires it. Alternatively a driver might
intercept ioctl(6, block) and return 0 (success). In this case the driver assumes responsibility for
detecting the need for erasure.
Unless otherwise stated ioctl(op, arg) can return None. Consequently an implementation can ig-
nore unused values of op. Where op is intercepted, the return value for operations 4 and 5 are as detailed
above. Other operations should return 0 on success and non-zero for failure, with the value returned being an
OSError errno code.

1.1.16 platform – access to underlying platform’s identifying data

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: platform.
This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function
APIs.

Functions

platform.platform()
Returns a string identifying the underlying platform. This string is composed of several substrings in the following
order, delimited by dashes (-):
• the name of the platform system (e.g. Unix, Windows or MicroPython)
• the MicroPython version
• the architecture of the platform
• the version of the underlying platform
• the concatenation of the name of the libc that MicroPython is linked to and its corresponding version.
For example, this could be "MicroPython-1.20.0-xtensa-IDFv4.2.4-with-newlib3.0.0".
platform.python_compiler()
Returns a string identifying the compiler used for compiling MicroPython.

1.1. Python standard libraries and micro-libraries 27


MicroPython Documentation, Release v1.22.0

platform.libc_ver()
Returns a tuple of strings (lib, version), where lib is the name of the libc that MicroPython is linked to, and version
the corresponding version of this libc.

1.1.17 random – generate random numbers

This module implements a pseudo-random number generator (PRNG).


This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: random .

Note: The following notation is used for intervals:


• () are open interval brackets and do not include their endpoints. For example, (0, 1) means greater than 0 and less
than 1. In set notation: (0, 1) = {x | 0 < x < 1}.
• [] are closed interval brackets which include all their limit points. For example, [0, 1] means greater than or equal
to 0 and less than or equal to 1. In set notation: [0, 1] = {x | 0 <= x <= 1}.

Note: The randrange(), randint() and choice() functions are only available if the MI-
CROPY_PY_RANDOM_EXTRA_FUNCS configuration option is enabled.

Functions for integers

random.getrandbits(n)
Return an integer with n random bits (0 <= n <= 32).
random.randint(a, b)
Return a random integer in the range [a, b].
random.randrange(stop)
random.randrange(start, stop)
random.randrange(start, stop[, step ])
The first form returns a random integer from the range [0, stop). The second form returns a random integer from
the range [start, stop). The third form returns a random integer from the range [start, stop) in steps of step. For
instance, calling randrange(1, 10, 2) will return odd numbers between 1 and 9 inclusive.

Functions for floats

random.random()
Return a random floating point number in the range [0.0, 1.0).
random.uniform(a, b)
Return a random floating point number N such that a <= N <= b for a <= b, and b <= N <= a for b < a.

28 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Other Functions

random.seed(n=None, / )
Initialise the random number generator module with the seed n which should be an integer. When no argument
(or None) is passed in it will (if supported by the port) initialise the PRNG with a true random number (usually a
hardware generated random number).
The None case only works if MICROPY_PY_RANDOM_SEED_INIT_FUNC is enabled by the port, otherwise it
raises ValueError.
random.choice(sequence)
Chooses and returns one item at random from sequence (tuple, list or any object that supports the subscript opera-
tion).

1.1.18 re – simple regular expressions

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: re.
This module implements regular expression operations. Regular expression syntax supported is a subset of CPython re
module (and actually is a subset of POSIX extended regular expressions).
Supported operators and special sequences are:
.
Match any character.
[...]
Match set of characters. Individual characters and ranges are supported, including negated sets (e.g. [^a-c]).
^
Match the start of the string.
$
Match the end of the string.
?
Match zero or one of the previous sub-pattern.
*
Match zero or more of the previous sub-pattern.
+
Match one or more of the previous sub-pattern.
??
Non-greedy version of ?, match zero or one, with the preference for zero.
*?
Non-greedy version of *, match zero or more, with the preference for the shortest match.
+?
Non-greedy version of +, match one or more, with the preference for the shortest match.
|
Match either the left-hand side or the right-hand side sub-patterns of this operator.
(...)
Grouping. Each group is capturing (a substring it captures can be accessed with match.group() method).

1.1. Python standard libraries and micro-libraries 29


MicroPython Documentation, Release v1.22.0

\d
Matches digit. Equivalent to [0-9].
\D
Matches non-digit. Equivalent to [^0-9].
\s
Matches whitespace. Equivalent to [ \t-\r].
\S
Matches non-whitespace. Equivalent to [^ \t-\r].
\w
Matches “word characters” (ASCII only). Equivalent to [A-Za-z0-9_].
\W
Matches non “word characters” (ASCII only). Equivalent to [^A-Za-z0-9_].
\
Escape character. Any other character following the backslash, except for those listed above, is taken literally.
For example, \* is equivalent to literal * (not treated as the * operator). Note that \r, \n, etc. are not handled
specially, and will be equivalent to literal letters r, n, etc. Due to this, it’s not recommended to use raw Python
strings (r"") for regular expressions. For example, r"\r\n" when used as the regular expression is equivalent
to "rn". To match CR character followed by LF, use "\r\n".
NOT SUPPORTED:
• counted repetitions ({m,n})
• named groups ((?P<name>...))
• non-capturing groups ((?:...))
• more advanced assertions (\b, \B)
• special character escapes like \r, \n - use Python’s own escaping instead
• etc.
Example:

import re

# As re doesn't support escapes itself, use of r"" strings is not


# recommended.
regex = re.compile("[\r\n]")

regex.split("line1\rline2\nline3\r\n")

# Result:
# ['line1', 'line2', 'line3', '', '']

30 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Functions

re.compile(regex_str[, flags ])
Compile regular expression, return regex object.
re.match(regex_str, string)
Compile regex_str and match against string. Match always happens from starting position in a string.
re.search(regex_str, string)
Compile regex_str and search it in a string. Unlike match, this will search string for first position which matches
regex (which still may be 0 if regex is anchored).
re.sub(regex_str, replace, string, count=0, flags=0, / )
Compile regex_str and search for it in string, replacing all matches with replace, and returning the new string.
replace can be a string or a function. If it is a string then escape sequences of the form \<number> and \
g<number> can be used to expand to the corresponding group (or an empty string for unmatched groups). If
replace is a function then it must take a single argument (the match) and should return a replacement string.
If count is specified and non-zero then substitution will stop after this many substitutions are made. The flags
argument is ignored.
Note: availability of this function depends on MicroPython port.
re.DEBUG
Flag value, display debug information about compiled expression. (Availability depends on MicroPython port.)

Regex objects

Compiled regular expression. Instances of this class are created using re.compile().
regex.match(string)
regex.search(string)
regex.sub(replace, string, count=0, flags=0, / )
Similar to the module-level functions match(), search() and sub(). Using methods is (much) more efficient
if the same regex is applied to multiple strings.
regex.split(string, max_split=-1, / )
Split a string using regex. If max_split is given, it specifies maximum number of splits to perform. Returns list of
strings (there may be up to max_split+1 elements if it’s specified).

Match objects

Match objects as returned by match() and search() methods, and passed to the replacement function in sub().
match.group(index)
Return matching (sub)string. index is 0 for entire match, 1 and above for each capturing group. Only numeric
groups are supported.
match.groups()
Return a tuple containing all the substrings of the groups of the match.
Note: availability of this method depends on MicroPython port.
match.start([index ])

1.1. Python standard libraries and micro-libraries 31


MicroPython Documentation, Release v1.22.0

match.end([index ])
Return the index in the original string of the start or end of the substring group that was matched. index defaults to
the entire group, otherwise it will select a group.
Note: availability of these methods depends on MicroPython port.
match.span([index ])
Returns the 2-tuple (match.start(index), match.end(index)).
Note: availability of this method depends on MicroPython port.

1.1.19 select – wait for events on a set of streams

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: select.
This module provides functions to efficiently wait for events on multiple streams (select streams which are ready for
operations).

Functions

select.poll()
Create an instance of the Poll class.
select.select(rlist, wlist, xlist [, timeout ])
Wait for activity on a set of objects.
This function is provided by some MicroPython ports for compatibility and is not efficient. Usage of Poll is
recommended instead.

class Poll

Methods

poll.register(obj [, eventmask ])
Register stream obj for polling. eventmask is logical OR of:
• select.POLLIN - data available for reading
• select.POLLOUT - more data can be written
Note that flags like select.POLLHUP and select.POLLERR are not valid as input eventmask (these are
unsolicited events which will be returned from poll() regardless of whether they are asked for). This semantics
is per POSIX.
eventmask defaults to select.POLLIN | select.POLLOUT.
It is OK to call this function multiple times for the same obj. Successive calls will update obj’s eventmask to the
value of eventmask (i.e. will behave as modify()).
poll.unregister(obj)
Unregister obj from polling.
poll.modify(obj, eventmask)
Modify the eventmask for obj. If obj is not registered, OSError is raised with error of ENOENT.

32 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

poll.poll(timeout=-1, / )
Wait for at least one of the registered objects to become ready or have an exceptional condition, with optional
timeout in milliseconds (if timeout arg is not specified or -1, there is no timeout).
Returns list of (obj, event, …) tuples. There may be other elements in tuple, depending on a platform and
version, so don’t assume that its size is 2. The event element specifies which events happened with a stream
and is a combination of select.POLL* constants described above. Note that flags select.POLLHUP and
select.POLLERR can be returned at any time (even if were not asked for), and must be acted on accordingly
(the corresponding stream unregistered from poll and likely closed), because otherwise all further invocations of
poll() may return immediately with these flags set for this stream again.
In case of timeout, an empty list is returned.

Difference to CPython
Tuples returned may contain more than 2 elements as described above.

poll.ipoll(timeout=-1, flags=0, / )
Like poll.poll(), but instead returns an iterator which yields a callee-owned tuple. This function
provides an efficient, allocation-free way to poll on streams.
If flags is 1, one-shot behaviour for events is employed: streams for which events happened will have their event
masks automatically reset (equivalent to poll.modify(obj, 0)), so new events for such a stream won’t be
processed until new mask is set with poll.modify(). This behaviour is useful for asynchronous I/O schedulers.

Difference to CPython
This function is a MicroPython extension.

1.1.20 socket – socket module

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: socket.
This module provides access to the BSD socket interface.

Difference to CPython
For efficiency and consistency, socket objects in MicroPython implement a stream (file-like) interface directly. In
CPython, you need to convert a socket to a file-like object using makefile() method. This method is still supported
by MicroPython (but is a no-op), so where compatibility with CPython matters, be sure to use it.

1.1. Python standard libraries and micro-libraries 33


MicroPython Documentation, Release v1.22.0

Socket address format(s)

The native socket address format of the socket module is an opaque data type returned by getaddrinfo function,
which must be used to resolve textual address (including numeric addresses):

sockaddr = socket.getaddrinfo('www.micropython.org', 80)[0][-1]


# You must use getaddrinfo() even for numeric addresses
sockaddr = socket.getaddrinfo('127.0.0.1', 80)[0][-1]
# Now you can use that address
sock.connect(sockaddr)

Using getaddrinfo is the most efficient (both in terms of memory and processing power) and portable way to work
with addresses.
However, socket module (note the difference with native MicroPython socket module described here) provides
CPython-compatible way to specify addresses using tuples, as described below. Note that depending on a MicroPython
port, socket module can be builtin or need to be installed from micropython-lib (as in the case of MicroPython
Unix port), and some ports still accept only numeric addresses in the tuple format, and require to use getaddrinfo
function to resolve domain names.
Summing up:
• Always use getaddrinfo when writing portable applications.
• Tuple addresses described below can be used as a shortcut for quick hacks and interactive use, if your port supports
them.
Tuple address format for socket module:
• IPv4: (ipv4_address, port), where ipv4_address is a string with dot-notation numeric IPv4 address, e.g. "8.8.
8.8", and port is and integer port number in the range 1-65535. Note the domain names are not accepted as
ipv4_address, they should be resolved first using socket.getaddrinfo().
• IPv6: (ipv6_address, port, flowinfo, scopeid), where ipv6_address is a string with colon-notation numeric IPv6
address, e.g. "2001:db8::1", and port is an integer port number in the range 1-65535. flowinfo must be
0. scopeid is the interface scope identifier for link-local addresses. Note the domain names are not accepted
as ipv6_address, they should be resolved first using socket.getaddrinfo(). Availability of IPv6 support
depends on a MicroPython port.

Functions

socket.getaddrinfo(host, port, af=0, type=0, proto=0, flags=0, / )


Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creat-
ing a socket connected to that service. Arguments af, type, and proto (which have the same meaning as for the
socket() function) can be used to filter which kind of addresses are returned. If a parameter is not specified or
zero, all combinations of addresses can be returned (requiring filtering on the user side).
The resulting list of 5-tuples has the following structure:

(family, type, proto, canonname, sockaddr)

The following example shows how to connect to a given url:

s = socket.socket()
# This assumes that if "type" is not specified, an address for
# SOCK_STREAM will be returned, which may be not true
s.connect(socket.getaddrinfo('www.micropython.org', 80)[0][-1])

34 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Recommended use of filtering params:

s = socket.socket()
# Guaranteed to return an address which can be connect'ed to for
# stream operation.
s.connect(socket.getaddrinfo('www.micropython.org', 80, 0, SOCK_STREAM)[0][-1])

Difference to CPython
CPython raises a socket.gaierror exception (OSError subclass) in case of error in this function. Mi-
croPython doesn’t have socket.gaierror and raises OSError directly. Note that error numbers of getad-
drinfo() form a separate namespace and may not match error numbers from the errno module. To distinguish
getaddrinfo() errors, they are represented by negative numbers, whereas standard system errors are positive
numbers (error numbers are accessible using e.args[0] property from an exception object). The use of negative
values is a provisional detail which may change in the future.

socket.inet_ntop(af, bin_addr)
Convert a binary network address bin_addr of the given address family af to a textual representation:

>>> socket.inet_ntop(socket.AF_INET, b"\x7f\0\0\1")


'127.0.0.1'

socket.inet_pton(af, txt_addr)
Convert a textual network address txt_addr of the given address family af to a binary representation:

>>> socket.inet_pton(socket.AF_INET, "1.2.3.4")


b'\x01\x02\x03\x04'

Constants

socket.AF_INET
socket.AF_INET6
Address family types. Availability depends on a particular MicroPython port.
socket.SOCK_STREAM
socket.SOCK_DGRAM
Socket types.
socket.IPPROTO_UDP
socket.IPPROTO_TCP
IP protocol numbers. Availability depends on a particular MicroPython port. Note that you don’t need to spec-
ify these in a call to socket.socket(), because SOCK_STREAM socket type automatically selects IP-
PROTO_TCP, and SOCK_DGRAM - IPPROTO_UDP. Thus, the only real use of these constants is as an argument
to setsockopt().
socket.SOL_*
Socket option levels (an argument to setsockopt()). The exact inventory depends on a MicroPython port.
socket.SO_*
Socket options (an argument to setsockopt()). The exact inventory depends on a MicroPython port.
Constants specific to WiPy:

1.1. Python standard libraries and micro-libraries 35


MicroPython Documentation, Release v1.22.0

socket.IPPROTO_SEC
Special protocol value to create SSL-compatible socket.

class socket

class socket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, / )


Create a new socket using the given address family, socket type and protocol number. Note that specifying proto in
most cases is not required (and not recommended, as some MicroPython ports may omit IPPROTO_* constants).
Instead, type argument will select needed protocol automatically:

# Create STREAM TCP socket


socket(AF_INET, SOCK_STREAM)
# Create DGRAM UDP socket
socket(AF_INET, SOCK_DGRAM)

Methods

socket.close()
Mark the socket closed and release all resources. Once that happens, all future operations on the socket object will
fail. The remote end will receive EOF indication if supported by protocol.
Sockets are automatically closed when they are garbage-collected, but it is recommended to close() them ex-
plicitly as soon you finished working with them.
socket.bind(address)
Bind the socket to address. The socket must not already be bound.
socket.listen([backlog ])
Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it’s lower, it will be set to 0);
and specifies the number of unaccepted connections that the system will allow before refusing new connections. If
not specified, a default reasonable value is chosen.
socket.accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value is
a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and
address is the address bound to the socket on the other end of the connection.
socket.connect(address)
Connect to a remote socket at address.
socket.send(bytes)
Send data to the socket. The socket must be connected to a remote socket. Returns number of bytes sent, which
may be smaller than the length of data (“short write”).
socket.sendall(bytes)
Send all data to the socket. The socket must be connected to a remote socket. Unlike send(), this method will
try to send all of data, by sending data chunk by chunk consecutively.
The behaviour of this method on non-blocking sockets is undefined. Due to this, on MicroPython, it’s recommended
to use write() method instead, which has the same “no short writes” policy for blocking sockets, and will return
number of bytes sent on non-blocking sockets.

36 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

socket.recv(bufsize)
Receive data from the socket. The return value is a bytes object representing the data received. The maximum
amount of data to be received at once is specified by bufsize.
socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is
specified by address.
socket.recvfrom(bufsize)
Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing
the data received and address is the address of the socket sending the data.
socket.setsockopt(level, optname, value)
Set the value of the given socket option. The needed symbolic constants are defined in the socket module (SO_*
etc.). The value can be an integer or a bytes-like object representing a buffer.
socket.settimeout(value)
Note: Not every port supports this method, see below.
Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number
expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise an OSError
exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket
is put in non-blocking mode. If None is given, the socket is put in blocking mode.
Not every MicroPython port supports this method. A more portable and generic solution is to use select.poll
object. This allows to wait on multiple objects at the same time (and not just on sockets, but on generic stream
objects which support polling). Example:

# Instead of:
s.settimeout(1.0) # time in seconds
s.read(10) # may timeout

# Use:
poller = select.poll()
poller.register(s, select.POLLIN)
res = poller.poll(1000) # time in milliseconds
if not res:
# s is still not ready for input, i.e. operation timed out

Difference to CPython
CPython raises a socket.timeout exception in case of timeout, which is an OSError subclass. MicroPython
raises an OSError directly instead. If you use except OSError: to catch the exception, your code will work
both in MicroPython and CPython.

socket.setblocking(flag)
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking
mode.
This method is a shorthand for certain settimeout() calls:
• sock.setblocking(True) is equivalent to sock.settimeout(None)
• sock.setblocking(False) is equivalent to sock.settimeout(0)

1.1. Python standard libraries and micro-libraries 37


MicroPython Documentation, Release v1.22.0

socket.makefile(mode='rb', buffering=0, / )
Return a file object associated with the socket. The exact returned type depends on the arguments given to make-
file(). The support is limited to binary modes only (‘rb’, ‘wb’, and ‘rwb’). CPython’s arguments: encoding, errors
and newline are not supported.

Difference to CPython
As MicroPython doesn’t support buffered streams, values of buffering parameter is ignored and treated as if it was
0 (unbuffered).

Difference to CPython
Closing the file object returned by makefile() WILL close the original socket as well.

socket.read([size ])
Read up to size bytes from the socket. Return a bytes object. If size is not given, it reads all data available from the
socket until EOF; as such the method will not return until the socket is closed. This function tries to read as much
data as requested (no “short reads”). This may be not possible with non-blocking socket though, and then less data
will be returned.
socket.readinto(buf [, nbytes ])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most len(buf)
bytes. Just as read(), this method follows “no short reads” policy.
Return value: number of bytes read and stored into buf.
socket.readline()
Read a line, ending in a newline character.
Return value: the line read.
socket.write(buf)
Write the buffer of bytes to the socket. This function will try to write all data to a socket (no “short writes”). This
may be not possible with a non-blocking socket though, and returned value will be less than the length of buf.
Return value: number of bytes written.
exception socket.error
MicroPython does NOT have this exception.

Difference to CPython
CPython used to have a socket.error exception which is now deprecated, and is an alias of OSError. In
MicroPython, use OSError directly.

38 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

1.1.21 ssl – SSL/TLS module

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: ssl.
This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) en-
cryption and peer authentication facilities for network sockets, both client-side and server-side.

Functions

ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, cadata=None,


server_hostname=None, do_handshake=True)

Wrap the given sock and return a new wrapped-socket object. The implementation of this function
is to first create an SSLContext and then call the SSLContext.wrap_socket method on that
context object. The arguments sock, server_side and server_hostname are passed through unchanged
to the method call. The argument do_handshake is passed through as do_handshake_on_connect. The
remaining arguments have the following behaviour:

• cert_reqs determines whether the peer (server or client) must present a valid certificate. Note that for mbedtls
based ports, ssl.CERT_NONE and ssl.CERT_OPTIONAL will not validate any certificate, only ssl.
CERT_REQUIRED will.
• cadata is a bytes object containing the CA certificate chain (in DER format) that will validate the peer’s
certificate. Currently only a single DER-encoded certificate is supported.

Depending on the underlying module implementation in a particular MicroPython port, some or all keyword argu-
ments above may be not supported.

class SSLContext

class ssl.SSLContext(protocol, / )
Create a new SSLContext instance. The protocol argument must be one of the PROTOCOL_* constants.
SSLContext.load_cert_chain(certfile, keyfile)
Load a private key and the corresponding certificate. The certfile is a string with the file path of the certificate. The
keyfile is a string with the file path of the private key.

Difference to CPython
MicroPython extension: certfile and keyfile can be bytes objects instead of strings, in which case they are interpreted
as the actual certificate/key data.

SSLContext.load_verify_locations(cafile=None, cadata=None)
Load the CA certificate chain that will validate the peer’s certificate. cafile is the file path of the CA certificates.
cadata is a bytes object containing the CA certificates. Only one of these arguments should be provided.
SSLContext.get_ciphers()
Get a list of enabled ciphers, returned as a list of strings.
SSLContext.set_ciphers(ciphers)
Set the available ciphers for sockets created with this context. ciphers should be a list of strings in the IANA cipher
suite format .

1.1. Python standard libraries and micro-libraries 39


MicroPython Documentation, Release v1.22.0

SSLContext.wrap_socket(sock, *, server_side=False, do_handshake_on_connect=True,


server_hostname=None)
Takes a stream sock (usually socket.socket instance of SOCK_STREAM type), and returns an instance of
ssl.SSLSocket, wrapping the underlying stream. The returned object has the usual stream interface methods
like read(), write(), etc.
• server_side selects whether the wrapped socket is on the server or client side. A server-side SSL socket should
be created from a normal socket returned from accept() on a non-SSL listening server socket.
• do_handshake_on_connect determines whether the handshake is done as part of the wrap_socket or
whether it is deferred to be done as part of the initial reads or writes For blocking sockets doing the hand-
shake immediately is standard. For non-blocking sockets (i.e. when the sock passed into wrap_socket
is in non-blocking mode) the handshake should generally be deferred because otherwise wrap_socket
blocks until it completes. Note that in AXTLS the handshake can be deferred until the first read or write but
it then blocks until completion.
• server_hostname is for use as a client, and sets the hostname to check against the received server certificate.
It also sets the name for Server Name Indication (SNI), allowing the server to present the proper certificate.

Warning: Some implementations of ssl module do NOT validate server certificates, which makes an SSL con-
nection established prone to man-in-the-middle attacks.
CPython’s wrap_socket returns an SSLSocket object which has methods typical for sockets, such as send,
recv, etc. MicroPython’s wrap_socket returns an object more similar to CPython’s SSLObject which does
not have these socket methods.

SSLContext.verify_mode
Set or get the behaviour for verification of peer certificates. Must be one of the CERT_* constants.

Note: ssl.CERT_REQUIRED requires the device’s date/time to be properly set, e.g. using mpremote rtc --set or
ntptime, and server_hostname must be specified when on the client side.

Exceptions

ssl.SSLError
This exception does NOT exist. Instead its base class, OSError, is used.

Constants

ssl.PROTOCOL_TLS_CLIENT
ssl.PROTOCOL_TLS_SERVER
Supported values for the protocol parameter.
ssl.CERT_NONE
ssl.CERT_OPTIONAL
ssl.CERT_REQUIRED
Supported values for cert_reqs parameter, and the SSLContext.verify_mode attribute.

40 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

1.1.22 struct – pack and unpack primitive data types

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: struct.
The following byte orders are supported:

Character Byte order Size Alignment


@ native native native
< little-endian standard none
> big-endian standard none
! network (= big-endian) standard none

The following data types are supported:

Format C Type Python type Standard size


b signed char integer 1
B unsigned char integer 1
h short integer 2
H unsigned short integer 2
i int integer (1) 4
I unsigned int integer (1) 4
l long integer (1) 4
L unsigned long integer (1) 4
q long long integer (1) 8
Q unsigned long long integer (1) 8
f float float (2) 4
d double float (2) 8
s char[] bytes
P void * integer

(1) Requires long support when used with values larger than 30 bits.
(2) Requires floating point support.

Difference to CPython
Whitespace is not supported in format strings.

Functions

struct.calcsize(fmt)
Return the number of bytes needed to store the given fmt.
struct.pack(fmt, v1, v2, ...)
Pack the values v1, v2, … according to the format string fmt. The return value is a bytes object encoding the values.
struct.pack_into(fmt, buffer, offset, v1, v2, ...)
Pack the values v1, v2, … according to the format string fmt into a buffer starting at offset. offset may be negative
to count from the end of buffer.

1.1. Python standard libraries and micro-libraries 41


MicroPython Documentation, Release v1.22.0

struct.unpack(fmt, data)
Unpack from the data according to the format string fmt. The return value is a tuple of the unpacked values.
struct.unpack_from(fmt, data, offset=0, / )
Unpack from the data starting at offset according to the format string fmt. offset may be negative to count from the
end of data. The return value is a tuple of the unpacked values.

1.1.23 sys – system specific functions

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: sys.

Functions

sys.exit(retval=0, / )
Terminate current program with a given exit code. Underlyingly, this function raise as SystemExit exception.
If an argument is given, its value given as an argument to SystemExit.
sys.atexit(func)
Register func to be called upon termination. func must be a callable that takes no arguments, or None to disable
the call. The atexit function will return the previous value set by this function, which is initially None.

Difference to CPython
This function is a MicroPython extension intended to provide similar functionality to the atexit module in
CPython.

sys.print_exception(exc, file=sys.stdout, / )
Print exception with a traceback to a file-like object file (or sys.stdout by default).

Difference to CPython
This is simplified version of a function which appears in the traceback module in CPython. Unlike
traceback.print_exception(), this function takes just exception value instead of exception type, ex-
ception value, and traceback object; file argument should be positional; further arguments are not supported.
CPython-compatible traceback module can be found in micropython-lib.

sys.settrace(tracefunc)
Enable tracing of bytecode execution. For details see the CPython documentation.
This function requires a custom MicroPython build as it is typically not present in pre-built firmware (due to it
affecting performance). The relevant configuration option is MICROPY_PY_SYS_SETTRACE.

42 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

sys.argv
A mutable list of arguments the current program was started with.
sys.byteorder
The byte order of the system ("little" or "big").
sys.implementation
Object with information about the current Python implementation. For MicroPython, it has following attributes:
• name - string “micropython”
• version - tuple (major, minor, micro), e.g. (1, 7, 0)
• _machine - string describing the underlying machine
• _mpy - supported mpy file-format version (optional attribute)
This object is the recommended way to distinguish MicroPython from other Python implementations (note that it
still may not exist in the very minimal ports).

Difference to CPython
CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPy-
thon.

sys.maxsize
Maximum value which a native integer type can hold on the current platform, or maximum value representable by
MicroPython integer type, if it’s smaller than platform max value (that is the case for MicroPython ports without
long int support).
This attribute is useful for detecting “bitness” of a platform (32-bit vs 64-bit, etc.). It’s recommended to not compare
this attribute to some value directly, but instead count number of bits in it:

bits = 0
v = sys.maxsize
while v:
bits += 1
v >>= 1
if bits > 32:
# 64-bit (or more) platform
...
else:
# 32-bit (or less) platform
# Note that on 32-bit platform, value of bits may be less than 32
# (e.g. 31) due to peculiarities described above, so use "> 16",
# "> 32", "> 64" style of comparisons.

sys.modules
Dictionary of loaded modules. On some ports, it may not include builtin modules.
sys.path
A mutable list of directories to search for imported modules.

Difference to CPython

1.1. Python standard libraries and micro-libraries 43


MicroPython Documentation, Release v1.22.0

On MicroPython, an entry with the value ".frozen" will indicate that import should search frozen modules at
that point in the search. If no frozen module is found then search will not look for a directory called .frozen,
instead it will continue with the next entry in sys.path.

sys.platform
The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g.
"linux". For baremetal ports it is an identifier of a board, e.g. "pyboard" for the original MicroPython
reference board. It thus can be used to distinguish one board from another. If you need to check whether your
program runs on MicroPython (vs other Python implementation), use sys.implementation instead.
sys.ps1
sys.ps2
Mutable attributes holding strings, which are used for the REPL prompt. The defaults give the standard Python
prompt of >>> and ....
sys.stderr
Standard error stream.
sys.stdin
Standard input stream.
sys.stdout
Standard output stream.
sys.tracebacklimit
A mutable attribute holding an integer value which is the maximum number of traceback entries to store in an
exception. Set to 0 to disable adding tracebacks. Defaults to 1000.
Note: this is not available on all ports.
sys.version
Python language version that this implementation conforms to, as a string.
sys.version_info
Python language version that this implementation conforms to, as a tuple of ints.

Difference to CPython
Only the first three version numbers (major, minor, micro) are supported and they can be referenced
only by index, not by name.

1.1.24 time – time related functions

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: time.
The time module provides functions for getting the current time and date, measuring time intervals, and for delays.
Time Epoch: Unix port uses standard for POSIX systems epoch of 1970-01-01 00:00:00 UTC. However, some embedded
ports use epoch of 2000-01-01 00:00:00 UTC. Epoch year may be determined with gmtime(0)[0].
Maintaining actual calendar date/time: This requires a Real Time Clock (RTC). On systems with underlying OS
(including some RTOS), an RTC may be implicit. Setting and maintaining actual calendar time is responsibility of
OS/RTOS and is done outside of MicroPython, it just uses OS API to query date/time. On baremetal ports however

44 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

system time depends on machine.RTC() object. The current calendar time may be set using machine.RTC().
datetime(tuple) function, and maintained by following means:
• By a backup battery (which may be an additional, optional component for a particular board).
• Using networked time protocol (requires setup by a port/user).
• Set manually by a user on each power-up (many boards then maintain RTC time across hard resets, though some
may require setting it again in such case).
If actual calendar time is not maintained with a system/MicroPython RTC, functions below which require reference to
current absolute time may behave not as expected.

Functions

time.gmtime([secs ])
time.localtime([secs ])
Convert the time secs expressed in seconds since the Epoch (see above) into an 8-tuple which contains: (year,
month, mday, hour, minute, second, weekday, yearday) If secs is not provided or None,
then the current time from the RTC is used.
The gmtime() function returns a date-time tuple in UTC, and localtime() returns a date-time tuple in local
time.
The format of the entries in the 8-tuple are:
• year includes the century (for example 2014).
• month is 1-12
• mday is 1-31
• hour is 0-23
• minute is 0-59
• second is 0-59
• weekday is 0-6 for Mon-Sun
• yearday is 1-366
time.mktime()
This is inverse function of localtime. It’s argument is a full 8-tuple which expresses a time as per localtime. It
returns an integer which is the number of seconds since Jan 1, 2000.
time.sleep(seconds)
Sleep for the given number of seconds. Some boards may accept seconds as a floating-point number to sleep for a
fractional number of seconds. Note that other boards may not accept a floating-point argument, for compatibility
with them use sleep_ms() and sleep_us() functions.
time.sleep_ms(ms)
Delay for given number of milliseconds, should be positive or 0.
This function will delay for at least the given number of milliseconds, but may take longer than that if other pro-
cessing must take place, for example interrupt handlers or other threads. Passing in 0 for ms will still allow this
other processing to occur. Use sleep_us() for more precise delays.

1.1. Python standard libraries and micro-libraries 45


MicroPython Documentation, Release v1.22.0

time.sleep_us(us)
Delay for given number of microseconds, should be positive or 0.
This function attempts to provide an accurate delay of at least us microseconds, but it may take longer if the system
has other higher priority processing to perform.
time.ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, that wraps around after some value.
The wrap-around value is not explicitly exposed, but we will refer to it as TICKS_MAX to simplify discussion.
Period of the values is TICKS_PERIOD = TICKS_MAX + 1. TICKS_PERIOD is guaranteed to be a power of two,
but otherwise may differ from port to port. The same period value is used for all of ticks_ms(), ticks_us(),
ticks_cpu() functions (for simplicity). Thus, these functions will return a value in range [0 .. TICKS_MAX],
inclusive, total TICKS_PERIOD values. Note that only non-negative values are used. For the most part, you should
treat values returned by these functions as opaque. The only operations available for them are ticks_diff()
and ticks_add() functions described below.
Note: Performing standard mathematical operations (+, -) or relational operators (<, <=, >, >=) directly on these
value will lead to invalid result. Performing mathematical operations and then passing their results as arguments to
ticks_diff() or ticks_add() will also lead to invalid results from the latter functions.
time.ticks_us()
Just like ticks_ms() above, but in microseconds.
time.ticks_cpu()
Similar to ticks_ms() and ticks_us(), but with the highest possible resolution in the system. This is usually
CPU clocks, and that’s why the function is named that way. But it doesn’t have to be a CPU clock, some other timing
source available in a system (e.g. high-resolution timer) can be used instead. The exact timing unit (resolution)
of this function is not specified on time module level, but documentation for a specific port may provide more
specific information. This function is intended for very fine benchmarking or very tight real-time loops. Avoid
using it in portable code.
Availability: Not every port implements this function.
time.ticks_add(ticks, delta)
Offset ticks value by a given number, which can be either positive or negative. Given a ticks value, this function
allows to calculate ticks value delta ticks before or after it, following modular-arithmetic definition of tick values
(see ticks_ms() above). ticks parameter must be a direct result of call to ticks_ms(), ticks_us(), or
ticks_cpu() functions (or from previous call to ticks_add()). However, delta can be an arbitrary integer
number or numeric expression. ticks_add() is useful for calculating deadlines for events/tasks. (Note: you
must use ticks_diff() function to work with deadlines.)
Examples:

# Find out what ticks value there was 100ms ago


print(ticks_add(time.ticks_ms(), -100))

# Calculate deadline for operation and test for it


deadline = ticks_add(time.ticks_ms(), 200)
while ticks_diff(deadline, time.ticks_ms()) > 0:
do_a_little_of_something()

# Find out TICKS_MAX used by this port


print(ticks_add(0, -1))

time.ticks_diff(ticks1, ticks2)
Measure ticks difference between values returned from ticks_ms(), ticks_us(), or ticks_cpu() func-
tions, as a signed value which may wrap around.

46 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

The argument order is the same as for subtraction operator, ticks_diff(ticks1, ticks2) has the same
meaning as ticks1 - ticks2. However, values returned by ticks_ms(), etc. functions may wrap around,
so directly using subtraction on them will produce incorrect result. That is why ticks_diff() is needed, it
implements modular (or more specifically, ring) arithmetic to produce correct result even for wrap-around val-
ues (as long as they not too distant in between, see below). The function returns signed value in the range [-
TICKS_PERIOD/2 .. TICKS_PERIOD/2-1] (that’s a typical range definition for two’s-complement signed binary
integers). If the result is negative, it means that ticks1 occurred earlier in time than ticks2. Otherwise, it means
that ticks1 occurred after ticks2. This holds only if ticks1 and ticks2 are apart from each other for no more than
TICKS_PERIOD/2-1 ticks. If that does not hold, incorrect result will be returned. Specifically, if two tick values
are apart for TICKS_PERIOD/2-1 ticks, that value will be returned by the function. However, if TICKS_PERIOD/2
of real-time ticks has passed between them, the function will return -TICKS_PERIOD/2 instead, i.e. result value
will wrap around to the negative range of possible values.
Informal rationale of the constraints above: Suppose you are locked in a room with no means to monitor passing
of time except a standard 12-notch clock. Then if you look at dial-plate now, and don’t look again for another 13
hours (e.g., if you fall for a long sleep), then once you finally look again, it may seem to you that only 1 hour has
passed. To avoid this mistake, just look at the clock regularly. Your application should do the same. “Too long
sleep” metaphor also maps directly to application behaviour: don’t let your application run any single task for too
long. Run tasks in steps, and do time-keeping in between.
ticks_diff() is designed to accommodate various usage patterns, among them:
• Polling with timeout. In this case, the order of events is known, and you will deal only with positive results
of ticks_diff():

# Wait for GPIO pin to be asserted, but at most 500us


start = time.ticks_us()
while pin.value() == 0:
if time.ticks_diff(time.ticks_us(), start) > 500:
raise TimeoutError

• Scheduling events. In this case, ticks_diff() result may be negative if an event is overdue:

# This code snippet is not optimized


now = time.ticks_ms()
scheduled_time = task.scheduled_time()
if ticks_diff(scheduled_time, now) > 0:
print("Too early, let's nap")
sleep_ms(ticks_diff(scheduled_time, now))
task.run()
elif ticks_diff(scheduled_time, now) == 0:
print("Right at time!")
task.run()
elif ticks_diff(scheduled_time, now) < 0:
print("Oops, running late, tell task to run faster!")
task.run(run_faster=true)

Note: Do not pass time() values to ticks_diff(), you should use normal mathematical operations on them.
But note that time() may (and will) also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_
problem .
time.time()
Returns the number of seconds, as an integer, since the Epoch, assuming that underlying RTC is set and maintained
as described above. If an RTC is not set, this function returns number of seconds since a port-specific reference
point in time (for embedded boards without a battery-backed RTC, usually since power up or reset). If you want to
develop portable MicroPython application, you should not rely on this function to provide higher than second pre-
cision. If you need higher precision, absolute timestamps, use time_ns(). If relative times are acceptable then

1.1. Python standard libraries and micro-libraries 47


MicroPython Documentation, Release v1.22.0

use the ticks_ms() and ticks_us() functions. If you need calendar time, gmtime() or localtime()
without an argument is a better choice.

Difference to CPython
In CPython, this function returns number of seconds since Unix epoch, 1970-01-01 00:00 UTC, as a floating-point,
usually having microsecond precision. With MicroPython, only Unix port uses the same Epoch, and if floating-point
precision allows, returns sub-second precision. Embedded hardware usually doesn’t have floating-point precision
to represent both long time ranges and subsecond precision, so they use integer value with second precision. Some
embedded hardware also lacks battery-powered RTC, so returns number of seconds since last power-up or from
other relative, hardware-specific point (e.g. reset).

time.time_ns()
Similar to time() but returns nanoseconds since the Epoch, as an integer (usually a big integer, so will allocate
on the heap).

1.1.25 zlib – zlib compression & decompression

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: zlib.
This module allows compression and decompression of binary data with the DEFLATE algorithm (commonly used in
the zlib library and gzip archiver).

Note: Prefer to use deflate.DeflateIO instead of the functions in this module as it provides a streaming interface
to compression and decompression which is convenient and more memory efficient when working with reading or writing
compressed data to a file, socket, or stream.

Availability:
• From MicroPython v1.21 onwards, this module may not be present by default on all MicroPython firmware as it
duplicates functionality available in the deflate module.
• A copy of this module can be installed (or frozen) from micropython-lib (source). See Package management for
more information. This documentation describes that module.
• Requires the built-in deflate module (available since MicroPython v1.21)
• Compression support will only be available if compression support is enabled in the built-in deflate module.

Functions

zlib.decompress(data, wbits=15, / )
Decompresses data into a bytes object.
The wbits parameter works the same way as for zlib.compress() with the following additional valid values:
• 0: Automatically determine the window size from the zlib header (data must be in zlib format).
• 35 to 47: Auto-detect either the zlib or gzip format.
As for zlib.compress(), see the CPython documentation for zlib for more information about the
wbits parameter. As for zlib.compress(), MicroPython also supports smaller window sizes than CPython.
See more MicroPython-specific details in the deflate module documentation.

48 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

If the data to be decompressed requires a larger window size, it will fail during decompression.
zlib.compress(data, wbits=15, / )
Compresses data into a bytes object.
wbits allows you to configure the DEFLATE dictionary window size and the output format. The window size allows
you to trade-off memory usage for compression level. A larger window size will allow the compressor to reference
fragments further back in the input. The output formats are “raw” DEFLATE (no header/footer), zlib, and gzip,
where the latter two include a header and checksum.
The low four bits of the absolute value of wbits set the base-2 logarithm of the DEFLATE dictionary window size.
So for example, wbits=10, wbits=-10, and wbits=26 all set the window size to 1024 bytes. Valid window
sizes are 5 to 15 inclusive (corresponding to 32 to 32k bytes).
Negative values of wbits between -5 and -15 correspond to “raw” output mode, positive values between 5 and
15 correspond to zlib output mode, and positive values between 21 and 31 correspond to gzip output mode.
See the CPython documentation for zlib for more information about the wbits parameter. Note that
MicroPython allows for smaller window sizes, which is useful when memory is constrained while still achieving a
reasonable level of compression. It also speeds up the compressor. See more MicroPython-specific details in the
deflate module documentation.

1.1.26 _thread – multithreading support

This module implements a subset of the corresponding CPython module, as described below. For more information, refer
to the original CPython documentation: _thread.
This module implements multithreading support.
This module is highly experimental and its API is not yet fully settled and not yet described in this documentation.

1.2 MicroPython-specific libraries

Functionality specific to the MicroPython implementation is available in the following libraries.

1.2.1 bluetooth — low-level Bluetooth

This module provides an interface to a Bluetooth controller on a board. Currently this supports Bluetooth Low Energy
(BLE) in Central, Peripheral, Broadcaster, and Observer roles, as well as GATT Server and Client and L2CAP connection-
oriented-channels. A device may operate in multiple roles concurrently. Pairing (and bonding) is supported on some ports.
This API is intended to match the low-level Bluetooth protocol and provide building-blocks for higher-level abstractions
such as specific device types.

Note: For most applications, we recommend using the higher-level aioble library.

Note: This module is still under development and its classes, functions, methods and constants are subject to change.

1.2. MicroPython-specific libraries 49


MicroPython Documentation, Release v1.22.0

class BLE

Constructor

class bluetooth.BLE
Returns the singleton BLE object.

Configuration

BLE.active([active, ]/ )
Optionally changes the active state of the BLE radio, and returns the current state.
The radio must be made active before using any other methods on this class.
BLE.config('param', / )
BLE.config(*, param=value, ...)
Get or set configuration values of the BLE interface. To get a value the parameter name should be quoted as a string,
and just one parameter is queried at a time. To set values use the keyword syntax, and one or more parameter can
be set at a time.
Currently supported values are:
• 'mac': The current address in use, depending on the current address mode. This returns a tuple of
(addr_type, addr).
See gatts_write for details about address type.
This may only be queried while the interface is currently active.
• 'addr_mode': Sets the address mode. Values can be:
– 0x00 - PUBLIC - Use the controller’s public address.
– 0x01 - RANDOM - Use a generated static address.
– 0x02 - RPA - Use resolvable private addresses.
– 0x03 - NRPA - Use non-resolvable private addresses.
By default the interface mode will use a PUBLIC address if available, otherwise it will use a RANDOM
address.
• 'gap_name': Get/set the GAP device name used by service 0x1800, characteristic 0x2a00. This can be
set at any time and changed multiple times.
• 'rxbuf': Get/set the size in bytes of the internal buffer used to store incoming events. This buffer is global
to the entire BLE driver and so handles incoming data for all events, including all characteristics. Increasing
this allows better handling of bursty incoming data (for example scan results) and the ability to receive larger
characteristic values.
• 'mtu': Get/set the MTU that will be used during a ATT MTU exchange. The resulting MTU will be the
minimum of this and the remote device’s MTU. ATT MTU exchange will not happen automatically (unless
the remote device initiates it), and must be manually initiated with gattc_exchange_mtu. Use the
_IRQ_MTU_EXCHANGED event to discover the MTU for a given connection.
• 'bond': Sets whether bonding will be enabled during pairing. When enabled, pairing requests will set the
“bond” flag and the keys will be stored by both devices.
• 'mitm': Sets whether MITM-protection is required for pairing.

50 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• 'io': Sets the I/O capabilities of this device.


Available options are:
_IO_CAPABILITY_DISPLAY_ONLY = const(0)
_IO_CAPABILITY_DISPLAY_YESNO = const(1)
_IO_CAPABILITY_KEYBOARD_ONLY = const(2)
_IO_CAPABILITY_NO_INPUT_OUTPUT = const(3)
_IO_CAPABILITY_KEYBOARD_DISPLAY = const(4)

• 'le_secure': Sets whether “LE Secure” pairing is required. Default is false (i.e. allow “Legacy Pairing”).

Event Handling

BLE.irq(handler, / )
Registers a callback for events from the BLE stack. The handler takes two arguments, event (which will be one
of the codes below) and data (which is an event-specific tuple of values).
Note: As an optimisation to prevent unnecessary allocations, the addr, adv_data, char_data, no-
tify_data, and uuid entries in the tuples are read-only memoryview instances pointing to bluetooth’s
internal ringbuffer, and are only valid during the invocation of the IRQ handler function. If your program needs to
save one of these values to access after the IRQ handler has returned (e.g. by saving it in a class instance or global
variable), then it needs to take a copy of the data, either by using bytes() or bluetooth.UUID(), like this:
connected_addr = bytes(addr) # equivalently: adv_data, char_data, or notify_data
matched_uuid = bluetooth.UUID(uuid)

For example, the IRQ handler for a scan result might inspect the adv_data to decide if it’s the correct device,
and only then copy the address data to be used elsewhere in the program. And to print data from within the IRQ
handler, print(bytes(addr)) will be needed.
An event handler showing all possible events:
def bt_irq(event, data):
if event == _IRQ_CENTRAL_CONNECT:
# A central has connected to this peripheral.
conn_handle, addr_type, addr = data
elif event == _IRQ_CENTRAL_DISCONNECT:
# A central has disconnected from this peripheral.
conn_handle, addr_type, addr = data
elif event == _IRQ_GATTS_WRITE:
# A client has written to this characteristic or descriptor.
conn_handle, attr_handle = data
elif event == _IRQ_GATTS_READ_REQUEST:
# A client has issued a read. Note: this is only supported on STM32.
# Return a non-zero integer to deny the read (see below), or zero (or␣
,→None)

# to accept the read.


conn_handle, attr_handle = data
elif event == _IRQ_SCAN_RESULT:
# A single scan result.
addr_type, addr, adv_type, rssi, adv_data = data
elif event == _IRQ_SCAN_DONE:
# Scan duration finished or manually stopped.
pass
elif event == _IRQ_PERIPHERAL_CONNECT:
# A successful gap_connect().
(continues on next page)

1.2. MicroPython-specific libraries 51


MicroPython Documentation, Release v1.22.0

(continued from previous page)


conn_handle, addr_type, addr = data
elif event == _IRQ_PERIPHERAL_DISCONNECT:
# Connected peripheral has disconnected.
conn_handle, addr_type, addr = data
elif event == _IRQ_GATTC_SERVICE_RESULT:
# Called for each service found by gattc_discover_services().
conn_handle, start_handle, end_handle, uuid = data
elif event == _IRQ_GATTC_SERVICE_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value␣
,→otherwise.

conn_handle, status = data


elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Called for each characteristic found by gattc_discover_services().
conn_handle, end_handle, value_handle, properties, uuid = data
elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value␣
,→otherwise.

conn_handle, status = data


elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
# Called for each descriptor found by gattc_discover_descriptors().
conn_handle, dsc_handle, uuid = data
elif event == _IRQ_GATTC_DESCRIPTOR_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value␣
,→otherwise.

conn_handle, status = data


elif event == _IRQ_GATTC_READ_RESULT:
# A gattc_read() has completed.
conn_handle, value_handle, char_data = data
elif event == _IRQ_GATTC_READ_DONE:
# A gattc_read() has completed.
# Note: Status will be zero on success, implementation-specific value␣
,→otherwise.

conn_handle, value_handle, status = data


elif event == _IRQ_GATTC_WRITE_DONE:
# A gattc_write() has completed.
# Note: Status will be zero on success, implementation-specific value␣
,→otherwise.

conn_handle, value_handle, status = data


elif event == _IRQ_GATTC_NOTIFY:
# A server has sent a notify request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTC_INDICATE:
# A server has sent an indicate request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTS_INDICATE_DONE:
# A client has acknowledged the indication.
# Note: Status will be zero on successful acknowledgment, implementation-
,→specific value otherwise.

conn_handle, value_handle, status = data


elif event == _IRQ_MTU_EXCHANGED:
# ATT MTU exchange complete (either initiated by us or the remote device).
conn_handle, mtu = data
elif event == _IRQ_L2CAP_ACCEPT:
# A new channel has been accepted.
(continues on next page)

52 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)


# Return a non-zero integer to reject the connection, or zero (or None)␣
,→to accept.

conn_handle, cid, psm, our_mtu, peer_mtu = data


elif event == _IRQ_L2CAP_CONNECT:
# A new channel is now connected (either as a result of connecting or␣
,→accepting).

conn_handle, cid, psm, our_mtu, peer_mtu = data


elif event == _IRQ_L2CAP_DISCONNECT:
# Existing channel has disconnected (status is zero), or a connection␣
,→attempt failed (non-zero status).

conn_handle, cid, psm, status = data


elif event == _IRQ_L2CAP_RECV:
# New data is available on the channel. Use l2cap_recvinto to read.
conn_handle, cid = data
elif event == _IRQ_L2CAP_SEND_READY:
# A previous l2cap_send that returned False has now completed and the␣
,→channel is ready to send again.

# If status is non-zero, then the transmit buffer overflowed and the␣


,→application should re-send the data.

conn_handle, cid, status = data


elif event == _IRQ_CONNECTION_UPDATE:
# The remote device has updated connection parameters.
conn_handle, conn_interval, conn_latency, supervision_timeout, status =␣
,→data

elif event == _IRQ_ENCRYPTION_UPDATE:


# The encryption state has changed (likely as a result of pairing or␣
,→bonding).

conn_handle, encrypted, authenticated, bonded, key_size = data


elif event == _IRQ_GET_SECRET:
# Return a stored secret.
# If key is None, return the index'th value of this sec_type.
# Otherwise return the corresponding value for this sec_type and key.
sec_type, index, key = data
return value
elif event == _IRQ_SET_SECRET:
# Save a secret to the store for this sec_type and key.
sec_type, key, value = data
return True
elif event == _IRQ_PASSKEY_ACTION:
# Respond to a passkey request during pairing.
# See gap_passkey() for details.
# action will be an action that is compatible with the configured "io"␣
,→config.

# passkey will be non-zero if action is "numeric comparison".


conn_handle, action, passkey = data

The event codes are:


from micropython import const
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
(continues on next page)

1.2. MicroPython-specific libraries 53


MicroPython Documentation, Release v1.22.0

(continued from previous page)


_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)
_IRQ_GATTS_INDICATE_DONE = const(20)
_IRQ_MTU_EXCHANGED = const(21)
_IRQ_L2CAP_ACCEPT = const(22)
_IRQ_L2CAP_CONNECT = const(23)
_IRQ_L2CAP_DISCONNECT = const(24)
_IRQ_L2CAP_RECV = const(25)
_IRQ_L2CAP_SEND_READY = const(26)
_IRQ_CONNECTION_UPDATE = const(27)
_IRQ_ENCRYPTION_UPDATE = const(28)
_IRQ_GET_SECRET = const(29)
_IRQ_SET_SECRET = const(30)

For the _IRQ_GATTS_READ_REQUEST event, the available return codes are:

_GATTS_NO_ERROR = const(0x00)
_GATTS_ERROR_READ_NOT_PERMITTED = const(0x02)
_GATTS_ERROR_WRITE_NOT_PERMITTED = const(0x03)
_GATTS_ERROR_INSUFFICIENT_AUTHENTICATION = const(0x05)
_GATTS_ERROR_INSUFFICIENT_AUTHORIZATION = const(0x08)
_GATTS_ERROR_INSUFFICIENT_ENCRYPTION = const(0x0f)

For the _IRQ_PASSKEY_ACTION event, the available actions are:

_PASSKEY_ACTION_NONE = const(0)
_PASSKEY_ACTION_INPUT = const(2)
_PASSKEY_ACTION_DISPLAY = const(3)
_PASSKEY_ACTION_NUMERIC_COMPARISON = const(4)

In order to save space in the firmware, these constants are not included on the bluetooth module. Add the ones that
you need from the list above to your program.

Broadcaster Role (Advertiser)

BLE.gap_advertise(interval_us, adv_data=None, *, resp_data=None, connectable=True)


Starts advertising at the specified interval (in microseconds). This interval will be rounded down to the nearest
625us. To stop advertising, set interval_us to None.
adv_data and resp_data can be any type that implements the buffer protocol (e.g. bytes, bytearray, str).
adv_data is included in all broadcasts, and resp_data is send in reply to an active scan.
Note: if adv_data (or resp_data) is None, then the data passed to the previous call to gap_advertise will
be re-used. This allows a broadcaster to resume advertising with just gap_advertise(interval_us). To
clear the advertising payload pass an empty bytes, i.e. b''.

54 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Observer Role (Scanner)

BLE.gap_scan(duration_ms, interval_us=1280000, window_us=11250, active=False, / )


Run a scan operation lasting for the specified duration (in milliseconds).
To scan indefinitely, set duration_ms to 0.
To stop scanning, set duration_ms to None.
Use interval_us and window_us to optionally configure the duty cycle. The scanner will run for window_us mi-
croseconds every interval_us microseconds for a total of duration_ms milliseconds. The default interval and win-
dow are 1.28 seconds and 11.25 milliseconds respectively (background scanning).
For each scan result the _IRQ_SCAN_RESULT event will be raised, with event data (addr_type, addr,
adv_type, rssi, adv_data).
addr_type values indicate public or random addresses:
• 0x00 - PUBLIC
• 0x01 - RANDOM (either static, RPA, or NRPA, the type is encoded in the address itself)
adv_type values correspond to the Bluetooth Specification:
• 0x00 - ADV_IND - connectable and scannable undirected advertising
• 0x01 - ADV_DIRECT_IND - connectable directed advertising
• 0x02 - ADV_SCAN_IND - scannable undirected advertising
• 0x03 - ADV_NONCONN_IND - non-connectable undirected advertising
• 0x04 - SCAN_RSP - scan response
active can be set True if you want to receive scan responses in the results.
When scanning is stopped (either due to the duration finishing or when explicitly stopped), the _IRQ_SCAN_DONE
event will be raised.

Central Role

A central device can connect to peripherals that it has discovered using the observer role (see gap_scan) or with a
known address.
BLE.gap_connect(addr_type, addr, scan_duration_ms=2000, min_conn_interval_us=None,
max_conn_interval_us=None, / )
Connect to a peripheral.
See gap_scan for details about address types.
To cancel an outstanding connection attempt early, call gap_connect(None).
On success, the _IRQ_PERIPHERAL_CONNECT event will be raised. If cancelling a connection attempt, the
_IRQ_PERIPHERAL_DISCONNECT event will be raised.
The device will wait up to scan_duration_ms to receive an advertising payload from the device.
The connection interval can be configured in microseconds using either or both of min_conn_interval_us and
max_conn_interval_us. Otherwise a default interval will be chosen, typically between 30000 and 50000 microsec-
onds. A shorter interval will increase throughput, at the expense of power usage.

1.2. MicroPython-specific libraries 55


MicroPython Documentation, Release v1.22.0

Peripheral Role

A peripheral device is expected to send connectable advertisements (see gap_advertise). It will usually be acting as
a GATT server, having first registered services and characteristics using gatts_register_services.
When a central connects, the _IRQ_CENTRAL_CONNECT event will be raised.

Central & Peripheral Roles

BLE.gap_disconnect(conn_handle, / )
Disconnect the specified connection handle. This can either be a central that has connected to this device (if acting
as a peripheral) or a peripheral that was previously connected to by this device (if acting as a central).
On success, the _IRQ_PERIPHERAL_DISCONNECT or _IRQ_CENTRAL_DISCONNECT event will be raised.
Returns False if the connection handle wasn’t connected, and True otherwise.

GATT Server

A GATT server has a set of registered services. Each service may contain characteristics, which each have a value.
Characteristics can also contain descriptors, which themselves have values.
These values are stored locally, and are accessed by their “value handle” which is generated during service registration.
They can also be read from or written to by a remote client device. Additionally, a server can “notify” a characteristic to
a connected client via a connection handle.
A device in either central or peripheral roles may function as a GATT server, however in most cases it will be more
common for a peripheral device to act as the server.
Characteristics and descriptors have a default maximum size of 20 bytes. Anything written to them by a client will be
truncated to this length. However, any local write will increase the maximum size, so if you want to allow larger writes
from a client to a given characteristic, use gatts_write after registration. e.g. gatts_write(char_handle,
bytes(100)).
BLE.gatts_register_services(services_definition, / )
Configures the server with the specified services, replacing any existing services.
services_definition is a list of services, where each service is a two-element tuple containing a UUID and a list of
characteristics.
Each characteristic is a two-or-three-element tuple containing a UUID, a flags value, and optionally a list of
descriptors.
Each descriptor is a two-element tuple containing a UUID and a flags value.
The flags are a bitwise-OR combination of the flags defined below. These set both the behaviour of the characteristic
(or descriptor) as well as the security and privacy requirements.
The return value is a list (one element per service) of tuples (each element is a value handle). Characteristics and
descriptor handles are flattened into the same tuple, in the order that they are defined.
The following example registers two services (Heart Rate, and Nordic UART):

HR_UUID = bluetooth.UUID(0x180D)
HR_CHAR = (bluetooth.UUID(0x2A37), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
HR_SERVICE = (HR_UUID, (HR_CHAR,),)
UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_
(continues on next page)

56 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)


,→READ | bluetooth.FLAG_NOTIFY,)
UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_
,→WRITE,)

UART_SERVICE = (UART_UUID, (UART_TX, UART_RX,),)


SERVICES = (HR_SERVICE, UART_SERVICE,)
( (hr,), (tx, rx,), ) = bt.gatts_register_services(SERVICES)

The three value handles (hr, tx, rx) can be used with gatts_read, gatts_write, gatts_notify, and
gatts_indicate.
Note: Advertising must be stopped before registering services.
Available flags for characteristics and descriptors are:

from micropython import const


_FLAG_BROADCAST = const(0x0001)
_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)
_FLAG_INDICATE = const(0x0020)
_FLAG_AUTHENTICATED_SIGNED_WRITE = const(0x0040)

_FLAG_AUX_WRITE = const(0x0100)
_FLAG_READ_ENCRYPTED = const(0x0200)
_FLAG_READ_AUTHENTICATED = const(0x0400)
_FLAG_READ_AUTHORIZED = const(0x0800)
_FLAG_WRITE_ENCRYPTED = const(0x1000)
_FLAG_WRITE_AUTHENTICATED = const(0x2000)
_FLAG_WRITE_AUTHORIZED = const(0x4000)

As for the IRQs above, any required constants should be added to your Python code.
BLE.gatts_read(value_handle, / )
Reads the local value for this handle (which has either been written by gatts_write or by a remote client).
BLE.gatts_write(value_handle, data, send_update=False, / )
Writes the local value for this handle, which can be read by a client.
If send_update is True, then any subscribed clients will be notified (or indicated, depending on what they’re
subscribed to and which operations the characteristic supports) about this write.
BLE.gatts_notify(conn_handle, value_handle, data=None, / )
Sends a notification request to a connected client.
If data is None (the default), then the current local value (as set with gatts_write) will be sent.
Otherwise, if data is not None, then that value is sent to the client as part of the notification. The local value will
not be modified.
Note: The notification will be sent regardless of the subscription status of the client to this characteristic.
BLE.gatts_indicate(conn_handle, value_handle, data=None, / )
Sends a indication request to a connected client.
If data is None (the default), then the current local value (as set with gatts_write) will be sent.
Otherwise, if data is not None, then that value is sent to the client as part of the indication. The local value will
not be modified.

1.2. MicroPython-specific libraries 57


MicroPython Documentation, Release v1.22.0

On acknowledgment (or failure, e.g. timeout), the _IRQ_GATTS_INDICATE_DONE event will be raised.
Note: The indication will be sent regardless of the subscription status of the client to this characteristic.
BLE.gatts_set_buffer(value_handle, len, append=False, / )
Sets the internal buffer size for a value in bytes. This will limit the largest possible write that can be received. The
default is 20.
Setting append to True will make all remote writes append to, rather than replace, the current value. At most
len bytes can be buffered in this way. When you use gatts_read, the value will be cleared after reading. This
feature is useful when implementing something like the Nordic UART Service.

GATT Client

A GATT client can discover and read/write characteristics on a remote GATT server.
It is more common for a central role device to act as the GATT client, however it’s also possible for a peripheral to act as
a client in order to discover information about the central that has connected to it (e.g. to read the device name from the
device information service).
BLE.gattc_discover_services(conn_handle, uuid=None, / )
Query a connected server for its services.
Optionally specify a service uuid to query for that service only.
For each service discovered, the _IRQ_GATTC_SERVICE_RESULT event will be raised, followed by
_IRQ_GATTC_SERVICE_DONE on completion.
BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle, uuid=None, / )
Query a connected server for characteristics in the specified range.
Optionally specify a characteristic uuid to query for that characteristic only.
You can use start_handle=1, end_handle=0xffff to search for a characteristic in any service.
For each characteristic discovered, the _IRQ_GATTC_CHARACTERISTIC_RESULT event will be raised, fol-
lowed by _IRQ_GATTC_CHARACTERISTIC_DONE on completion.
BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle, / )
Query a connected server for descriptors in the specified range.
For each descriptor discovered, the _IRQ_GATTC_DESCRIPTOR_RESULT event will be raised, followed by
_IRQ_GATTC_DESCRIPTOR_DONE on completion.
BLE.gattc_read(conn_handle, value_handle, / )
Issue a remote read to a connected server for the specified characteristic or descriptor handle.
When a value is available, the _IRQ_GATTC_READ_RESULT event will be raised. Additionally, the
_IRQ_GATTC_READ_DONE will be raised.
BLE.gattc_write(conn_handle, value_handle, data, mode=0, / )
Issue a remote write to a connected server for the specified characteristic or descriptor handle.
The argument mode specifies the write behaviour, with the currently supported values being:
• mode=0 (default) is a write-without-response: the write will be sent to the remote server but no confirmation
will be returned, and no event will be raised.
• mode=1 is a write-with-response: the remote server is requested to send a response/acknowledgement that
it received the data.
If a response is received from the remote server the _IRQ_GATTC_WRITE_DONE event will be raised.

58 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

BLE.gattc_exchange_mtu(conn_handle, / )
Initiate MTU exchange with a connected server, using the preferred MTU set using BLE.
config(mtu=value).
The _IRQ_MTU_EXCHANGED event will be raised when MTU exchange completes.
Note: MTU exchange is typically initiated by the central. When using the BlueKitchen stack in the central role, it
does not support a remote peripheral initiating the MTU exchange. NimBLE works for both roles.

L2CAP connection-oriented-channels

This feature allows for socket-like data exchange between two BLE devices. Once the devices are connected
via GAP, either device can listen for the other to connect on a numeric PSM (Protocol/Service Multiplexer).
Note: This is currently only supported when using the NimBLE stack on STM32 and Unix (not ESP32).
Only one L2CAP channel may be active at a given time (i.e. you cannot connect while listening).
Active L2CAP channels are identified by the connection handle that they were established on and a CID
(channel ID).
Connection-oriented channels have built-in credit-based flow control. Unlike ATT, where devices negoti-
ate a shared MTU, both the listening and connecting devices each set an independent MTU which limits
the maximum amount of outstanding data that the remote device can send before it is fully consumed in
l2cap_recvinto.
BLE.l2cap_listen(psm, mtu, / )
Start listening for incoming L2CAP channel requests on the specified psm with the local MTU set to mtu.
When a remote device initiates a connection, the _IRQ_L2CAP_ACCEPT event will be raised, which gives the
listening server a chance to reject the incoming connection (by returning a non-zero integer).
Once the connection is accepted, the _IRQ_L2CAP_CONNECT event will be raised, allowing the server to obtain
the channel id (CID) and the local and remote MTU.
Note: It is not currently possible to stop listening.
BLE.l2cap_connect(conn_handle, psm, mtu, / )
Connect to a listening peer on the specified psm with local MTU set to mtu.
On successful connection, the the _IRQ_L2CAP_CONNECT event will be raised, allowing the client to obtain the
CID and the local and remote (peer) MTU.
An unsuccessful connection will raise the _IRQ_L2CAP_DISCONNECT event with a non-zero status.
BLE.l2cap_disconnect(conn_handle, cid, / )
Disconnect an active L2CAP channel with the specified conn_handle and cid.
BLE.l2cap_send(conn_handle, cid, buf, / )
Send the specified buf (which must support the buffer protocol) on the L2CAP channel identified by conn_handle
and cid.
The specified buffer cannot be larger than the remote (peer) MTU, and no more than twice the size of the local
MTU.
This will return False if the channel is now “stalled”, which means that l2cap_send must not be called again
until the _IRQ_L2CAP_SEND_READY event is received (which will happen when the remote device grants more
credits, typically after it has received and processed the data).

1.2. MicroPython-specific libraries 59


MicroPython Documentation, Release v1.22.0

BLE.l2cap_recvinto(conn_handle, cid, buf, / )


Receive data from the specified conn_handle and cid into the provided buf (which must support the buffer protocol,
e.g. bytearray or memoryview).
Returns the number of bytes read from the channel.
If buf is None, then returns the number of bytes available.
Note: After receiving the _IRQ_L2CAP_RECV event, the application should continue calling
l2cap_recvinto until no more bytes are available in the receive buffer (typically up to the size of the
remote (peer) MTU).
Until the receive buffer is empty, the remote device will not be granted more channel credits and will be unable to
send any more data.

Pairing and bonding

Pairing allows a connection to be encrypted and authenticated via exchange of secrets (with optional MITM
protection via passkey authentication).
Bonding is the process of storing those secrets into non-volatile storage. When bonded, a device is able to re-
solve a resolvable private address (RPA) from another device based on the stored identity resolving key (IRK).
To support bonding, an application must implement the _IRQ_GET_SECRET and _IRQ_SET_SECRET
events.
Note: This is currently only supported when using the NimBLE stack on STM32 and Unix (not ESP32).
BLE.gap_pair(conn_handle, / )
Initiate pairing with the remote device.
Before calling this, ensure that the io, mitm, le_secure, and bond configuration options are set (via config).
On successful pairing, the _IRQ_ENCRYPTION_UPDATE event will be raised.
BLE.gap_passkey(conn_handle, action, passkey, / )
Respond to a _IRQ_PASSKEY_ACTION event for the specified conn_handle and action.
The passkey is a numeric value and will depend on on the action (which will depend on what I/O capability has
been set):
• When the action is _PASSKEY_ACTION_INPUT, then the application should prompt the user to enter the
passkey that is shown on the remote device.
• When the action is _PASSKEY_ACTION_DISPLAY, then the application should generate a random 6-digit
passkey and show it to the user.
• When the action is _PASSKEY_ACTION_NUMERIC_COMPARISON, then the application should show the
passkey that was provided in the _IRQ_PASSKEY_ACTION event and then respond with either 0 (cancel
pairing), or 1 (accept pairing).

60 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class UUID

Constructor

class bluetooth.UUID(value, / )
Creates a UUID instance with the specified value.
The value can be either:
• A 16-bit integer. e.g. 0x2908.
• A 128-bit UUID string. e.g. '6E400001-B5A3-F393-E0A9-E50E24DCCA9E'.

1.2.2 btree – simple BTree database

The btree module implements a simple key-value database using external storage (disk files, or in general case, a
random-access stream). Keys are stored sorted in the database, and besides efficient retrieval by a key value, a database
also supports efficient ordered range scans (retrieval of values with the keys in a given range). On the application interface
side, BTree database work as close a possible to a way standard dict type works, one notable difference is that both keys
and values must be bytes-like objects (so, if you want to store objects of other types, you need to first serialize them to
str or bytes or another type that supports the buffer protocol).
The module is based on the well-known BerkelyDB library, version 1.xx.
Example:

import btree

# First, we need to open a stream which holds a database


# This is usually a file, but can be in-memory database
# using io.BytesIO, a raw flash partition, etc.
# Oftentimes, you want to create a database file if it doesn't
# exist and open if it exists. Idiom below takes care of this.
# DO NOT open database with "a+b" access mode.
try:
f = open("mydb", "r+b")
except OSError:
f = open("mydb", "w+b")

# Now open a database itself


db = btree.open(f)

# The keys you add will be sorted internally in the database


db[b"3"] = b"three"
db[b"1"] = b"one"
db[b"2"] = b"two"

# Assume that any changes are cached in memory unless


# explicitly flushed (or database closed). Flush database
# at the end of each "transaction".
db.flush()

# Prints b'two'
print(db[b"2"])

# Iterate over sorted keys in the database, starting from b"2"


# until the end of the database, returning only values.
(continues on next page)

1.2. MicroPython-specific libraries 61


MicroPython Documentation, Release v1.22.0

(continued from previous page)


# Mind that arguments passed to values() method are *key* values.
# Prints:
# b'two'
# b'three'
for word in db.values(b"2"):
print(word)

del db[b"2"]

# No longer true, prints False


print(b"2" in db)

# Prints:
# b"1"
# b"3"
for key in db:
print(key)

db.close()

# Don't forget to close the underlying stream!


f.close()

Functions

btree.open(stream, *, flags=0, pagesize=0, cachesize=0, minkeypage=0)


Open a database from a random-access stream (like an open file). All other parameters are optional and keyword-
only, and allow to tweak advanced parameters of the database operation (most users will not need them):
• flags - Currently unused.
• pagesize - Page size used for the nodes in BTree. Acceptable range is 512-65536. If 0, a port-specific default
will be used, optimized for port’s memory usage and/or performance.
• cachesize - Suggested memory cache size in bytes. For a board with enough memory using larger values may
improve performance. Cache policy is as follows: entire cache is not allocated at once; instead, accessing a
new page in database will allocate a memory buffer for it, until value specified by cachesize is reached. Then,
these buffers will be managed using LRU (least recently used) policy. More buffers may still be allocated if
needed (e.g., if a database contains big keys and/or values). Allocated cache buffers aren’t reclaimed.
• minkeypage - Minimum number of keys to store per page. Default value of 0 equivalent to 2.
Returns a BTree object, which implements a dictionary protocol (set of methods), and some additional methods
described below.

Methods

btree.close()
Close the database. It’s mandatory to close the database at the end of processing, as some unwritten data may be
still in the cache. Note that this does not close underlying stream with which the database was opened, it should be
closed separately (which is also mandatory to make sure that data flushed from buffer to the underlying storage).
btree.flush()
Flush any data in cache to the underlying stream.

62 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

btree.__getitem__(key)
btree.get(key, default=None, / )
btree.__setitem__(key, val)
btree.__delitem__(key)
btree.__contains__(key)
Standard dictionary methods.
btree.__iter__()
A BTree object can be iterated over directly (similar to a dictionary) to get access to all keys in order.
btree.keys([start_key[, end_key[, flags ]]])
btree.values([start_key[, end_key[, flags ]]])
btree.items([start_key[, end_key[, flags ]]])
These methods are similar to standard dictionary methods, but also can take optional parameters to iterate over
a key sub-range, instead of the entire database. Note that for all 3 methods, start_key and end_key arguments
represent key values. For example, values() method will iterate over values corresponding to they key range
given. None values for start_key means “from the first key”, no end_key or its value of None means “until the end of
database”. By default, range is inclusive of start_key and exclusive of end_key, you can include end_key in iteration
by passing flags of btree.INCL. You can iterate in descending key direction by passing flags of btree.DESC.
The flags values can be ORed together.

Constants

btree.INCL
A flag for keys(), values(), items() methods to specify that scanning should be inclusive of the end key.
btree.DESC
A flag for keys(), values(), items() methods to specify that scanning should be in descending direction
of keys.

1.2.3 cryptolib – cryptographic ciphers

Classes

class cryptolib.aes

classmethod __init__(key, mode[, IV ])


Initialize cipher object, suitable for encryption/decryption. Note: after initialization, cipher object can be
use only either for encryption or decryption. Running decrypt() operation after encrypt() or vice versa is not
supported.
Parameters are:
• key is an encryption/decryption key (bytes-like).
• mode is:
– 1 (or cryptolib.MODE_ECB if it exists) for Electronic Code Book (ECB).
– 2 (or cryptolib.MODE_CBC if it exists) for Cipher Block Chaining (CBC).
– 6 (or cryptolib.MODE_CTR if it exists) for Counter mode (CTR).
• IV is an initialization vector for CBC mode.

1.2. MicroPython-specific libraries 63


MicroPython Documentation, Release v1.22.0

• For Counter mode, IV is the initial value for the counter.


encrypt(in_buf [, out_buf ])
Encrypt in_buf. If no out_buf is given result is returned as a newly allocated bytes object. Otherwise, result
is written into mutable buffer out_buf. in_buf and out_buf can also refer to the same mutable buffer, in which
case data is encrypted in-place.
decrypt(in_buf [, out_buf ])
Like encrypt(), but for decryption.

1.2.4 deflate – deflate compression & decompression

This module allows compression and decompression of binary data with the DEFLATE algorithm (commonly used in
the zlib library and gzip archiver).
Availability:
• Added in MicroPython v1.21.
• Decompression: Enabled via the MICROPY_PY_DEFLATE build option, on by default on ports with the “extra
features” level or higher (which is most boards).
• Compression: Enabled via the MICROPY_PY_DEFLATE_COMPRESS build option, on by default on ports with
the “full features” level or higher (generally this means you need to build your own firmware to enable this).

Classes

class deflate.DeflateIO(stream, format=AUTO, wbits=0, close=False, / )


This class can be used to wrap a stream which is any stream-like object such as a file, socket, or stream (including
io.BytesIO). It is itself a stream and implements the standard read/readinto/write/close methods.
The stream must be a blocking stream. Non-blocking streams are currently not supported.
The format can be set to any of the constants defined below, and defaults to AUTO which for decompressing will
auto-detect gzip or zlib streams, and for compressing it will generate a raw stream.
The wbits parameter sets the base-2 logarithm of the DEFLATE dictionary window size. So for example, setting
wbits to 10 sets the window size to 1024 bytes. Valid values are 5 to 15 inclusive (corresponding to window sizes
of 32 to 32k bytes).
If wbits is set to 0 (the default), then for compression a window size of 256 bytes will be used (as if wbits was set
to 8). For decompression, it depends on the format:
• RAW will use 256 bytes (corresponding to wbits set to 8).
• ZLIB (or AUTO with zlib detected) will use the value from the zlib header.
• GZIP (or AUTO with gzip detected) will use 32 kilobytes (corresponding to wbits set to 15).
See the window size notes below for more information about the window size, zlib, and gzip streams.
If close is set to True then the underlying stream will be closed automatically when the deflate.DeflateIO
stream is closed. This is useful if you want to return a deflate.DeflateIO stream that wraps another stream
and not have the caller need to know about managing the underlying stream.
If compression is enabled, a given deflate.DeflateIO instance supports both reading and writing. For
example, a bidirectional stream like a socket can be wrapped, which allows for compression/decompression in
both directions.

64 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

deflate.AUTO
deflate.RAW
deflate.ZLIB
deflate.GZIP
Supported values for the format parameter.

Examples

A typical use case for deflate.DeflateIO is to read or write a compressed file from storage:
import deflate

# Writing a zlib-compressed stream (uses the default window size of 256 bytes).
with open("data.gz", "wb") as f:
with deflate.DeflateIO(f, deflate.ZLIB) as d:
# Use d.write(...) etc

# Reading a zlib-compressed stream (auto-detect window size).


with open("data.z", "rb") as f:
with deflate.DeflateIO(f, deflate.ZLIB) as d:
# Use d.read(), d.readinto(), etc.

Because deflate.DeflateIO is a stream, it can be used for example with json.dump() and json.load()
(and any other places streams can be used):
import deflate, json

# Write a dictionary as JSON in gzip format, with a


# small (64 byte) window size.
config = { ... }
with open("config.gz", "wb") as f:
with deflate.DeflateIO(f, deflate.GZIP, 6) as f:
json.dump(config, f)

# Read back that dictionary.


with open("config.gz", "rb") as f:
with deflate.DeflateIO(f, deflate.GZIP, 6) as f:
config = json.load(f)

If your source data is not in a stream format, you can use io.BytesIO to turn it into a stream suitable for use with
deflate.DeflateIO:
import deflate, io

# Decompress a bytes/bytearray value.


compressed_data = get_data_z()
with deflate.DeflateIO(io.BytesIO(compressed_data), deflate.ZLIB) as d:
decompressed_data = d.read()

# Compress a bytes/bytearray value.


uncompressed_data = get_data()
stream = io.BytesIO()
with deflate.DeflateIO(stream, deflate.ZLIB) as d:
(continues on next page)

1.2. MicroPython-specific libraries 65


MicroPython Documentation, Release v1.22.0

(continued from previous page)


d.write(uncompressed_data)
compressed_data = stream.getvalue()

Deflate window size

The window size limits how far back in the stream the (de)compressor can reference. Increasing the window size will
improve compression, but will require more memory and make the compressor slower.
If an input stream was compressed a given window size, then DeflateIO using a smaller window size will fail mid-way
during decompression with OSError, but only if a back-reference actually refers back further than the decompressor’s
window size. This means it may be possible to decompress with a smaller window size. For example, this would trivially
be the case if the original uncompressed data is shorter than the window size.

Decompression

The zlib format includes a header which specifies the window size that was used to compress the data. This indicates the
maximum window size required to decompress this stream. If this header value is less than the specified wbits value (or
if wbits is unset), then the header value will be used.
The gzip format does not include the window size in the header, and assumes that all gzip compressors (e.g. the gzip
utility, or CPython’s implementation of gzip.GzipFile) use the maximum window size of 32kiB. For this reason, if
the wbits parameter is not set, the decompressor will use a 32 kiB window size (corresponding to wbits set to 15). This
means that to be able to decompress an arbitrary gzip stream, you must have at least this much RAM available. If you
control the source data, consider instead using the zlib format with a smaller window size.
The raw format has no header and therefore does not include any information about the window size. If wbits is not set,
then it will default to a window size of 256 bytes, which may not be large enough for a given stream. Therefore it is
recommended that you should always explicitly set wbits if using the raw format.

Compression

For compression, MicroPython will default to a window size of 256 bytes for all formats. This provides a reasonable
amount of compression with minimal memory usage and fast compression time, and will generate output that will work
with any decompressor.

1.2.5 framebuf — frame buffer manipulation

This module provides a general frame buffer which can be used to create bitmap images, which can then be sent to a
display.

66 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class FrameBuffer

The FrameBuffer class provides a pixel buffer which can be drawn upon with pixels, lines, rectangles, ellipses, polygons,
text and even other FrameBuffers. It is useful when generating output for displays.
For example:

import framebuf

# FrameBuffer needs 2 bytes for every RGB565 pixel


fbuf = framebuf.FrameBuffer(bytearray(100 * 10 * 2), 100, 10, framebuf.RGB565)

fbuf.fill(0)
fbuf.text('MicroPython!', 0, 0, 0xffff)
fbuf.hline(0, 9, 96, 0xffff)

Constructors

class framebuf.FrameBuffer(buffer, width, height, format, stride=width, / )


Construct a FrameBuffer object. The parameters are:
• buffer is an object with a buffer protocol which must be large enough to contain every pixel defined by the
width, height and format of the FrameBuffer.
• width is the width of the FrameBuffer in pixels
• height is the height of the FrameBuffer in pixels
• format specifies the type of pixel used in the FrameBuffer; permissible values are listed under Constants
below. These set the number of bits used to encode a color value and the layout of these bits in buffer. Where
a color value c is passed to a method, c is a small integer with an encoding that is dependent on the format of
the FrameBuffer.
• stride is the number of pixels between each horizontal line of pixels in the FrameBuffer. This defaults to width
but may need adjustments when implementing a FrameBuffer within another larger FrameBuffer or screen.
The buffer size must accommodate an increased step size.
One must specify valid buffer, width, height, format and optionally stride. Invalid buffer size or dimensions may
lead to unexpected errors.

Drawing primitive shapes

The following methods draw shapes onto the FrameBuffer.


FrameBuffer.fill(c)
Fill the entire FrameBuffer with the specified color.
FrameBuffer.pixel(x, y[, c ])
If c is not given, get the color value of the specified pixel. If c is given, set the specified pixel to the given color.
FrameBuffer.hline(x, y, w, c)

FrameBuffer.vline(x, y, h, c)

1.2. MicroPython-specific libraries 67


MicroPython Documentation, Release v1.22.0

FrameBuffer.line(x1, y1, x2, y2, c)


Draw a line from a set of coordinates using the given color and a thickness of 1 pixel. The line method draws
the line up to a second set of coordinates whereas the hline and vline methods draw horizontal and vertical
lines respectively up to a given length.
FrameBuffer.rect(x, y, w, h, c[, f ])
Draw a rectangle at the given location, size and color.
The optional f parameter can be set to True to fill the rectangle. Otherwise just a one pixel outline is drawn.
FrameBuffer.ellipse(x, y, xr, yr, c[, f, m ])
Draw an ellipse at the given location. Radii xr and yr define the geometry; equal values cause a circle to be drawn.
The c parameter defines the color.
The optional f parameter can be set to True to fill the ellipse. Otherwise just a one pixel outline is drawn.
The optional m parameter enables drawing to be restricted to certain quadrants of the ellipse. The LS four bits
determine which quadrants are to be drawn, with bit 0 specifying Q1, b1 Q2, b2 Q3 and b3 Q4. Quadrants are
numbered counterclockwise with Q1 being top right.
FrameBuffer.poly(x, y, coords, c[, f ])
Given a list of coordinates, draw an arbitrary (convex or concave) closed polygon at the given x, y location using
the given color.
The coords must be specified as a array of integers, e.g. array('h', [x0, y0, x1, y1, ... xn,
yn]).
The optional f parameter can be set to True to fill the polygon. Otherwise just a one pixel outline is drawn.

Drawing text

FrameBuffer.text(s, x, y[, c ])
Write text to the FrameBuffer using the the coordinates as the upper-left corner of the text. The color of the text
can be defined by the optional argument but is otherwise a default value of 1. All characters have dimensions of
8x8 pixels and there is currently no way to change the font.

Other methods

FrameBuffer.scroll(xstep, ystep)
Shift the contents of the FrameBuffer by the given vector. This may leave a footprint of the previous colors in the
FrameBuffer.
FrameBuffer.blit(fbuf, x, y, key=-1, palette=None)
Draw another FrameBuffer on top of the current one at the given coordinates. If key is specified then it should be a
color integer and the corresponding color will be considered transparent: all pixels with that color value will not be
drawn. (If the palette is specified then the key is compared to the value from palette, not to the value directly from
fbuf.)
The palette argument enables blitting between FrameBuffers with differing formats. Typical usage is to render a
monochrome or grayscale glyph/icon to a color display. The palette is a FrameBuffer instance whose format is that
of the current FrameBuffer. The palette height is one pixel and its pixel width is the number of colors in the source
FrameBuffer. The palette for an N-bit source needs 2**N pixels; the palette for a monochrome source would have
2 pixels representing background and foreground colors. The application assigns a color to each pixel in the palette.
The color of the current pixel will be that of that palette pixel whose x position is the color of the corresponding
source pixel.

68 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

framebuf.MONO_VLSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are vertically mapped with bit 0
being nearest the top of the screen. Consequently each byte occupies 8 vertical pixels. Subsequent bytes appear at
successive horizontal locations until the rightmost edge is reached. Further bytes are rendered at locations starting
at the leftmost edge, 8 pixels lower.
framebuf.MONO_HLSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are horizontally mapped. Each
byte occupies 8 horizontal pixels with bit 7 being the leftmost. Subsequent bytes appear at successive horizontal
locations until the rightmost edge is reached. Further bytes are rendered on the next row, one pixel lower.
framebuf.MONO_HMSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are horizontally mapped. Each
byte occupies 8 horizontal pixels with bit 0 being the leftmost. Subsequent bytes appear at successive horizontal
locations until the rightmost edge is reached. Further bytes are rendered on the next row, one pixel lower.
framebuf.RGB565
Red Green Blue (16-bit, 5+6+5) color format
framebuf.GS2_HMSB
Grayscale (2-bit) color format
framebuf.GS4_HMSB
Grayscale (4-bit) color format
framebuf.GS8
Grayscale (8-bit) color format

1.2.6 machine — functions related to the hardware

The machine module contains specific functions related to the hardware on a particular board. Most functions in this
module allow to achieve direct and unrestricted access to and control of hardware blocks on a system (like CPU, timers,
buses, etc.). Used incorrectly, this can lead to malfunction, lockups, crashes of your board, and in extreme cases, hardware
damage.
A note of callbacks used by functions and class methods of machine module: all these callbacks should be considered as
executing in an interrupt context. This is true for both physical devices with IDs >= 0 and “virtual” devices with negative
IDs like -1 (these “virtual” devices are still thin shims on top of real hardware and real hardware interrupts). See Writing
interrupt handlers.

Memory access

The module exposes three objects used for raw memory access.
machine.mem8
Read/write 8 bits of memory.
machine.mem16
Read/write 16 bits of memory.

1.2. MicroPython-specific libraries 69


MicroPython Documentation, Release v1.22.0

machine.mem32
Read/write 32 bits of memory.
Use subscript notation [...] to index these objects with the address of interest. Note that the address is the byte address,
regardless of the size of memory being accessed.
Example use (registers are specific to an stm32 microcontroller):

import machine
from micropython import const

GPIOA = const(0x48000000)
GPIO_BSRR = const(0x18)
GPIO_IDR = const(0x10)

# set PA2 high


machine.mem32[GPIOA + GPIO_BSRR] = 1 << 2

# read PA3
value = (machine.mem32[GPIOA + GPIO_IDR] >> 3) & 1

Reset related functions

machine.reset()
Resets the device in a manner similar to pushing the external RESET button.
machine.soft_reset()
Performs a soft reset of the interpreter, deleting all Python objects and resetting the Python heap. It tries to retain
the method by which the user is connected to the MicroPython REPL (eg serial, USB, Wifi).
machine.reset_cause()
Get the reset cause. See constants for the possible return values.
machine.bootloader([value ])
Reset the device and enter its bootloader. This is typically used to put the device into a state where it can be
programmed with new firmware.
Some ports support passing in an optional value argument which can control which bootloader to enter, what to
pass to it, or other things.

Interrupt related functions

The following functions allow control over interrupts. Some systems require interrupts to operate correctly so disabling
them for long periods may compromise core functionality, for example watchdog timers may trigger unexpectedly. In-
terrupts should only be disabled for a minimum amount of time and then re-enabled to their previous state. For example:

import machine

# Disable interrupts
state = machine.disable_irq()

# Do a small amount of time-critical work here

# Enable interrupts
machine.enable_irq(state)

70 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

machine.disable_irq()
Disable interrupt requests. Returns the previous IRQ state which should be considered an opaque value. This
return value should be passed to the enable_irq() function to restore interrupts to their original state, before
disable_irq() was called.
machine.enable_irq(state)
Re-enable interrupt requests. The state parameter should be the value that was returned from the most recent call
to the disable_irq() function.

Power related functions

machine.freq([hz ])
Returns the CPU frequency in hertz.
On some ports this can also be used to set the CPU frequency by passing in hz.
machine.idle()
Gates the clock to the CPU, useful to reduce power consumption at any time during short or long periods. Periph-
erals continue working and execution resumes as soon as any interrupt is triggered (on many ports this includes
system timer interrupt occurring at regular intervals on the order of millisecond).
machine.sleep()

Note: This function is deprecated, use lightsleep() instead with no arguments.

machine.lightsleep([time_ms ])
machine.deepsleep([time_ms ])
Stops execution in an attempt to enter a low power state.
If time_ms is specified then this will be the maximum time in milliseconds that the sleep will last for. Otherwise
the sleep can last indefinitely.
With or without a timeout, execution may resume at any time if there are events that require processing. Such
events, or wake sources, should be configured before sleeping, like Pin change or RTC timeout.
The precise behaviour and power-saving capabilities of lightsleep and deepsleep is highly dependent on the under-
lying hardware, but the general properties are:
• A lightsleep has full RAM and state retention. Upon wake execution is resumed from the point where the
sleep was requested, with all subsystems operational.
• A deepsleep may not retain RAM or any other state of the system (for example peripherals or network in-
terfaces). Upon wake execution is resumed from the main script, similar to a hard or power-on reset. The
reset_cause() function will return machine.DEEPSLEEP and this can be used to distinguish a deep-
sleep wake from other resets.
machine.wake_reason()
Get the wake reason. See constants for the possible return values.
Availability: ESP32, WiPy.

1.2. MicroPython-specific libraries 71


MicroPython Documentation, Release v1.22.0

Miscellaneous functions

machine.unique_id()
Returns a byte string with a unique identifier of a board/SoC. It will vary from a board/SoC instance to another, if
underlying hardware allows. Length varies by hardware (so use substring of a full value if you expect a short ID).
In some MicroPython ports, ID corresponds to the network MAC address.
machine.time_pulse_us(pin, pulse_level, timeout_us=1000000, / )
Time a pulse on the given pin, and return the duration of the pulse in microseconds. The pulse_level argument
should be 0 to time a low pulse or 1 to time a high pulse.
If the current input value of the pin is different to pulse_level, the function first (*) waits until the pin input becomes
equal to pulse_level, then (**) times the duration that the pin is equal to pulse_level. If the pin is already equal to
pulse_level then timing starts straight away.
The function will return -2 if there was timeout waiting for condition marked (*) above, and -1 if there was timeout
during the main measurement, marked (**) above. The timeout is the same for both cases and given by timeout_us
(which is in microseconds).
machine.bitstream(pin, encoding, timing, data, / )
Transmits data by bit-banging the specified pin. The encoding argument specifies how the bits are encoded, and
timing is an encoding-specific timing specification.
The supported encodings are:
• 0 for “high low” pulse duration modulation. This will transmit 0 and 1 bits as timed pulses, starting with
the most significant bit. The timing must be a four-tuple of nanoseconds in the format (high_time_0,
low_time_0, high_time_1, low_time_1). For example, (400, 850, 800, 450) is the
timing specification for WS2812 RGB LEDs at 800kHz.
The accuracy of the timing varies between ports. On Cortex M0 at 48MHz, it is at best +/- 120ns, however on
faster MCUs (ESP8266, ESP32, STM32, Pyboard), it will be closer to +/-30ns.

Note: For controlling WS2812 / NeoPixel strips, see the neopixel module for a higher-level API.

machine.rng()
Return a 24-bit software generated random number.
Availability: WiPy.

Constants

machine.IDLE
machine.SLEEP
machine.DEEPSLEEP
IRQ wake values.
machine.PWRON_RESET
machine.HARD_RESET
machine.WDT_RESET
machine.DEEPSLEEP_RESET

72 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

machine.SOFT_RESET
Reset causes.
machine.WLAN_WAKE
machine.PIN_WAKE
machine.RTC_WAKE
Wake-up reasons.

Classes

class Pin – control I/O pins

A pin object is used to control I/O pins (also known as GPIO - general-purpose input/output). Pin objects are commonly
associated with a physical pin that can drive an output voltage and read input voltages. The pin class has methods to set
the mode of the pin (IN, OUT, etc) and methods to get and set the digital logic level. For analog control of a pin, see the
ADC class.
A pin object is constructed by using an identifier which unambiguously specifies a certain I/O pin. The allowed forms of
the identifier and the physical pin that the identifier maps to are port-specific. Possibilities for the identifier are an integer,
a string or a tuple with port and pin number.
Usage Model:
from machine import Pin

# create an output pin on pin #0


p0 = Pin(0, Pin.OUT)

# set the value low then high


p0.value(0)
p0.value(1)

# create an input pin on pin #2, with a pull up resistor


p2 = Pin(2, Pin.IN, Pin.PULL_UP)

# read and print the pin value


print(p2.value())

# reconfigure pin #0 in input mode with a pull down resistor


p0.init(p0.IN, p0.PULL_DOWN)

# configure an irq callback


p0.irq(lambda p:print(p))

Constructors

class machine.Pin(id, mode=-1, pull=-1, *, value=None, drive=0, alt=-1)


Access the pin peripheral (GPIO pin) associated with the given id. If additional arguments are given in the
constructor then they are used to initialise the pin. Any settings that are not specified will remain in their previous
state.
The arguments are:
• id is mandatory and can be an arbitrary object. Among possible value types are: int (an internal Pin identi-
fier), str (a Pin name), and tuple (pair of [port, pin]).

1.2. MicroPython-specific libraries 73


MicroPython Documentation, Release v1.22.0

• mode specifies the pin mode, which can be one of:


– Pin.IN - Pin is configured for input. If viewed as an output the pin is in high-impedance state.
– Pin.OUT - Pin is configured for (normal) output.
– Pin.OPEN_DRAIN - Pin is configured for open-drain output. Open-drain output works in the following
way: if the output value is set to 0 the pin is active at a low level; if the output value is 1 the pin is in a
high-impedance state. Not all ports implement this mode, or some might only on certain pins.
– Pin.ALT - Pin is configured to perform an alternative function, which is port specific. For a pin con-
figured in such a way any other Pin methods (except Pin.init()) are not applicable (calling them
will lead to undefined, or a hardware-specific, result). Not all ports implement this mode.
– Pin.ALT_OPEN_DRAIN - The Same as Pin.ALT, but the pin is configured as open-drain. Not all
ports implement this mode.
– Pin.ANALOG - Pin is configured for analog input, see the ADC class.
• pull specifies if the pin has a (weak) pull resistor attached, and can be one of:
– None - No pull up or down resistor.
– Pin.PULL_UP - Pull up resistor enabled.
– Pin.PULL_DOWN - Pull down resistor enabled.
• value is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial output pin value if
given, otherwise the state of the pin peripheral remains unchanged.
• drive specifies the output power of the pin and can be one of: Pin.DRIVE_0, Pin.DRIVE_1, etc., in-
creasing in drive strength. The actual current driving capabilities are port dependent. Not all ports implement
this argument.
• alt specifies an alternate function for the pin and the values it can take are port dependent. This argument is
valid only for Pin.ALT and Pin.ALT_OPEN_DRAIN modes. It may be used when a pin supports more
than one alternate function. If only one pin alternate function is supported the this argument is not required.
Not all ports implement this argument.
As specified above, the Pin class allows to set an alternate function for a particular pin, but it does not specify any
further operations on such a pin. Pins configured in alternate-function mode are usually not used as GPIO but are
instead driven by other hardware peripherals. The only operation supported on such a pin is re-initialising, by calling
the constructor or Pin.init() method. If a pin that is configured in alternate-function mode is re-initialised
with Pin.IN, Pin.OUT, or Pin.OPEN_DRAIN, the alternate function will be removed from the pin.

Methods

Pin.init(mode=-1, pull=-1, *, value=None, drive=0, alt=-1)


Re-initialise the pin using the given parameters. Only those arguments that are specified will be set. The rest of
the pin peripheral state will remain unchanged. See the constructor documentation for details of the arguments.
Returns None.
Pin.value([x ])
This method allows to set and get the value of the pin, depending on whether the argument x is supplied or not.
If the argument is omitted then this method gets the digital logic level of the pin, returning 0 or 1 corresponding to
low and high voltage signals respectively. The behaviour of this method depends on the mode of the pin:
• Pin.IN - The method returns the actual input value currently present on the pin.
• Pin.OUT - The behaviour and return value of the method is undefined.

74 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• Pin.OPEN_DRAIN - If the pin is in state ‘0’ then the behaviour and return value of the method is undefined.
Otherwise, if the pin is in state ‘1’, the method returns the actual input value currently present on the pin.
If the argument is supplied then this method sets the digital logic level of the pin. The argument x can be anything
that converts to a boolean. If it converts to True, the pin is set to state ‘1’, otherwise it is set to state ‘0’. The
behaviour of this method depends on the mode of the pin:
• Pin.IN - The value is stored in the output buffer for the pin. The pin state does not change, it remains in the
high-impedance state. The stored value will become active on the pin as soon as it is changed to Pin.OUT
or Pin.OPEN_DRAIN mode.
• Pin.OUT - The output buffer is set to the given value immediately.
• Pin.OPEN_DRAIN - If the value is ‘0’ the pin is set to a low voltage state. Otherwise the pin is set to
high-impedance state.
When setting the value this method returns None.
Pin.__call__([x ])
Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. It is equivalent
to Pin.value([x]). See Pin.value() for more details.
Pin.on()
Set pin to “1” output level.
Pin.off()
Set pin to “0” output level.
Pin.irq(handler=None, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, *, priority=1, wake=None, hard=False)
Configure an interrupt handler to be called when the trigger source of the pin is active. If the pin mode is Pin.IN
then the trigger source is the external value on the pin. If the pin mode is Pin.OUT then the trigger source is the
output buffer of the pin. Otherwise, if the pin mode is Pin.OPEN_DRAIN then the trigger source is the output
buffer for state ‘0’ and the external pin value for state ‘1’.
The arguments are:
• handler is an optional function to be called when the interrupt triggers. The handler must take exactly one
argument which is the Pin instance.
• trigger configures the event which can generate an interrupt. Possible values are:
– Pin.IRQ_FALLING interrupt on falling edge.
– Pin.IRQ_RISING interrupt on rising edge.
– Pin.IRQ_LOW_LEVEL interrupt on low level.
– Pin.IRQ_HIGH_LEVEL interrupt on high level.
These values can be OR’ed together to trigger on multiple events.
• priority sets the priority level of the interrupt. The values it can take are port-specific, but higher values
always represent higher priorities.
• wake selects the power mode in which this interrupt can wake up the system. It can be machine.IDLE,
machine.SLEEP or machine.DEEPSLEEP. These values can also be OR’ed together to make a pin
generate interrupts in more than one power mode.
• hard if true a hardware interrupt is used. This reduces the delay between the pin change and the handler
being called. Hard interrupt handlers may not allocate memory; see Writing interrupt handlers. Not all ports
support this argument.
This method returns a callback object.

1.2. MicroPython-specific libraries 75


MicroPython Documentation, Release v1.22.0

The following methods are not part of the core Pin API and only implemented on certain ports.
Pin.low()
Set pin to “0” output level.
Availability: nrf, rp2, stm32 ports.
Pin.high()
Set pin to “1” output level.
Availability: nrf, rp2, stm32 ports.
Pin.mode([mode ])
Get or set the pin mode. See the constructor documentation for details of the mode argument.
Availability: cc3200, stm32 ports.
Pin.pull([pull ])
Get or set the pin pull state. See the constructor documentation for details of the pull argument.
Availability: cc3200, stm32 ports.
Pin.drive([drive ])
Get or set the pin drive strength. See the constructor documentation for details of the drive argument.
Availability: cc3200 port.

Constants

The following constants are used to configure the pin objects. Note that not all constants are available on all ports.
Pin.IN
Pin.OUT
Pin.OPEN_DRAIN
Pin.ALT
Pin.ALT_OPEN_DRAIN
Pin.ANALOG
Selects the pin mode.
Pin.PULL_UP
Pin.PULL_DOWN
Pin.PULL_HOLD
Selects whether there is a pull up/down resistor. Use the value None for no pull.
Pin.DRIVE_0
Pin.DRIVE_1
Pin.DRIVE_2
Selects the pin drive strength. A port may define additional drive constants with increasing number corresponding
to increasing drive strength.
Pin.IRQ_FALLING
Pin.IRQ_RISING
Pin.IRQ_LOW_LEVEL
Pin.IRQ_HIGH_LEVEL
Selects the IRQ trigger type.

76 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class Signal – control and sense external I/O devices

The Signal class is a simple extension of the Pin class. Unlike Pin, which can be only in “absolute” 0 and 1 states, a
Signal can be in “asserted” (on) or “deasserted” (off) states, while being inverted (active-low) or not. In other words, it
adds logical inversion support to Pin functionality. While this may seem a simple addition, it is exactly what is needed
to support wide array of simple digital devices in a way portable across different boards, which is one of the major
MicroPython goals. Regardless of whether different users have an active-high or active-low LED, a normally open or
normally closed relay - you can develop a single, nicely looking application which works with each of them, and capture
hardware configuration differences in few lines in the config file of your app.
Example:

from machine import Pin, Signal

# Suppose you have an active-high LED on pin 0


led1_pin = Pin(0, Pin.OUT)
# ... and active-low LED on pin 1
led2_pin = Pin(1, Pin.OUT)

# Now to light up both of them using Pin class, you'll need to set
# them to different values
led1_pin.value(1)
led2_pin.value(0)

# Signal class allows to abstract away active-high/active-low


# difference
led1 = Signal(led1_pin, invert=False)
led2 = Signal(led2_pin, invert=True)

# Now lighting up them looks the same


led1.value(1)
led2.value(1)

# Even better:
led1.on()
led2.on()

Following is the guide when Signal vs Pin should be used:


• Use Signal: If you want to control a simple on/off (including software PWM!) devices like LEDs, multi-segment
indicators, relays, buzzers, or read simple binary sensors, like normally open or normally closed buttons, pulled high
or low, Reed switches, moisture/flame detectors, etc. etc. Summing up, if you have a real physical device/sensor
requiring GPIO access, you likely should use a Signal.
• Use Pin: If you implement a higher-level protocol or bus to communicate with more complex devices.
The split between Pin and Signal come from the use cases above and the architecture of MicroPython: Pin offers the
lowest overhead, which may be important when bit-banging protocols. But Signal adds additional flexibility on top of
Pin, at the cost of minor overhead (much smaller than if you implemented active-high vs active-low device differences in
Python manually!). Also, Pin is a low-level object which needs to be implemented for each support board, while Signal
is a high-level object which comes for free once Pin is implemented.
If in doubt, give the Signal a try! Once again, it is offered to save developers from the need to handle unexciting differences
like active-low vs active-high signals, and allow other users to share and enjoy your application, instead of being frustrated
by the fact that it doesn’t work for them simply because their LEDs or relays are wired in a slightly different way.

1.2. MicroPython-specific libraries 77


MicroPython Documentation, Release v1.22.0

Constructors

class machine.Signal(pin_obj, invert=False)


class machine.Signal(pin_arguments..., *, invert=False)
Create a Signal object. There’re two ways to create it:
• By wrapping existing Pin object - universal method which works for any board.
• By passing required Pin parameters directly to Signal constructor, skipping the need to create intermediate
Pin object. Available on many, but not all boards.
The arguments are:
• pin_obj is existing Pin object.
• pin_arguments are the same arguments as can be passed to Pin constructor.
• invert - if True, the signal will be inverted (active low).

Methods

Signal.value([x ])
This method allows to set and get the value of the signal, depending on whether the argument x is supplied or not.
If the argument is omitted then this method gets the signal level, 1 meaning signal is asserted (active) and 0 - signal
inactive.
If the argument is supplied then this method sets the signal level. The argument x can be anything that converts to
a boolean. If it converts to True, the signal is active, otherwise it is inactive.
Correspondence between signal being active and actual logic level on the underlying pin depends on whether signal
is inverted (active-low) or not. For non-inverted signal, active status corresponds to logical 1, inactive - to logical
0. For inverted/active-low signal, active status corresponds to logical 0, while inactive - to logical 1.
Signal.on()
Activate signal.
Signal.off()
Deactivate signal.

class ADC – analog to digital conversion

The ADC class provides an interface to analog-to-digital converters, and represents a single endpoint that can sample a
continuous voltage and convert it to a discretised value.
For extra control over ADC sampling see machine.ADCBlock.
Example usage:

from machine import ADC

adc = ADC(pin) # create an ADC object acting on a pin


val = adc.read_u16() # read a raw analog value in the range 0-65535
val = adc.read_uv() # read an analog value in microvolts

78 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class machine.ADC(id, *, sample_ns, atten)


Access the ADC associated with a source identified by id. This id may be an integer (usually specifying a channel
number), a Pin object, or other value supported by the underlying machine.
If additional keyword-arguments are given then they will configure various aspects of the ADC. If not given, these
settings will take previous or default values. The settings are:
• sample_ns is the sampling time in nanoseconds.
• atten specifies the input attenuation.

Methods

ADC.init(*, sample_ns, atten)


Apply the given settings to the ADC. Only those arguments that are specified will be changed. See the ADC
constructor above for what the arguments are.
ADC.block()
Return the ADCBlock instance associated with this ADC object.
This method only exists if the port supports the ADCBlock class.
ADC.read_u16()
Take an analog reading and return an integer in the range 0-65535. The return value represents the raw reading
taken by the ADC, scaled such that the minimum value is 0 and the maximum value is 65535.
ADC.read_uv()
Take an analog reading and return an integer value with units of microvolts. It is up to the particular port whether
or not this value is calibrated, and how calibration is done.

class ADCBlock – control ADC peripherals

The ADCBlock class provides access to an ADC peripheral which has a number of channels that can be used to sample
analog values. It allows finer control over configuration of machine.ADC objects, which do the actual sampling.
This class is not always available.
Example usage:

from machine import ADCBlock

block = ADCBlock(id, bits=12) # create an ADCBlock with 12-bit resolution


adc = block.connect(4, pin) # connect channel 4 to the given pin
val = adc.read_uv() # read an analog value

1.2. MicroPython-specific libraries 79


MicroPython Documentation, Release v1.22.0

Constructors

class machine.ADCBlock(id, *, bits)


Access the ADC peripheral identified by id, which may be an integer or string.
The bits argument, if given, sets the resolution in bits of the conversion process. If not specified then the previous
or default resolution is used.

Methods

ADCBlock.init(*, bits)
Configure the ADC peripheral. bits will set the resolution of the conversion process.
ADCBlock.connect(channel, *, ...)
ADCBlock.connect(source, *, ...)
ADCBlock.connect(channel, source, *, ...)
Connect up a channel on the ADC peripheral so it is ready for sampling, and return an ADC object that represents
that connection.
The channel argument must be an integer, and source must be an object (for example a Pin) which can be connected
up for sampling.
If only channel is given then it is configured for sampling.
If only source is given then that object is connected to a default channel ready for sampling.
If both channel and source are given then they are connected together and made ready for sampling.
Any additional keyword arguments are used to configure the returned ADC object, via its init method.

class PWM – pulse width modulation

This class provides pulse width modulation output.


Example usage:

from machine import PWM

pwm = PWM(pin, freq=50, duty_u16=8192) # create a PWM object on a pin


# and set freq and duty
pwm.duty_u16(32768) # set duty to 50%

# reinitialise with a period of 200us, duty of 5us


pwm.init(freq=5000, duty_ns=5000)

pwm.duty_ns(3000) # set pulse width to 3us

pwm.deinit()

80 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class machine.PWM(dest, *, freq, duty_u16, duty_ns, invert)


Construct and return a new PWM object using the following parameters:
• dest is the entity on which the PWM is output, which is usually a machine.Pin object, but a port may allow
other values, like integers.
• freq should be an integer which sets the frequency in Hz for the PWM cycle.
• duty_u16 sets the duty cycle as a ratio duty_u16 / 65535.
• duty_ns sets the pulse width in nanoseconds.
• invert inverts the respective output if the value is True
Setting freq may affect other PWM objects if the objects share the same underlying PWM generator (this is hard-
ware specific). Only one of duty_u16 and duty_ns should be specified at a time. invert is not available at all ports.

Methods

PWM.init(*, freq, duty_u16, duty_ns)


Modify settings for the PWM object. See the above constructor for details about the parameters.
PWM.deinit()
Disable the PWM output.
PWM.freq([value ])
Get or set the current frequency of the PWM output.
With no arguments the frequency in Hz is returned.
With a single value argument the frequency is set to that value in Hz. The method may raise a ValueError if
the frequency is outside the valid range.
PWM.duty_u16([value ])
Get or set the current duty cycle of the PWM output, as an unsigned 16-bit value in the range 0 to 65535 inclusive.
With no arguments the duty cycle is returned.
With a single value argument the duty cycle is set to that value, measured as the ratio value / 65535.
PWM.duty_ns([value ])
Get or set the current pulse width of the PWM output, as a value in nanoseconds.
With no arguments the pulse width in nanoseconds is returned.
With a single value argument the pulse width is set to that value.

1.2. MicroPython-specific libraries 81


MicroPython Documentation, Release v1.22.0

Specific PWM class implementations

The following concrete class(es) implement enhancements to the PWM class.


pyb.Timer for PyBoard

Limitations of PWM

• Not all frequencies can be generated with absolute accuracy due to the discrete nature of the computing hardware.
Typically the PWM frequency is obtained by dividing some integer base frequency by an integer divider. For
example, if the base frequency is 80MHz and the required PWM frequency is 300kHz the divider must be a non-
integer number 80000000 / 300000 = 266.67. After rounding the divider is set to 267 and the PWM frequency
will be 80000000 / 267 = 299625.5 Hz, not 300kHz. If the divider is set to 266 then the PWM frequency will be
80000000 / 266 = 300751.9 Hz, but again not 300kHz.
Some ports like the RP2040 one use a fractional divider, which allow a finer granularity of the frequency at higher
frequencies by switching the PWM pulse duration between two adjacent values, such that the resulting average
frequency is more close to the intended one, at the cost of spectral purity.
• The duty cycle has the same discrete nature and its absolute accuracy is not achievable. On most hardware platforms
the duty will be applied at the next frequency period. Therefore, you should wait more than “1/frequency” before
measuring the duty.
• The frequency and the duty cycle resolution are usually interdependent. The higher the PWM frequency the lower
the duty resolution which is available, and vice versa. For example, a 300kHz PWM frequency can have a duty
cycle resolution of 8 bit, not 16-bit as may be expected. In this case, the lowest 8 bits of duty_u16 are insignificant.
So:

pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2)

and:

pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2 + 255)

will generate PWM with the same 50% duty cycle.

class UART – duplex serial communication bus

UART implements the standard UART/USART duplex serial communications protocol. At the physical level it consists
of 2 lines: RX and TX. The unit of communication is a character (not to be confused with a string character) which can
be 8 or 9 bits wide.
UART objects can be created and initialised using:

from machine import UART

uart = UART(1, 9600) # init with given baudrate


uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters

Supported parameters differ on a board:


Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With parity=None, only 8 and 9 bits are supported. With parity
enabled, only 7 and 8 bits are supported.
WiPy/CC3200: Bits can be 5, 6, 7, 8. Stop can be 1 or 2.
A UART object acts like a stream object and reading and writing is done using the standard stream methods:

82 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

uart.read(10) # read 10 characters, returns a bytes object


uart.read() # read all available characters
uart.readline() # read a line
uart.readinto(buf) # read and store into the given buffer
uart.write('abc') # write the 3 characters

Constructors

class machine.UART(id, ...)


Construct a UART object of the given id.

Methods

UART.init(baudrate=9600, bits=8, parity=None, stop=1, *, ...)


Initialise the UART bus with the given parameters:
• baudrate is the clock rate.
• bits is the number of bits per character, 7, 8 or 9.
• parity is the parity, None, 0 (even) or 1 (odd).
• stop is the number of stop bits, 1 or 2.
Additional keyword-only parameters that may be supported by a port are:
• tx specifies the TX pin to use.
• rx specifies the RX pin to use.
• rts specifies the RTS (output) pin to use for hardware receive flow control.
• cts specifies the CTS (input) pin to use for hardware transmit flow control.
• txbuf specifies the length in characters of the TX buffer.
• rxbuf specifies the length in characters of the RX buffer.
• timeout specifies the time to wait for the first character (in ms).
• timeout_char specifies the time to wait between characters (in ms).
• invert specifies which lines to invert.
– 0 will not invert lines (idle state of both lines is logic high).
– UART.INV_TX will invert TX line (idle state of TX line now logic low).
– UART.INV_RX will invert RX line (idle state of RX line now logic low).
– UART.INV_TX | UART.INV_RX will invert both lines (idle state at logic low).
• flow specifies which hardware flow control signals to use. The value is a bitmask.
– 0 will ignore hardware flow control signals.
– UART.RTS will enable receive flow control by using the RTS output pin to signal if the receive FIFO
has sufficient space to accept more data.
– UART.CTS will enable transmit flow control by pausing transmission when the CTS input pin signals
that the receiver is running low on buffer space.

1.2. MicroPython-specific libraries 83


MicroPython Documentation, Release v1.22.0

– UART.RTS | UART.CTS will enable both, for full hardware flow control.
On the WiPy only the following keyword-only parameter is supported:
• pins is a 4 or 2 item list indicating the TX, RX, RTS and CTS pins (in that order). Any of the pins can be
None if one wants the UART to operate with limited functionality. If the RTS pin is given the the RX pin
must be given as well. The same applies to CTS. When no pins are given, then the default set of TX and RX
pins is taken, and hardware flow control will be disabled. If pins is None, no pin assignment will be made.

Note: It is possible to call init() multiple times on the same object in order to reconfigure UART on the fly.
That allows using single UART peripheral to serve different devices attached to different GPIO pins. Only one
device can be served at a time in that case. Also do not call deinit() as it will prevent calling init() again.

UART.deinit()
Turn off the UART bus.

Note: You will not be able to call init() on the object after deinit(). A new instance needs to be created
in that case.

UART.any()
Returns an integer counting the number of characters that can be read without blocking. It will return 0 if there
are no characters available and a positive number if there are characters. The method may return 1 even if there is
more than one character available for reading.
For more sophisticated querying of available characters use select.poll:

poll = select.poll()
poll.register(uart, select.POLLIN)
poll.poll(timeout)

UART.read([nbytes ])
Read characters. If nbytes is specified then read at most that many bytes, otherwise read as much data as possible.
It may return sooner if a timeout is reached. The timeout is configurable in the constructor.
Return value: a bytes object containing the bytes read in. Returns None on timeout.
UART.readinto(buf [, nbytes ])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most
len(buf) bytes. It may return sooner if a timeout is reached. The timeout is configurable in the constructor.
Return value: number of bytes read and stored into buf or None on timeout.
UART.readline()
Read a line, ending in a newline character. It may return sooner if a timeout is reached. The timeout is configurable
in the constructor.
Return value: the line read or None on timeout.
UART.write(buf)
Write the buffer of bytes to the bus.
Return value: number of bytes written or None on timeout.
UART.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration longer than required for a normal
transmission of a character.

84 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

UART.irq(trigger, priority=1, handler=None, wake=machine.IDLE)


Create a callback to be triggered when data is received on the UART.
• trigger can only be UART.RX_ANY
• priority level of the interrupt. Can take values in the range 1-7. Higher values represent higher priorities.
• handler an optional function to be called when new characters arrive.
• wake can only be machine.IDLE.

Note: The handler will be called whenever any of the following two conditions are met:
• 8 new characters have been received.
• At least 1 new character is waiting in the Rx buffer and the Rx line has been silent for the duration of 1
complete frame.
This means that when the handler function is called there will be between 1 to 8 characters waiting.

Returns an irq object.


Availability: WiPy.
UART.flush()
Waits until all data has been sent. In case of a timeout, an exception is raised. The timeout duration depends on
the tx buffer size and the baud rate. Unless flow control is enabled, a timeout should not occur.

Note: For the rp2, esp8266 and nrf ports the call returns while the last byte is sent. If required, a one character
wait time has to be added in the calling script.

Availability: rp2, esp32, esp8266, mimxrt, cc3200, stm32, nrf ports, renesas-ra
UART.txdone()
Tells whether all data has been sent or no data transfer is happening. In this case, it returns True. If a data
transmission is ongoing it returns False.

Note: For the rp2, esp8266 and nrf ports the call may return True even if the last byte of a transfer is still being
sent. If required, a one character wait time has to be added in the calling script.

Availability: rp2, esp32, esp8266, mimxrt, cc3200, stm32, nrf ports, renesas-ra

Constants

UART.RX_ANY
IRQ trigger sources
Availability: WiPy.

1.2. MicroPython-specific libraries 85


MicroPython Documentation, Release v1.22.0

class SPI – a Serial Peripheral Interface bus protocol (controller side)

SPI is a synchronous serial protocol that is driven by a controller. At the physical level, a bus consists of 3 lines: SCK,
MOSI, MISO. Multiple devices can share the same bus. Each device should have a separate, 4th signal, CS (Chip Select),
to select a particular device on a bus with which communication takes place. Management of a CS signal should happen
in user code (via machine.Pin class).
Both hardware and software SPI implementations exist via the machine.SPI and machine.SoftSPI classes. Hardware
SPI uses underlying hardware support of the system to perform the reads/writes and is usually efficient and fast but may
have restrictions on which pins can be used. Software SPI is implemented by bit-banging and can be used on any pin but
is not as efficient. These classes have the same methods available and differ primarily in the way they are constructed.
Example usage:

from machine import SPI, Pin

spi = SPI(0, baudrate=400000) # Create SPI peripheral 0 at frequency of␣


,→400kHz.

# Depending on the use case, extra parameters␣


,→ may be required
# to select the bus characteristics and/or␣
,→pins to use.
cs = Pin(4, mode=Pin.OUT, value=1) # Create chip-select on pin 4.

try:
cs(0) # Select peripheral.
spi.write(b"12345678") # Write 8 bytes, and don't care about␣
,→received data.

finally:
cs(1) # Deselect peripheral.

try:
cs(0) # Select peripheral.
rxdata = spi.read(8, 0x42) # Read 8 bytes while writing 0x42 for each␣
,→byte.

finally:
cs(1) # Deselect peripheral.

rxdata = bytearray(8)
try:
cs(0) # Select peripheral.
spi.readinto(rxdata, 0x42) # Read 8 bytes inplace while writing 0x42 for␣
,→each byte.

finally:
cs(1) # Deselect peripheral.

txdata = b"12345678"
rxdata = bytearray(len(txdata))
try:
cs(0) # Select peripheral.
spi.write_readinto(txdata, rxdata) # Simultaneously write and read bytes.
finally:
cs(1) # Deselect peripheral.

86 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class machine.SPI(id, ...)


Construct an SPI object on the given bus, id. Values of id depend on a particular port and its hardware. Values 0,
1, etc. are commonly used to select hardware SPI block #0, #1, etc.
With no additional parameters, the SPI object is created but not initialised (it has the settings from the last ini-
tialisation of the bus, if any). If extra arguments are given, the bus is initialised. See init for parameters of
initialisation.
class machine.SoftSPI(baudrate=500000, *, polarity=0, phase=0, bits=8, firstbit=MSB, sck=None,
mosi=None, miso=None)
Construct a new software SPI object. Additional parameters must be given, usually at least sck, mosi and miso, and
these are used to initialise the bus. See SPI.init for a description of the parameters.

Methods

SPI.init(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None,


pins=(SCK, MOSI, MISO))
Initialise the SPI bus with the given parameters:
• baudrate is the SCK clock rate.
• polarity can be 0 or 1, and is the level the idle clock line sits at.
• phase can be 0 or 1 to sample data on the first or second clock edge respectively.
• bits is the width in bits of each transfer. Only 8 is guaranteed to be supported by all hardware.
• firstbit can be SPI.MSB or SPI.LSB.
• sck, mosi, miso are pins (machine.Pin) objects to use for bus signals. For most hardware SPI blocks (as
selected by id parameter to the constructor), pins are fixed and cannot be changed. In some cases, hardware
blocks allow 2-3 alternative pin sets for a hardware SPI block. Arbitrary pin assignments are possible only
for a bitbanging SPI driver (id = -1).
• pins - WiPy port doesn’t sck, mosi, miso arguments, and instead allows to specify them as a tuple of
pins parameter.
In the case of hardware SPI the actual clock frequency may be lower than the requested baudrate. This is dependent
on the platform hardware. The actual rate may be determined by printing the SPI object.
SPI.deinit()
Turn off the SPI bus.
SPI.read(nbytes, write=0x00)
Read a number of bytes specified by nbytes while continuously writing the single byte given by write. Returns
a bytes object with the data that was read.
SPI.readinto(buf, write=0x00)
Read into the buffer specified by buf while continuously writing the single byte given by write. Returns None.
Note: on WiPy this function returns the number of bytes read.
SPI.write(buf)
Write the bytes contained in buf. Returns None.
Note: on WiPy this function returns the number of bytes written.

1.2. MicroPython-specific libraries 87


MicroPython Documentation, Release v1.22.0

SPI.write_readinto(write_buf, read_buf)
Write the bytes from write_buf while reading into read_buf. The buffers can be the same or different, but
both buffers must have the same length. Returns None.
Note: on WiPy this function returns the number of bytes written.

Constants

SPI.CONTROLLER
for initialising the SPI bus to controller; this is only used for the WiPy
SPI.MSB
SoftSPI.MSB
set the first bit to be the most significant bit
SPI.LSB
SoftSPI.LSB
set the first bit to be the least significant bit

class I2C – a two-wire serial protocol

I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and
SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on.
Printing the I2C object gives you information about its configuration.
Both hardware and software I2C implementations exist via the machine.I2C and machine.SoftI2C classes. Hardware
I2C uses underlying hardware support of the system to perform the reads/writes and is usually efficient and fast but may
have restrictions on which pins can be used. Software I2C is implemented by bit-banging and can be used on any pin but
is not as efficient. These classes have the same methods available and differ primarily in the way they are constructed.

Note: The I2C bus requires pull-up circuitry on both SDA and SCL for it’s operation. Usually these are resistors in
the range of 1 - 10 kOhm, connected from each SDA/SCL to Vcc. Without these, the behaviour is undefined and may
range from blocking, unexpected watchdog reset to just wrong values. Often, this pull-up circuitry is built-in already to
the MCU board or sensor breakout boards, but there is no rule for that. So please check in case of trouble. See also this
excellent learning guide by Adafruit about I2C wiring.

Example usage:
from machine import I2C

i2c = I2C(freq=400000) # create I2C peripheral at frequency of 400kHz


# depending on the port, extra parameters may be␣
,→ required
# to select the peripheral and/or pins to use

i2c.scan() # scan for peripherals, returning a list of 7-bit␣


,→addresses

i2c.writeto(42, b'123') # write 3 bytes to peripheral with 7-bit address 42


i2c.readfrom(42, 4) # read 4 bytes from peripheral with 7-bit address 42
(continues on next page)

88 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)

i2c.readfrom_mem(42, 8, 3) # read 3 bytes from memory of peripheral 42,


# starting at memory-address 8 in the peripheral
i2c.writeto_mem(42, 2, b'\x10') # write 1 byte to memory of peripheral 42
# starting at address 2 in the peripheral

Constructors

class machine.I2C(id, *, scl, sda, freq=400000, timeout=50000)


Construct and return a new I2C object using the following parameters:
• id identifies a particular I2C peripheral. Allowed values for depend on the particular port/board
• scl should be a pin object specifying the pin to use for SCL.
• sda should be a pin object specifying the pin to use for SDA.
• freq should be an integer which sets the maximum frequency for SCL.
• timeout is the maximum time in microseconds to allow for I2C transactions. This parameter is not allowed
on some ports.
Note that some ports/boards will have default values of scl and sda that can be changed in this constructor. Others
will have fixed values of scl and sda that cannot be changed.
class machine.SoftI2C(scl, sda, *, freq=400000, timeout=50000)
Construct a new software I2C object. The parameters are:
• scl should be a pin object specifying the pin to use for SCL.
• sda should be a pin object specifying the pin to use for SDA.
• freq should be an integer which sets the maximum frequency for SCL.
• timeout is the maximum time in microseconds to wait for clock stretching (SCL held low by another device
on the bus), after which an OSError(ETIMEDOUT) exception is raised.

General Methods

I2C.init(scl, sda, *, freq=400000)


Initialise the I2C bus with the given arguments:
• scl is a pin object for the SCL line
• sda is a pin object for the SDA line
• freq is the SCL clock rate
In the case of hardware I2C the actual clock frequency may be lower than the requested frequency. This
is dependent on the platform hardware. The actual rate may be determined by printing the I2C object.
I2C.deinit()
Turn off the I2C bus.
Availability: WiPy.
I2C.scan()
Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of those that respond. A device responds
if it pulls the SDA line low after its address (including a write bit) is sent on the bus.

1.2. MicroPython-specific libraries 89


MicroPython Documentation, Release v1.22.0

Primitive I2C operations

The following methods implement the primitive I2C controller bus operations and can be combined to make any I2C
transaction. They are provided if you need more control over the bus, otherwise the standard methods (see below) can be
used.
These methods are only available on the machine.SoftI2C class.
I2C.start()
Generate a START condition on the bus (SDA transitions to low while SCL is high).
I2C.stop()
Generate a STOP condition on the bus (SDA transitions to high while SCL is high).
I2C.readinto(buf, nack=True, / )
Reads bytes from the bus and stores them into buf. The number of bytes read is the length of buf. An ACK will be
sent on the bus after receiving all but the last byte. After the last byte is received, if nack is true then a NACK will
be sent, otherwise an ACK will be sent (and in this case the peripheral assumes more bytes are going to be read in
a later call).
I2C.write(buf)
Write the bytes from buf to the bus. Checks that an ACK is received after each byte and stops transmitting the
remaining bytes if a NACK is received. The function returns the number of ACKs that were received.

Standard bus operations

The following methods implement the standard I2C controller read and write operations that target a given peripheral
device.
I2C.readfrom(addr, nbytes, stop=True, / )
Read nbytes from the peripheral specified by addr. If stop is true then a STOP condition is generated at the end of
the transfer. Returns a bytes object with the data read.
I2C.readfrom_into(addr, buf, stop=True, / )
Read into buf from the peripheral specified by addr. The number of bytes read will be the length of buf. If stop is
true then a STOP condition is generated at the end of the transfer.
The method returns None.
I2C.writeto(addr, buf, stop=True, / )
Write the bytes from buf to the peripheral specified by addr. If a NACK is received following the write of a byte
from buf then the remaining bytes are not sent. If stop is true then a STOP condition is generated at the end of the
transfer, even if a NACK is received. The function returns the number of ACKs that were received.
I2C.writevto(addr, vector, stop=True, / )
Write the bytes contained in vector to the peripheral specified by addr. vector should be a tuple or list of objects with
the buffer protocol. The addr is sent once and then the bytes from each object in vector are written out sequentially.
The objects in vector may be zero bytes in length in which case they don’t contribute to the output.
If a NACK is received following the write of a byte from one of the objects in vector then the remaining bytes, and
any remaining objects, are not sent. If stop is true then a STOP condition is generated at the end of the transfer,
even if a NACK is received. The function returns the number of ACKs that were received.

90 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Memory operations

Some I2C devices act as a memory device (or set of registers) that can be read from and written to. In this case there
are two addresses associated with an I2C transaction: the peripheral address and the memory address. The following
methods are convenience functions to communicate with such devices.
I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
Read nbytes from the peripheral specified by addr starting from the memory address specified by memaddr. The
argument addrsize specifies the address size in bits. Returns a bytes object with the data read.
I2C.readfrom_mem_into(addr, memaddr, buf, *, addrsize=8)
Read into buf from the peripheral specified by addr starting from the memory address specified by memaddr. The
number of bytes read is the length of buf. The argument addrsize specifies the address size in bits (on ESP8266
this argument is not recognised and the address size is always 8 bits).
The method returns None.
I2C.writeto_mem(addr, memaddr, buf, *, addrsize=8)
Write buf to the peripheral specified by addr starting from the memory address specified by memaddr. The argu-
ment addrsize specifies the address size in bits (on ESP8266 this argument is not recognised and the address size
is always 8 bits).
The method returns None.

class I2S – Inter-IC Sound bus protocol

I2S is a synchronous serial protocol used to connect digital audio devices. At the physical level, a bus consists of 3 lines:
SCK, WS, SD. The I2S class supports controller operation. Peripheral operation is not supported.
The I2S class is currently available as a Technical Preview. During the preview period, feedback from users is encouraged.
Based on this feedback, the I2S class API and implementation may be changed.
I2S objects can be created and initialized using:
from machine import I2S
from machine import Pin

# ESP32
sck_pin = Pin(14) # Serial clock output
ws_pin = Pin(13) # Word clock output
sd_pin = Pin(12) # Serial data output

or

# PyBoards
sck_pin = Pin("Y6") # Serial clock output
ws_pin = Pin("Y5") # Word clock output
sd_pin = Pin("Y8") # Serial data output

audio_out = I2S(2,
sck=sck_pin, ws=ws_pin, sd=sd_pin,
mode=I2S.TX,
bits=16,
format=I2S.MONO,
rate=44100,
ibuf=20000)

(continues on next page)

1.2. MicroPython-specific libraries 91


MicroPython Documentation, Release v1.22.0

(continued from previous page)


audio_in = I2S(2,
sck=sck_pin, ws=ws_pin, sd=sd_pin,
mode=I2S.RX,
bits=32,
format=I2S.STEREO,
rate=22050,
ibuf=20000)

3 modes of operation are supported:


• blocking
• non-blocking
• asyncio
blocking:

num_written = audio_out.write(buf) # blocks until buf emptied

num_read = audio_in.readinto(buf) # blocks until buf filled

non-blocking:

audio_out.irq(i2s_callback) # i2s_callback is called when buf is emptied


num_written = audio_out.write(buf) # returns immediately

audio_in.irq(i2s_callback) # i2s_callback is called when buf is filled


num_read = audio_in.readinto(buf) # returns immediately

asyncio:

swriter = asyncio.StreamWriter(audio_out)
swriter.write(buf)
await swriter.drain()

sreader = asyncio.StreamReader(audio_in)
num_read = await sreader.readinto(buf)

Some codec devices like the WM8960 or SGTL5000 require separate initialization before they can operate with the I2S
class. For these, separate drivers are supplied, which also offer methods for controlling volume, audio processing and
other things. For these drivers see:
• WM8960 – Driver for the WM8960 codec

Constructor

class machine.I2S(id, *, sck, ws, sd, mck=None, mode, bits, format, rate, ibuf)
Construct an I2S object of the given id:
• id identifies a particular I2S bus; it is board and port specific
Keyword-only parameters that are supported on all ports:
• sck is a pin object for the serial clock line
• ws is a pin object for the word select line
• sd is a pin object for the serial data line

92 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• mck is a pin object for the master clock line; master clock frequency is sampling rate * 256
• mode specifies receive or transmit
• bits specifies sample size (bits), 16 or 32
• format specifies channel format, STEREO or MONO
• rate specifies audio sampling rate (Hz); this is the frequency of the ws signal
• ibuf specifies internal buffer length (bytes)
For all ports, DMA runs continuously in the background and allows user applications to perform other operations
while sample data is transferred between the internal buffer and the I2S peripheral unit. Increasing the size of the
internal buffer has the potential to increase the time that user applications can perform non-I2S operations before
underflow (e.g. write method) or overflow (e.g. readinto method).

Methods

I2S.init(sck, ...)
see Constructor for argument descriptions
I2S.deinit()
Deinitialize the I2S bus
I2S.readinto(buf)
Read audio samples into the buffer specified by buf. buf must support the buffer protocol, such as bytearray or
array. “buf” byte ordering is little-endian. For Stereo format, left channel sample precedes right channel sample.
For Mono format, the left channel sample data is used. Returns number of bytes read
I2S.write(buf)
Write audio samples contained in buf. buf must support the buffer protocol, such as bytearray or array. “buf”
byte ordering is little-endian. For Stereo format, left channel sample precedes right channel sample. For Mono
format, the sample data is written to both the right and left channels. Returns number of bytes written
I2S.irq(handler)
Set a callback. handler is called when buf is emptied (write method) or becomes full (readinto method).
Setting a callback changes the write and readinto methods to non-blocking operation. handler is called
in the context of the MicroPython scheduler.
static I2S.shift(*, buf, bits, shift)
bitwise shift of all samples contained in buf. bits specifies sample size in bits. shift specifies the number of
bits to shift each sample. Positive for left shift, negative for right shift. Typically used for volume control. Each bit
shift changes sample volume by 6dB.

Constants

I2S.RX
for initialising the I2S bus mode to receive
I2S.TX
for initialising the I2S bus mode to transmit
I2S.STEREO
for initialising the I2S bus format to stereo

1.2. MicroPython-specific libraries 93


MicroPython Documentation, Release v1.22.0

I2S.MONO
for initialising the I2S bus format to mono

class RTC – real time clock

The RTC is an independent clock that keeps track of the date and time.
Example usage:

rtc = machine.RTC()
rtc.datetime((2020, 1, 21, 2, 10, 32, 36, 0))
print(rtc.datetime())

Constructors

class machine.RTC(id=0, ...)


Create an RTC object. See init for parameters of initialization.

Methods

RTC.datetime([datetimetuple ])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being an
8-tuple) it sets the date and time.
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
The meaning of the subseconds field is hardware dependent.
RTC.init(datetime)
Initialise the RTC. Datetime is a tuple of the form:
(year, month, day[, hour[, minute[, second[, microsecond[, tz-
info]]]]])
RTC.now()
Get get the current datetime tuple.
RTC.deinit()
Resets the RTC to the time of January 1, 2015 and starts running it again.
RTC.alarm(id, time, *, repeat=False)
Set the RTC alarm. Time might be either a millisecond value to program the alarm to current time + time_in_ms
in the future, or a datetimetuple. If the time passed is in milliseconds, repeat can be set to True to make the alarm
periodic.
RTC.alarm_left(alarm_id=0)
Get the number of milliseconds left before the alarm expires.
RTC.cancel(alarm_id=0)
Cancel a running alarm.

94 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

RTC.irq(*, trigger, handler=None, wake=machine.IDLE)


Create an irq object triggered by a real time clock alarm.
• trigger must be RTC.ALARM0
• handler is the function to be called when the callback is triggered.
• wake specifies the sleep mode from where this interrupt can wake up the system.

Constants

RTC.ALARM0
irq trigger source

class Timer – control hardware timers

Hardware timers deal with timing of periods and events. Timers are perhaps the most flexible and heterogeneous kind of
hardware in MCUs and SoCs, differently greatly from a model to a model. MicroPython’s Timer class defines a baseline
operation of executing a callback with a given period (or once after some delay), and allow specific boards to define more
non-standard behaviour (which thus won’t be portable to other boards).
See discussion of important constraints on Timer callbacks.

Note: Memory can’t be allocated inside irq handlers (an interrupt) and so exceptions raised within a handler don’t
give much information. See micropython.alloc_emergency_exception_buf() for how to get around this
limitation.

If you are using a WiPy board please refer to machine.TimerWiPy instead of this class.

Constructors

class machine.Timer(id, / , ...)


Construct a new timer object of the given id. id of -1 constructs a virtual timer (if supported by a board). id
shall not be passed as a keyword argument.
See init for parameters of initialisation.

Methods

Timer.init(*, mode=Timer.PERIODIC, freq=-1, period=-1, callback=None)


Initialise the timer. Example:

def mycallback(t):
pass

# periodic at 1kHz
tim.init(mode=Timer.PERIODIC, freq=1000, callback=mycallback)

# periodic with 100ms period


tim.init(period=100, callback=mycallback)
(continues on next page)

1.2. MicroPython-specific libraries 95


MicroPython Documentation, Release v1.22.0

(continued from previous page)

# one shot firing after 1000ms


tim.init(mode=Timer.ONE_SHOT, period=1000, callback=mycallback)

Keyword arguments:
• mode can be one of:
– Timer.ONE_SHOT - The timer runs once until the configured period of the channel expires.
– Timer.PERIODIC - The timer runs periodically at the configured frequency of the channel.
• freq - The timer frequency, in units of Hz. The upper bound of the frequency is dependent on the port.
When both the freq and period arguments are given, freq has a higher priority and period is ignored.
• period - The timer period, in milliseconds.
• callback - The callable to call upon expiration of the timer period. The callback must take one argument,
which is passed the Timer object. The callback argument shall be specified. Otherwise an exception will
occur upon timer expiration: TypeError: 'NoneType' object isn't callable
Timer.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.

Constants

Timer.ONE_SHOT
Timer.PERIODIC
Timer operating mode.

class WDT – watchdog timer

The WDT is used to restart the system when the application crashes and ends up into a non recoverable state. Once started
it cannot be stopped or reconfigured in any way. After enabling, the application must “feed” the watchdog periodically to
prevent it from expiring and resetting the system.
Example usage:

from machine import WDT


wdt = WDT(timeout=2000) # enable it with a timeout of 2s
wdt.feed()

Availability of this class: pyboard, WiPy, esp8266, esp32, rp2040, mimxrt.

Constructors

class machine.WDT(id=0, timeout=5000)


Create a WDT object and start it. The timeout must be given in milliseconds. Once it is running the timeout cannot
be changed and the WDT cannot be stopped either.
Notes: On the esp8266 a timeout cannot be specified, it is determined by the underlying system. On rp2040 devices,
the maximum timeout is 8388 ms.

96 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Methods

WDT.feed()
Feed the WDT to prevent it from resetting the system. The application should place this call in a sensible place
ensuring that the WDT is only fed after verifying that everything is functioning correctly.

class SD – secure digital memory card (cc3200 port only)

Warning: This is a non-standard class and is only available on the cc3200 port.

The SD card class allows to configure and enable the memory card module of the WiPy and automatically mount it as
/sd as part of the file system. There are several pin combinations that can be used to wire the SD card socket to the
WiPy and the pins used can be specified in the constructor. Please check the pinout and alternate functions table. for
more info regarding the pins which can be remapped to be used with a SD card.
Example usage:

from machine import SD


import os
# clk cmd and dat0 pins must be passed along with
# their respective alternate functions
sd = machine.SD(pins=('GP10', 'GP11', 'GP15'))
os.mount(sd, '/sd')
# do normal file operations

Constructors

class machine.SD(id, ...)


Create a SD card object. See init() for parameters if initialization.

Methods

SD.init(id=0, pins=('GP10', 'GP11', 'GP15'))


Enable the SD card. In order to initialize the card, give it a 3-tuple: (clk_pin, cmd_pin, dat0_pin).
SD.deinit()
Disable the SD card.

class SDCard – secure digital memory card

SD cards are one of the most common small form factor removable storage media. SD cards come in a variety of sizes
and physical form factors. MMC cards are similar removable storage devices while eMMC devices are electrically similar
storage devices designed to be embedded into other systems. All three form share a common protocol for communication
with their host system and high-level support looks the same for them all. As such in MicroPython they are implemented
in a single class called machine.SDCard .
Both SD and MMC interfaces support being accessed with a variety of bus widths. When being accessed with a 1-bit
wide interface they can be accessed using the SPI protocol. Different MicroPython hardware platforms support different

1.2. MicroPython-specific libraries 97


MicroPython Documentation, Release v1.22.0

widths and pin configurations but for most platforms there is a standard configuration for any given hardware. In general
constructing an SDCard object with without passing any parameters will initialise the interface to the default card slot
for the current hardware. The arguments listed below represent the common arguments that might need to be set in order
to use either a non-standard slot or a non-standard pin assignment. The exact subset of arguments supported will vary
from platform to platform.
class machine.SDCard(slot=1, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None, cs=None,
freq=20000000)
This class provides access to SD or MMC storage cards using either a dedicated SD/MMC interface hardware or
through an SPI channel. The class implements the block protocol defined by os.AbstractBlockDev. This
allows the mounting of an SD card to be as simple as:

os.mount(machine.SDCard(), "/sd")

The constructor takes the following parameters:


• slot selects which of the available interfaces to use. Leaving this unset will select the default interface.
• width selects the bus width for the SD/MMC interface.
• cd can be used to specify a card-detect pin.
• wp can be used to specify a write-protect pin.
• sck can be used to specify an SPI clock pin.
• miso can be used to specify an SPI miso pin.
• mosi can be used to specify an SPI mosi pin.
• cs can be used to specify an SPI chip select pin.
• freq selects the SD/MMC interface frequency in Hz (only supported on the ESP32).

Implementation-specific details

Different implementations of the SDCard class on different hardware support varying subsets of the options above.

PyBoard

The standard PyBoard has just one slot. No arguments are necessary or supported.

ESP32

The ESP32 provides two channels of SD/MMC hardware and also supports access to SD Cards through either of the two
SPI ports that are generally available to the user. As a result the slot argument can take a value between 0 and 3, inclusive.
Slots 0 and 1 use the built-in SD/MMC hardware while slots 2 and 3 use the SPI ports. Slot 0 supports 1, 4 or 8-bit wide
access while slot 1 supports 1 or 4-bit access; the SPI slots only support 1-bit access.

Note: Slot 0 is used to communicate with on-board flash memory on most ESP32 modules and so will be
unavailable to the user.

98 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Note: Most ESP32 modules that provide an SD card slot using the dedicated hardware only wire up 1 data
pin, so the default value for width is 1.

The pins used by the dedicated SD/MMC hardware are fixed. The pins used by the SPI hardware can be reassigned.

Note: If any of the SPI signals are remapped then all of the SPI signals will pass through a GPIO multiplexer
unit which can limit the performance of high frequency signals. Since the normal operating speed for SD
cards is 40MHz this can cause problems on some cards.

The default (and preferred) pin assignment are as follows:

Slot 0 1 2 3
Signal Pin Pin Pin Pin
sck 6 14 18 14
cmd 11 15
cs 5 15
miso 19 12
mosi 23 13
D0 7 2
D1 8 4
D2 9 12
D3 10 13
D4 16
D5 17
D6 5
D7 18

cc3200

You can set the pins used for SPI access by passing a tuple as the pins argument.
Note: The current cc3200 SD card implementation names the this class machine.SD rather than machine.SDCard
.

mimxrt

The SDCard module for the mimxrt port only supports access via dedicated SD/MMC peripheral (USDHC) in 4-bit mode
with 50MHz clock frequency exclusively. Unfortunately the MIMXRT1011 controller does not support the USDHC
peripheral. Hence this controller does not feature the machine.SDCard module.
Due to the decision to only support 4-bit mode with 50MHz clock frequency the interface has been simplified, and the
constructor signature is:
class machine.SDCard(slot=1)

The pins used for the USDHC peripheral have to be configured in mpconfigboard.h. Most of the controllers sup-
ported by the mimxrt port provide up to two USDHC peripherals. Therefore the pin configuration is performed using the
macro MICROPY_USDHCx with x being 1 or 2 respectively.
The following shows an example configuration for USDHC1:

1.2. MicroPython-specific libraries 99


MicroPython Documentation, Release v1.22.0

#define MICROPY_USDHC1 \
{ \
.cmd = { GPIO_SD_B0_02_USDHC1_CMD}, \
.clk = { GPIO_SD_B0_03_USDHC1_CLK }, \
.cd_b = { GPIO_SD_B0_06_USDHC1_CD_B },\
.data0 = { GPIO_SD_B0_04_USDHC1_DATA0 },\
.data1 = { GPIO_SD_B0_05_USDHC1_DATA1 },\
.data2 = { GPIO_SD_B0_00_USDHC1_DATA2 },\
.data3 = { GPIO_SD_B0_01_USDHC1_DATA3 },\
}

If the card detect pin is not used (cb_b pin) then the respective entry has to be filled with the following dummy value:

#define USDHC_DUMMY_PIN NULL , 0

Based on the definition of macro MICROPY_USDHC1 and/or MICROPY_USDHC2 the machine.SDCard module
either supports one or two slots. If only one of the defines is provided, calling machine.SDCard() or machine.
SDCard(1) will return an instance using the respective USDHC peripheral. When both macros are defined, calling
machine.SDCard(2) returns an instance using USDHC2.

1.2.7 micropython – access and control MicroPython internals

Functions

micropython.const(expr)
Used to declare that the expression is a constant so that the compiler can optimise it. The use of this function should
be as follows:

from micropython import const

CONST_X = const(123)
CONST_Y = const(2 * CONST_X + 1)

Constants declared this way are still accessible as global variables from outside the module they are declared in.
On the other hand, if a constant begins with an underscore then it is hidden, it is not available as a global variable,
and does not take up any memory during execution.
This const function is recognised directly by the MicroPython parser and is provided as part of the micropy-
thon module mainly so that scripts can be written which run under both CPython and MicroPython, by following
the above pattern.
micropython.opt_level([level ])
If level is given then this function sets the optimisation level for subsequent compilation of scripts, and returns
None. Otherwise it returns the current optimisation level.
The optimisation level controls the following compilation features:
• Assertions: at level 0 assertion statements are enabled and compiled into the bytecode; at levels 1 and higher
assertions are not compiled.
• Built-in __debug__ variable: at level 0 this variable expands to True; at levels 1 and higher it expands to
False.
• Source-code line numbers: at levels 0, 1 and 2 source-code line number are stored along with the bytecode
so that exceptions can report the line number they occurred at; at levels 3 and higher line numbers are not
stored.

100 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

The default optimisation level is usually level 0.


micropython.alloc_emergency_exception_buf(size)
Allocate size bytes of RAM for the emergency exception buffer (a good size is around 100 bytes). The buffer is
used to create exceptions in cases when normal RAM allocation would fail (eg within an interrupt handler) and
therefore give useful traceback information in these situations.
A good way to use this function is to put it at the start of your main script (eg boot.py or main.py) and then
the emergency exception buffer will be active for all the code following it.
micropython.mem_info([verbose ])
Print information about currently used memory. If the verbose argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently includes the amount of stack and heap
used. In verbose mode it prints out the entire heap indicating which blocks are used and which are free.
micropython.qstr_info([verbose ])
Print information about currently interned strings. If the verbose argument is given then extra information is printed.
The information that is printed is implementation dependent, but currently includes the number of interned strings
and the amount of RAM they use. In verbose mode it prints out the names of all RAM-interned strings.
micropython.stack_use()
Return an integer representing the current amount of stack that is being used. The absolute value of this is not
particularly useful, rather it should be used to compute differences in stack usage at different points.
micropython.heap_lock()

micropython.heap_unlock()

micropython.heap_locked()
Lock or unlock the heap. When locked no memory allocation can occur and a MemoryError will be raised if
any heap allocation is attempted. heap_locked() returns a true value if the heap is currently locked.
These functions can be nested, ie heap_lock() can be called multiple times in a row and the lock-depth will
increase, and then heap_unlock() must be called the same number of times to make the heap available again.
Both heap_unlock() and heap_locked() return the current lock depth (after unlocking for the former) as
a non-negative integer, with 0 meaning the heap is not locked.
If the REPL becomes active with the heap locked then it will be forcefully unlocked.
Note: heap_locked() is not enabled on most ports by default, requires MI-
CROPY_PY_MICROPYTHON_HEAP_LOCKED.
micropython.kbd_intr(chr)
Set the character that will raise a KeyboardInterrupt exception. By default this is set to 3 during script
execution, corresponding to Ctrl-C. Passing -1 to this function will disable capture of Ctrl-C, and passing 3 will
restore it.
This function can be used to prevent the capturing of Ctrl-C on the incoming stream of characters that is usually
used for the REPL, in case that stream is used for other purposes.
micropython.schedule(func, arg)
Schedule the function func to be executed “very soon”. The function is passed the value arg as its single argument.
“Very soon” means that the MicroPython runtime will do its best to execute the function at the earliest possible
time, given that it is also trying to be efficient, and that the following conditions hold:
• A scheduled function will never preempt another scheduled function.
• Scheduled functions are always executed “between opcodes” which means that all fundamental Python oper-
ations (such as appending to a list) are guaranteed to be atomic.

1.2. MicroPython-specific libraries 101


MicroPython Documentation, Release v1.22.0

• A given port may define “critical regions” within which scheduled functions will never be executed. Functions
may be scheduled within a critical region but they will not be executed until that region is exited. An example
of a critical region is a preempting interrupt handler (an IRQ).
A use for this function is to schedule a callback from a preempting IRQ. Such an IRQ puts restrictions on the code
that runs in the IRQ (for example the heap may be locked) and scheduling a function to call later will lift those
restrictions.
Note: If schedule() is called from a preempting IRQ, when memory allocation is not allowed and the callback
to be passed to schedule() is a bound method, passing this directly will fail. This is because creating a refer-
ence to a bound method causes memory allocation. A solution is to create a reference to the method in the class
constructor and to pass that reference to schedule(). This is discussed in detail here reference documentation
under “Creation of Python objects”.
There is a finite queue to hold the scheduled functions and schedule() will raise a RuntimeError if the
queue is full.

1.2.8 neopixel — control of WS2812 / NeoPixel LEDs

This module provides a driver for WS2818 / NeoPixel LEDs.

Note: This module is only included by default on the ESP8266, ESP32 and RP2 ports. On STM32 / Pyboard and others,
you can either install the neopixel package using mip, or you can download the module directly from micropython-lib
and copy it to the filesystem.

class NeoPixel

This class stores pixel data for a WS2812 LED strip connected to a pin. The application should set pixel data and then
call NeoPixel.write() when it is ready to update the strip.
For example:

import neopixel

# 32 LED strip connected to X8.


p = machine.Pin.board.X8
n = neopixel.NeoPixel(p, 32)

# Draw a red gradient.


for i in range(32):
n[i] = (i * 8, 0, 0)

# Update the strip.


n.write()

102 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class neopixel.NeoPixel(pin, n, *, bpp=3, timing=1)


Construct an NeoPixel object. The parameters are:
• pin is a machine.Pin instance.
• n is the number of LEDs in the strip.
• bpp is 3 for RGB LEDs, and 4 for RGBW LEDs.
• timing is 0 for 400KHz, and 1 for 800kHz LEDs (most are 800kHz).

Pixel access methods

NeoPixel.fill(pixel)
Sets the value of all pixels to the specified pixel value (i.e. an RGB/RGBW tuple).
NeoPixel.__len__()
Returns the number of LEDs in the strip.
NeoPixel.__setitem__(index, val)
Set the pixel at index to the value, which is an RGB/RGBW tuple.
NeoPixel.__getitem__(index)
Returns the pixel at index as an RGB/RGBW tuple.

Output methods

NeoPixel.write()
Writes the current pixel data to the strip.

1.2.9 network — network configuration

This module provides network drivers and routing configuration. To use this module, a MicroPython variant/build with
network capabilities must be installed. Network drivers for specific hardware are available within this module and are
used to configure hardware network interface(s). Network services provided by configured interfaces are then available
for use via the socket module.
For example:

# connect/ show IP config a specific network interface


# see below for examples of specific drivers
import network
import time
nic = network.Driver(...)
if not nic.isconnected():
nic.connect()
print("Waiting for connection...")
while not nic.isconnected():
time.sleep(1)
print(nic.ifconfig())

# now use socket as usual


(continues on next page)

1.2. MicroPython-specific libraries 103


MicroPython Documentation, Release v1.22.0

(continued from previous page)


import socket
addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
data = s.recv(1000)
s.close()

Common network adapter interface

This section describes an (implied) abstract base class for all network interface classes implemented by MicroPython ports
for different hardware. This means that MicroPython does not actually provide AbstractNIC class, but any actual NIC
class, as described in the following sections, implements methods as described here.
class network.AbstractNIC(id=None, ...)

Instantiate a network interface object. Parameters are network interface dependent. If there are more than one interface
of the same type, the first parameter should be id.
AbstractNIC.active([is_active ])
Activate (“up”) or deactivate (“down”) the network interface, if a boolean argument is passed. Otherwise, query
current state if no argument is provided. Most other methods require an active interface (behaviour of calling them
on inactive interface is undefined).
AbstractNIC.connect([service_id, key=None, *, ... ])
Connect the interface to a network. This method is optional, and available only for interfaces which are not “always
connected”. If no parameters are given, connect to the default (or the only) service. If a single parameter is given,
it is the primary identifier of a service to connect to. It may be accompanied by a key (password) required to access
said service. There can be further arbitrary keyword-only parameters, depending on the networking medium type
and/or particular device. Parameters can be used to: a) specify alternative service identifier types; b) provide
additional connection parameters. For various medium types, there are different sets of predefined/recommended
parameters, among them:
• WiFi: bssid keyword to connect to a specific BSSID (MAC address)
AbstractNIC.disconnect()
Disconnect from network.
AbstractNIC.isconnected()
Returns True if connected to network, otherwise returns False.
AbstractNIC.scan(*, ...)
Scan for the available network services/connections. Returns a list of tuples with discovered service parameters.
For various network media, there are different variants of predefined/ recommended tuple formats, among them:
• WiFi: (ssid, bssid, channel, RSSI, security, hidden). There may be further fields, specific to a particular
device.
The function may accept additional keyword arguments to filter scan results (e.g. scan for a particular service, on
a particular channel, for services of a particular set, etc.), and to affect scan duration and other parameters. Where
possible, parameter names should match those in connect().
AbstractNIC.status([param ])
Query dynamic status information of the interface. When called with no argument the return value describes the
network link status. Otherwise param should be a string naming the particular status parameter to retrieve.

104 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

The return types and values are dependent on the network medium/technology. Some of the parameters that may
be supported are:
• WiFi STA: use 'rssi' to retrieve the RSSI of the AP signal
• WiFi AP: use 'stations' to retrieve a list of all the STAs connected to the AP. The list contains tuples
of the form (MAC, RSSI).
AbstractNIC.ifconfig([(ip, subnet, gateway, dns) ])
Get/set IP-level network interface parameters: IP address, subnet mask, gateway and DNS server. When called
with no arguments, this method returns a 4-tuple with the above information. To set the above values, pass a 4-tuple
with the required information. For example:

nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))

AbstractNIC.config('param')
AbstractNIC.config(param=value, ...)
Get or set general network interface parameters. These methods allow to work with additional parameters beyond
standard IP configuration (as dealt with by ifconfig()). These include network-specific and hardware-specific
parameters. For setting parameters, the keyword argument syntax should be used, and multiple parameters can be
set at once. For querying, a parameter name should be quoted as a string, and only one parameter can be queried
at a time:

# Set WiFi access point name (formally known as SSID) and WiFi channel
ap.config(ssid='My AP', channel=11)
# Query params one by one
print(ap.config('ssid'))
print(ap.config('channel'))

Specific network class implementations

The following concrete classes implement the AbstractNIC interface and provide a way to control networking interfaces
of various kinds.

class WLAN – control built-in WiFi interfaces

This class provides a driver for WiFi network processors. Example usage:

import network
# enable station interface and connect to WiFi access point
nic = network.WLAN(network.STA_IF)
nic.active(True)
nic.connect('your-ssid', 'your-key')
# now use sockets as usual

1.2. MicroPython-specific libraries 105


MicroPython Documentation, Release v1.22.0

Constructors

class network.WLAN(interface_id)

Create a WLAN network interface object. Supported interfaces are network.STA_IF (station aka client, connects to
upstream WiFi access points) and network.AP_IF (access point, allows other WiFi clients to connect). Availability
of the methods below depends on interface type. For example, only STA interface may WLAN.connect() to an access
point.

Methods

WLAN.active([is_active ])
Activate (“up”) or deactivate (“down”) network interface, if boolean argument is passed. Otherwise, query current
state if no argument is provided. Most other methods require active interface.
WLAN.connect(ssid=None, key=None, *, bssid=None)
Connect to the specified wireless network, using the specified key. If bssid is given then the connection will be
restricted to the access-point with that MAC address (the ssid must also be specified in this case).
WLAN.disconnect()
Disconnect from the currently connected wireless network.
WLAN.scan()
Scan for the available wireless networks. Hidden networks – where the SSID is not broadcast – will also be scanned
if the WLAN interface allows it.
Scanning is only possible on STA interface. Returns list of tuples with the information about WiFi access points:
(ssid, bssid, channel, RSSI, security, hidden)
bssid is hardware address of an access point, in binary form, returned as bytes object. You can use binascii.
hexlify() to convert it to ASCII form.
There are five values for security:
• 0 – open
• 1 – WEP
• 2 – WPA-PSK
• 3 – WPA2-PSK
• 4 – WPA/WPA2-PSK
and two for hidden:
• 0 – visible
• 1 – hidden
WLAN.status([param ])
Return the current status of the wireless connection.
When called with no argument the return value describes the network link status. The possible statuses are defined
as constants:
• STAT_IDLE – no connection and no activity,
• STAT_CONNECTING – connecting in progress,

106 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• STAT_WRONG_PASSWORD – failed due to incorrect password,


• STAT_NO_AP_FOUND – failed because no access point replied,
• STAT_CONNECT_FAIL – failed due to other problems,
• STAT_GOT_IP – connection successful.
When called with one argument param should be a string naming the status parameter to retrieve. Supported
parameters in WiFI STA mode are: 'rssi'.
WLAN.isconnected()
In case of STA mode, returns True if connected to a WiFi access point and has a valid IP address. In AP mode
returns True when a station is connected. Returns False otherwise.
WLAN.ifconfig([(ip, subnet, gateway, dns) ])
Get/set IP-level network interface parameters: IP address, subnet mask, gateway and DNS server. When called
with no arguments, this method returns a 4-tuple with the above information. To set the above values, pass a 4-tuple
with the required information. For example:

nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))

WLAN.config('param')
WLAN.config(param=value, ...)
Get or set general network interface parameters. These methods allow to work with additional parameters beyond
standard IP configuration (as dealt with by WLAN.ifconfig()). These include network-specific and hardware-
specific parameters. For setting parameters, keyword argument syntax should be used, multiple parameters can be
set at once. For querying, parameters name should be quoted as a string, and only one parameter can be queries at
time:

# Set WiFi access point name (formally known as SSID) and WiFi channel
ap.config(ssid='My AP', channel=11)
# Query params one by one
print(ap.config('ssid'))
print(ap.config('channel'))

Following are commonly supported parameters (availability of a specific parameter depends on network technology
type, driver, and MicroPython port).

1.2. MicroPython-specific libraries 107


MicroPython Documentation, Release v1.22.0

Pa- Description
rame-
ter
mac MAC address (bytes)
ssid WiFi access point name (string)
chan- WiFi channel (integer)
nel
hidden Whether SSID is hidden (boolean)
secu- Security protocol supported (enumeration, see module constants)
rity
key Access key (string)
host- The hostname that will be sent to DHCP (STA interfaces) and mDNS (if supported, both STA and
name AP). (Deprecated, use network.hostname() instead)
recon- Number of reconnect attempts to make (integer, 0=none, -1=unlimited)
nects
tx- Maximum transmit power in dBm (integer or float)
power
pm WiFi Power Management setting (see below for allowed values)

Constants

WLAN.PM_PERFORMANCE
WLAN.PM_POWERSAVE
WLAN.PM_NONE
Allowed values for the WLAN.config(pm=...) network interface parameter:
• PM_PERFORMANCE: enable WiFi power management to balance power savings and WiFi performance
• PM_POWERSAVE: enable WiFi power management with additional power savings and reduced WiFi perfor-
mance
• PM_NONE: disable wifi power management

class WLANWiPy – WiPy specific WiFi control

Note: This class is a non-standard WLAN implementation for the WiPy. It is available simply as network.WLAN on
the WiPy but is named in the documentation below as network.WLANWiPy to distinguish it from the more general
network.WLAN class.

This class provides a driver for the WiFi network processor in the WiPy. Example usage:

import network
import time
# setup as a station
wlan = network.WLAN(mode=WLAN.STA)
wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key'))
while not wlan.isconnected():
time.sleep_ms(50)
print(wlan.ifconfig())
(continues on next page)

108 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)

# now use socket as usual


...

Constructors

class network.WLANWiPy(id=0, ...)


Create a WLAN object, and optionally configure it. See init() for params of configuration.

Note: The WLAN constructor is special in the sense that if no arguments besides the id are given, it will return the already
existing WLAN instance without re-configuring it. This is because WLAN is a system feature of the WiPy. If the already
existing instance is not initialized it will do the same as the other constructors an will initialize it with default values.

Methods

WLANWiPy.init(mode, *, ssid, auth, channel, antenna)


Set or get the WiFi network processor configuration.
Arguments are:
• mode can be either WLAN.STA or WLAN.AP.
• ssid is a string with the ssid name. Only needed when mode is WLAN.AP.
• auth is a tuple with (sec, key). Security can be None, WLAN.WEP, WLAN.WPA or WLAN.WPA2. The key is
a string with the network password. If sec is WLAN.WEP the key must be a string representing hexadecimal
values (e.g. ‘ABC1DE45BF’). Only needed when mode is WLAN.AP.
• channel a number in the range 1-11. Only needed when mode is WLAN.AP.
• antenna selects between the internal and the external antenna. Can be either WLAN.INT_ANT or WLAN.
EXT_ANT.
For example, you can do:
# create and configure as an access point
wlan.init(mode=WLAN.AP, ssid='wipy-wlan', auth=(WLAN.WPA2,'www.wipy.io'),␣
,→channel=7, antenna=WLAN.INT_ANT)

or:
# configure as an station
wlan.init(mode=WLAN.STA)

WLANWiPy.connect(ssid, *, auth=None, bssid=None, timeout=None)


Connect to a WiFi access point using the given SSID, and other security parameters.
• auth is a tuple with (sec, key). Security can be None, WLAN.WEP, WLAN.WPA or WLAN.WPA2. The key is
a string with the network password. If sec is WLAN.WEP the key must be a string representing hexadecimal
values (e.g. ‘ABC1DE45BF’).
• bssid is the MAC address of the AP to connect to. Useful when there are several APs with the same ssid.
• timeout is the maximum time in milliseconds to wait for the connection to succeed.

1.2. MicroPython-specific libraries 109


MicroPython Documentation, Release v1.22.0

WLANWiPy.scan()
Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi). Note that channel
is always None since this info is not provided by the WiPy.
WLANWiPy.disconnect()
Disconnect from the WiFi access point.
WLANWiPy.isconnected()
In case of STA mode, returns True if connected to a WiFi access point and has a valid IP address. In AP mode
returns True when a station is connected, False otherwise.
WLANWiPy.ifconfig(if_id=0, config=['dhcp' or configtuple])
With no parameters given returns a 4-tuple of (ip, subnet_mask, gateway, DNS_server).
if 'dhcp' is passed as a parameter then the DHCP client is enabled and the IP params are negotiated with the
AP.
If the 4-tuple config is given then a static IP is configured. For instance:

wlan.ifconfig(config=('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))

WLANWiPy.mode([mode ])
Get or set the WLAN mode.
WLANWiPy.ssid([ssid ])
Get or set the SSID when in AP mode.
WLANWiPy.auth([auth ])
Get or set the authentication type when in AP mode.
WLANWiPy.channel([channel ])
Get or set the channel (only applicable in AP mode).
WLANWiPy.antenna([antenna ])
Get or set the antenna type (external or internal).
WLANWiPy.mac([mac_addr ])
Get or set a 6-byte long bytes object with the MAC address.
WLANWiPy.irq(*, handler, wake)
Create a callback to be triggered when a WLAN event occurs during machine.SLEEP mode. Events are trig-
gered by socket activity or by WLAN connection/disconnection.
• handler is the function that gets called when the IRQ is triggered.
• wake must be machine.SLEEP.
Returns an IRQ object.

110 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

WLANWiPy.STA

WLANWiPy.AP
selects the WLAN mode
WLANWiPy.WEP

WLANWiPy.WPA

WLANWiPy.WPA2
selects the network security
WLANWiPy.INT_ANT

WLANWiPy.EXT_ANT
selects the antenna type

class WIZNET5K – control WIZnet5x00 Ethernet modules

This class allows you to control WIZnet5x00 Ethernet adaptors based on the W5200 and W5500 chipsets. The particular
chipset that is supported by the firmware is selected at compile-time via the MICROPY_PY_NETWORK_WIZNET5K
option.
Example usage:

import network
nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
print(nic.ifconfig())

# now use socket as usual


...

For this example to work the WIZnet5x00 module must have the following connections:
• MOSI connected to X8
• MISO connected to X7
• SCLK connected to X6
• nSS connected to X5
• nRESET connected to X4
It is possible to use other SPI buses and other pins for nSS and nRESET.

1.2. MicroPython-specific libraries 111


MicroPython Documentation, Release v1.22.0

Constructors

class network.WIZNET5K(spi, pin_cs, pin_rst)


Create a WIZNET5K driver object, initialise the WIZnet5x00 module using the given SPI bus and pins, and return
the WIZNET5K object.
Arguments are:
• spi is an SPI object which is the SPI bus that the WIZnet5x00 is connected to (the MOSI, MISO and SCLK
pins).
• pin_cs is a Pin object which is connected to the WIZnet5x00 nSS pin.
• pin_rst is a Pin object which is connected to the WIZnet5x00 nRESET pin.
All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example,
you can use:

nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)

Methods

WIZNET5K.isconnected()
Returns True if the physical Ethernet link is connected and up. Returns False otherwise.
WIZNET5K.ifconfig([(ip, subnet, gateway, dns) ])
Get/set IP address, subnet mask, gateway and DNS.
When called with no arguments, this method returns a 4-tuple with the above information.
To set the above values, pass a 4-tuple with the required information. For example:

nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))

WIZNET5K.regs()
Dump the WIZnet5x00 registers. Useful for debugging.

class LAN – control an Ethernet module

This class allows you to control the Ethernet interface. The PHY hardware type is board-specific.
Example usage:

import network
nic = network.LAN(0)
print(nic.ifconfig())

# now use socket as usual


...

112 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class network.LAN(id, *, phy_type=<board_default>, phy_addr=<board_default>,


ref_clk_mode=<board_default>)
Create a LAN driver object, initialise the LAN module using the given PHY driver name, and return the LAN
object.
Arguments are:
• id is the number of the Ethernet port, either 0 or 1.
• phy_type is the name of the PHY driver. For most board the on-board PHY has to be used and is the default.
Suitable values are port specific.
• phy_addr specifies the address of the PHY interface. As with phy_type, the hardwired value has to be used
for most boards and that value is the default.
• ref_clk_mode specifies, whether the data clock is provided by the Ethernet controller or the PYH interface.
The default value is the one that matches the board. If set to LAN.OUT or Pin.OUT or True, the clock is
driven by the Ethernet controller, if set to LAN.IN or Pin.IN or False, the clock is driven by the PHY
interface.
For example, with the Seeed Arch Mix board you can use:

nic = LAN(0, phy_type=LAN.PHY_LAN8720, phy_addr=1, ref_clk_mode=Pin.IN)

Methods

LAN.active([state ])
With a parameter, it sets the interface active if state is true, otherwise it sets it inactive. Without a parameter, it
returns the state.
LAN.isconnected()
Returns True if the physical Ethernet link is connected and up. Returns False otherwise.
LAN.status()
Returns the LAN status.
LAN.ifconfig([(ip, subnet, gateway, dns) ])
Get/set IP address, subnet mask, gateway and DNS.
When called with no arguments, this method returns a 4-tuple with the above information.
To set the above values, pass a 4-tuple with the required information. For example:

nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))

LAN.config(config_parameters)
Sets or gets parameters of the LAN interface. The only parameter that can be retrieved is the MAC address, using:

mac = LAN.config("mac")

The parameters that can be set are:


• trace=n sets trace levels; suitable values are:
– 2: trace TX

1.2. MicroPython-specific libraries 113


MicroPython Documentation, Release v1.22.0

– 4: trace RX
– 8: full trace
• low_power=bool sets or clears low power mode, valid values being False or True.

Specific LAN class implementations

On the mimxrt port, suitable values for the phy_type constructor argument are: PHY_KSZ8081, PHY_DP83825,
PHY_DP83848, PHY_LAN8720, PHY_RTL8211F.

Network functions

The following are functions available in the network module.


network.country([code ])
Get or set the two-letter ISO 3166-1 Alpha-2 country code to be used for radio compliance.
If the code parameter is provided, the country will be set to this value. If the function is called without parameters,
it returns the current country.
The default code "XX" represents the “worldwide” region.
network.hostname([name ])
Get or set the hostname that will identify this device on the network. It will be used by all interfaces.
This hostname is used for:
• Sending to the DHCP server in the client request. (If using DHCP)
• Broadcasting via mDNS. (If enabled)
If the name parameter is provided, the hostname will be set to this value. If the function is called without parameters,
it returns the current hostname.
A change in hostname is typically only applied during connection. For DHCP this is because the hostname is part of
the DHCP client request, and the implementation of mDNS in most ports only initialises the hostname once during
connection. For this reason, you must set the hostname before activating/connecting your network interfaces.
The length of the hostname is limited to 32 characters. MicroPython ports may choose to set a lower limit for
memory reasons. If the given name does not fit, a ValueError is raised.
The default hostname is typically the name of the board.
network.phy_mode([mode ])
Get or set the PHY mode.
If the mode parameter is provided, the PHY mode will be set to this value. If the function is called without
parameters, it returns the current PHY mode.
The possible modes are defined as constants:
• MODE_11B – IEEE 802.11b,
• MODE_11G – IEEE 802.11g,
• MODE_11N – IEEE 802.11n.
Availability: ESP8266.

114 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

1.2.10 uctypes – access binary data in a structured way

This module implements “foreign data interface” for MicroPython. The idea behind it is similar to CPython’s ctypes
modules, but the actual API is different, streamlined and optimized for small size. The basic idea of the module is to define
data structure layout with about the same power as the C language allows, and then access it using familiar dot-syntax to
reference sub-fields.

Warning: uctypes module allows access to arbitrary memory addresses of the machine (including I/O and control
registers). Uncareful usage of it may lead to crashes, data loss, and even hardware malfunction.

See also:
Module struct
Standard Python way to access binary data structures (doesn’t scale well to large and complex structures).
Usage examples:

import uctypes

# Example 1: Subset of ELF file header


# https://wikipedia.org/wiki/Executable_and_Linkable_Format#File_header
ELF_HEADER = {
"EI_MAG": (0x0 | uctypes.ARRAY, 4 | uctypes.UINT8),
"EI_DATA": 0x5 | uctypes.UINT8,
"e_machine": 0x12 | uctypes.UINT16,
}

# "f" is an ELF file opened in binary mode


buf = f.read(uctypes.sizeof(ELF_HEADER, uctypes.LITTLE_ENDIAN))
header = uctypes.struct(uctypes.addressof(buf), ELF_HEADER, uctypes.LITTLE_ENDIAN)
assert header.EI_MAG == b"\x7fELF"
assert header.EI_DATA == 1, "Oops, wrong endianness. Could retry with uctypes.BIG_
,→ENDIAN."

print("machine:", hex(header.e_machine))

# Example 2: In-memory data structure, with pointers


COORD = {
"x": 0 | uctypes.FLOAT32,
"y": 4 | uctypes.FLOAT32,
}

STRUCT1 = {
"data1": 0 | uctypes.UINT8,
"data2": 4 | uctypes.UINT32,
"ptr": (8 | uctypes.PTR, COORD),
}

# Suppose you have address of a structure of type STRUCT1 in "addr"


# uctypes.NATIVE is optional (used by default)
struct1 = uctypes.struct(addr, STRUCT1, uctypes.NATIVE)
print("x:", struct1.ptr[0].x)

# Example 3: Access to CPU registers. Subset of STM32F4xx WWDG block


WWDG_LAYOUT = {
(continues on next page)

1.2. MicroPython-specific libraries 115


MicroPython Documentation, Release v1.22.0

(continued from previous page)


"WWDG_CR": (0, {
# BFUINT32 here means size of the WWDG_CR register
"WDGA": 7 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32,
"T": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32,
}),
"WWDG_CFR": (4, {
"EWI": 9 << uctypes.BF_POS | 1 << uctypes.BF_LEN | uctypes.BFUINT32,
"WDGTB": 7 << uctypes.BF_POS | 2 << uctypes.BF_LEN | uctypes.BFUINT32,
"W": 0 << uctypes.BF_POS | 7 << uctypes.BF_LEN | uctypes.BFUINT32,
}),
}

WWDG = uctypes.struct(0x40002c00, WWDG_LAYOUT)

WWDG.WWDG_CFR.WDGTB = 0b10
WWDG.WWDG_CR.WDGA = 1
print("Current counter:", WWDG.WWDG_CR.T)

Defining structure layout

Structure layout is defined by a “descriptor” - a Python dictionary which encodes field names as keys and other properties
required to access them as associated values:
{
"field1": <properties>,
"field2": <properties>,
...
}

Currently, uctypes requires explicit specification of offsets for each field. Offset are given in bytes from the structure
start.
Following are encoding examples for various field types:
• Scalar types:
"field_name": offset | uctypes.UINT32

in other words, the value is a scalar type identifier ORed with a field offset (in bytes) from the start of the structure.
• Recursive structures:
"sub": (offset, {
"b0": 0 | uctypes.UINT8,
"b1": 1 | uctypes.UINT8,
})

i.e. value is a 2-tuple, first element of which is an offset, and second is a structure descriptor dictionary (note: offsets
in recursive descriptors are relative to the structure it defines). Of course, recursive structures can be specified not
just by a literal dictionary, but by referring to a structure descriptor dictionary (defined earlier) by name.
• Arrays of primitive types:
"arr": (offset | uctypes.ARRAY, size | uctypes.UINT8),

i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar element type
ORed number of elements in the array.

116 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• Arrays of aggregate types:

"arr2": (offset | uctypes.ARRAY, size, {"b": 0 | uctypes.UINT8}),

i.e. value is a 3-tuple, first element of which is ARRAY flag ORed with offset, second is a number of elements in
the array, and third is a descriptor of element type.
• Pointer to a primitive type:

"ptr": (offset | uctypes.PTR, uctypes.UINT8),

i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, and second is a scalar element type.
• Pointer to an aggregate type:

"ptr2": (offset | uctypes.PTR, {"b": 0 | uctypes.UINT8}),

i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, second is a descriptor of type pointed
to.
• Bitfields:

"bitf0": offset | uctypes.BFUINT16 | lsbit << uctypes.BF_POS | bitsize << uctypes.


,→BF_LEN,

i.e. value is a type of scalar value containing given bitfield (typenames are similar to scalar types, but prefixes with
BF), ORed with offset for scalar value containing the bitfield, and further ORed with values for bit position and bit
length of the bitfield within the scalar value, shifted by BF_POS and BF_LEN bits, respectively. A bitfield position
is counted from the least significant bit of the scalar (having position of 0), and is the number of right-most bit of
a field (in other words, it’s a number of bits a scalar needs to be shifted right to extract the bitfield).
In the example above, first a UINT16 value will be extracted at offset 0 (this detail may be important when accessing
hardware registers, where particular access size and alignment are required), and then bitfield whose rightmost bit
is lsbit bit of this UINT16, and length is bitsize bits, will be extracted. For example, if lsbit is 0 and bitsize is 8, then
effectively it will access least-significant byte of UINT16.
Note that bitfield operations are independent of target byte endianness, in particular, example above will access
least-significant byte of UINT16 in both little- and big-endian structures. But it depends on the least significant bit
being numbered 0. Some targets may use different numbering in their native ABI, but uctypes always uses the
normalized numbering described above.

Module contents

class uctypes.struct(addr, descriptor, layout_type=NATIVE, / )


Instantiate a “foreign data structure” object based on structure address in memory, descriptor (encoded as a dic-
tionary), and layout type (see below).
uctypes.LITTLE_ENDIAN
Layout type for a little-endian packed structure. (Packed means that every field occupies exactly as many bytes as
defined in the descriptor, i.e. the alignment is 1).
uctypes.BIG_ENDIAN
Layout type for a big-endian packed structure.
uctypes.NATIVE
Layout type for a native structure - with data endianness and alignment conforming to the ABI of the system on
which MicroPython runs.

1.2. MicroPython-specific libraries 117


MicroPython Documentation, Release v1.22.0

uctypes.sizeof(struct, layout_type=NATIVE, / )
Return size of data structure in bytes. The struct argument can be either a structure class or a specific instantiated
structure object (or its aggregate field).
uctypes.addressof(obj)
Return address of an object. Argument should be bytes, bytearray or other object supporting buffer protocol (and
address of this buffer is what actually returned).
uctypes.bytes_at(addr, size)
Capture memory at the given address and size as bytes object. As bytes object is immutable, memory is actually
duplicated and copied into bytes object, so if memory contents change later, created object retains original value.
uctypes.bytearray_at(addr, size)
Capture memory at the given address and size as bytearray object. Unlike bytes_at() function above, memory is
captured by reference, so it can be both written too, and you will access current value at the given memory address.
uctypes.UINT8
uctypes.INT8
uctypes.UINT16
uctypes.INT16
uctypes.UINT32
uctypes.INT32
uctypes.UINT64
uctypes.INT64
Integer types for structure descriptors. Constants for 8, 16, 32, and 64 bit types are provided, both signed and
unsigned.
uctypes.FLOAT32
uctypes.FLOAT64
Floating-point types for structure descriptors.
uctypes.VOID
VOID is an alias for UINT8, and is provided to conveniently define C’s void pointers: (uctypes.PTR,
uctypes.VOID).
uctypes.PTR
uctypes.ARRAY
Type constants for pointers and arrays. Note that there is no explicit constant for structures, it’s implicit: an
aggregate type without PTR or ARRAY flags is a structure.

Structure descriptors and instantiating structure objects

Given a structure descriptor dictionary and its layout type, you can instantiate a specific structure instance at a given
memory address using uctypes.struct() constructor. Memory address usually comes from following sources:
• Predefined address, when accessing hardware registers on a baremetal system. Lookup these addresses in datasheet
for a particular MCU/SoC.
• As a return value from a call to some FFI (Foreign Function Interface) function.
• From uctypes.addressof(), when you want to pass arguments to an FFI function, or alternatively, to access
some data for I/O (for example, data read from a file or network socket).

118 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Structure objects

Structure objects allow accessing individual fields using standard dot notation: my_struct.substruct1.field1.
If a field is of scalar type, getting it will produce a primitive value (Python integer or float) corresponding to the value
contained in a field. A scalar field can also be assigned to.
If a field is an array, its individual elements can be accessed with the standard subscript operator [] - both read and
assigned to.
If a field is a pointer, it can be dereferenced using [0] syntax (corresponding to C * operator, though [0] works in C
too). Subscripting a pointer with other integer values but 0 are also supported, with the same semantics as in C.
Summing up, accessing structure fields generally follows the C syntax, except for pointer dereference, when you need to
use [0] operator instead of *.

Limitations

1. Accessing non-scalar fields leads to allocation of intermediate objects to represent them. This means that special
care should be taken to layout a structure which needs to be accessed when memory allocation is disabled (e.g. from an
interrupt). The recommendations are:
• Avoid accessing nested structures. For example, instead of mcu_registers.peripheral_a.register1,
define separate layout descriptors for each peripheral, to be accessed as peripheral_a.register1. Or just
cache a particular peripheral: peripheral_a = mcu_registers.peripheral_a. If a register consists
of multiple bitfields, you would need to cache references to a particular register: reg_a = mcu_registers.
peripheral_a.reg_a.
• Avoid other non-scalar data, like arrays. For example, instead of peripheral_a.register[0] use
peripheral_a.register0. Again, an alternative is to cache intermediate values, e.g. register0 =
peripheral_a.register[0].
2. Range of offsets supported by the uctypes module is limited. The exact range supported is considered an imple-
mentation detail, and the general suggestion is to split structure definitions to cover from a few kilobytes to a few dozen of
kilobytes maximum. In most cases, this is a natural situation anyway, e.g. it doesn’t make sense to define all registers of
an MCU (spread over 32-bit address space) in one structure, but rather a peripheral block by peripheral block. In some
extreme cases, you may need to split a structure in several parts artificially (e.g. if accessing native data structure with
multi-megabyte array in the middle, though that would be a very synthetic case).
The following libraries provide drivers for hardware components.

1.2.11 WM8960 – Driver for the WM8960 codec

This driver is used to control a WM8960 codec chip. It is a Python translation of the C-Code provided by NXP/Freescale
for their i.MX RT series of MCUs. Very little has been added, and just a few API related names were changed or added
to cope with the naming style of MicroPython.
The primary purpose of the driver is initialization and setting operation modes of the codec. It does not do the audio data
processing for the codec. That is the task of a separate driver.
The WM8960 supports an I2C interface, in addition to the audio interface. The connection depends on the interface used
and the number of devices in the system. For the I2C interface, SCL and SDA have to be connected, and of course GND
and Vcc. The I2C default address is 0x1A.

1.2. MicroPython-specific libraries 119


MicroPython Documentation, Release v1.22.0

Constructor

class WM8960(i2c, sample_rate, *, bits=16, swap=SWAP_NONE, route=ROUTE_PLAYBACK_RECORD,


left_input=INPUT_MIC3, right_input=INPUT_MIC2, sysclk_source=SYSCLK_MCLK,
mclk_freq=None, primary=False, adc_sync=SYNC_DAC, protocol=BUS_I2S,
i2c_address=WM8960_I2C_ADDR)
Create a WM8960 driver object, initialize the device with default settings and return the WM8960 object.
Only the first two arguments are mandatory. All others are optional. The arguments are:
• i2c is the I2C bus object.
• sample_rate is the audio sample rate. Acceptable values are 8000, 11025, 12000, 16000, 22050, 24000,
32000, 44100, 48000, 96000, 192000 and 384000. Note that not every I2S hardware will support all values.
• bits is the number of bits per audio word. Acceptable value are 16, 20, 24, and 32.
• swap swaps the left & right channel, if set; see below for options.
• route Setting the audio path in the codec; see below for options.
• left_input sets the audio source for the left input channel; see below for options.
• right_input sets the audio source for the right input channel; see below for options.
• play_source sets the audio target for the output audio; see below for options.
• sysclk_source controls whether the internal master clock called “sysclk” is directly taken from the MCLK
input or derived from it using an internal PLL. It is usually not required to change this.
• mclk_freq sets the mclk frequency applied to the MCLK pin of the codec. If not set, default values are used.
• primary lets the WM8960 act as primary or secondary device. The default setting is False. When set to
False, sample_rate and bits are controlled by the MCU.
• adc_sync sets which input is used for the ADC sync signal. The default is using the DACLRC pin.
• protocol sets the communication protocol. The default is I2S. See below for all options.
• i2c_address sets the I2C address of the WM8960, with default 0x1A.
If mclk_freq is not set the following default values are used:
• sysclk_source == SYSCLK_PLL: 11.2896 MHz for sample rates of 44100, 22050 and 11015 Hz, and 12.288
Mhz for sample rates < 48000, otherwise sample_rate * 256.
• sysclk_source == SYSCLK_MCLK: sample_rate * 256.
If the MCLK signal is applied using, for example,. a separate oscillator, it must be specified for proper operation.

Tables of parameter constants

Table 1: Swap Parameter


Value Name
0 SWAP_NONE
1 SWAP_INPUT
2 SWAP_OUTPUT

120 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Table 2: Protocol Parameter


Value Name
2 BUS_I2S
1 BUS_LEFT_JUSTIFIED
0 BUS_RIGHT_JUSTIFIED
3 BUS_PCMA
19 BUS_PCMB

Table 3: Input Source Parameter


Value Name Type
0 INPUT_CLOSED
1 INPUT_MIC1 Single ended
2 INPUT_MIC2 Differential
3 INPUT_MIC3 Differential
4 INPUT_LINE2
5 INPUT_LINE3

Table 4: Route Parameter


Value Name
0 ROUTE_BYPASS
1 ROUTE_PLAYBACK
2 ROUTE_PLAYBACK_RECORD
5 ROUTE_RECORD

Table 5: Master Clock Source Parameter


Value Name
0 SYSCLK_MCLK
1 SYSCLK_PLL

Table 6: Module Names


Value Name
0 MODULE_ADC
1 MODULE_DAC
2 MODULE_VREF
3 MODULE_HEADPHONE
4 MODULE_MIC_BIAS
5 MODULE_MIC
6 MODULE_LINE_IN
7 MODULE_LINE_OUT
8 MODULE_SPEAKER
9 MODULE_OMIX
10 MODULE_MONO_OUT

1.2. MicroPython-specific libraries 121


MicroPython Documentation, Release v1.22.0

Table 7: Play Channel Names


Value Name
1 PLAY_HEADPHONE_LEFT
2 PLAY_HEADPHONE_RIGHT
4 PLAY_SPEAKER_LEFT
8 PLAY_SPEAKER_RIGHT

Table 8: adc_sync Parameters


Value Name
0 SYNC_ADC
1 SYNC_DAC

Methods

In addition to initialization, the driver provides some useful methods for controlling its operation:
WM8960.set_left_input(input_source)
Specify the source for the left input. The input source names are listed above.
WM8960.set_right_input(input_source)
Specify the source for the right input. The input source names are listed above.
WM8960.volume(module, volume_l=None, volume_r=None)
Sets or gets the volume of a certain module.
If no volume values are supplied, the actual volume tuple is returned.
If one or two values are supplied, it sets the volume of a certain module. If two values are provided, the first one is
used for the left channel, the second for the right channel. If only one value is supplied, it is used for both channels.
The value range is normalized to 0.0-100.0 with a logarithmic scale.
For a list of suitable modules and db/step, see the table below.

Table 9: Module Names and dB steps


dB/Step Name
1.28 MODULE_ADC
1.28 MODULE_DAC
0.8 MODULE_HEADPHONE
0.475 MODULE_LINE_IN
0.8 MODULE_SPEAKER

WM8960.mute(module, mute, soft=True, ramp=wm8960.MUTE_FAST)


Mute or unmute the output. If mute is True, the output is muted, if False it is unmuted.
If soft is set as True, muting will happen as a soft transition. The time for the transition is defined by ramp, which
is either MUTE_FAST or MUTE_SLOW.
WM8960.set_data_route(route)
Set the audio data route. For the parameter value/names, see the table above.

122 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

WM8960.set_module(module, active)
Enable or disable a module, with active being False or True. For the list of module names, see the table above.
Note that enabling MODULE_MONO_OUT is different from the WM8960.mono method. The first enables output
3, while the WM8960.mono method sends a mono mix to the left and right output.
WM8960.enable_module(module)
Enable a module. For the list of module names, see the table above.
WM8960.disable_module(module)
Disable a module. For the list of module names, see the table above.
WM8960.expand_3d(level)
Enable Stereo 3D expansion. level is a number between 0 and 15. A value of 0 disables the expansion.
WM8960.mono(active)
If active is True, a Mono mix is sent to the left and right output channel. This is different from enabling the
MODULE_MONO_MIX, which enables output 3.
WM8960.alc_mode(channel, mode=ALC_MODE)
Enables or disables ALC mode. Parameters are:
• channel enables and sets the channel for ALC. The parameter values are:
– ALC_OFF: Switch ALC off
– ALS_RIGHT: Use the right input channel
– ALC_LEFT: Use the left input channel
– ALC_STEREO: Use both input channels.
• mode sets the ALC mode. Input values are:
– ALC_MODE: act as ALC
– ALC_LIMITER: act as limiter.
WM8960.alc_gain(target=-12, max_gain=30, min_gain=-17.25, noise_gate=-78)
Set the target level, highest and lowest gain levels and the noise gate as dB level. Permitted ranges are:
• target: -22.5 to -1.5 dB
• max_gain: -12 to 30 dB
• min_gain: -17 to 25 dB
• noise_gate: -78 to -30 dB
Excess values are limited to the permitted ranges. A value of -78 or less for noise_gate disables the noise gate
function.
WM8960.alc_time(attack=24, decay=192, hold=0)
Set the dynamic characteristic of ALC. The times are given as millisecond values. Permitted ranges are:
• attack: 6 to 6140
• decay: 24 to 24580
• hold: 0 to 43000
Excess values are limited within the permitted ranges.

1.2. MicroPython-specific libraries 123


MicroPython Documentation, Release v1.22.0

WM8960.deemphasis(active)
Enables or disables a deemphasis filter for playback, with active being False or True. This filter is applied only
for sample rates of 32000, 44100 and 48000. For other sample rates, the filter setting is silently ignored.
WM8960.deinit()
Disable all modules.

Examples

Run WM8960 in secondary mode (default):

# Micro_python WM8960 Codec driver


#
# Setting the driver to Slave mode using the default settings
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, 32000, left_input=wm8960.INPUT_MIC1)
wm.set_volume(wm8960.MODULE_HEADPHONE, 100)

Run WM8960 in primary mode:

# Micro_python WM8960 Codec driver


#
# Setting the driver to Master mode using specific audio format settings
#
from machine import Pin, I2C
import wm8960

i2c = I2C(0)
wm=wm8960.WM8960(i2c, 44100, primary=True, bits=16)

Run WM8960 on a MIMXRT10xx_DEV board in secondary mode (default):

# Micro_python WM8960 Codec driver


#
# Setting the driver to Slave mode using the default settings
# swap the input channels such that a MIMXRT Dev board mic, which
# is connected to the right input, is assigned to the left audio channel.
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, sample_rate=16_000,
adc_sync=wm8960.SYNC_DAC,
swap=wm8960.SWAP_INPUT,
sysclk_source=wm8960.SYSCLK_MCLK)

Record with a Sparkfun WM8960 breakout board with Teensy in secondary mode (default):

# Micro_python WM8960 Codec driver


#
# The breakout board uses a fixed 24MHz MCLK. Therefore the internal
# PLL must be used as sysclk, which is the master audio clock.
# The Sparkfun board has the WS pins for RX and TX connected on the
(continues on next page)

124 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)


# board. Therefore adc_sync must be set to sync_adc, to configure
# it's ADCLRC pin as input.
#
from machine import Pin, I2C
import wm8960
i2c = I2C(0)
wm=wm8960.WM8960(i2c, sample_rate=16_000,
adc_sync=wm8960.SYNC_ADC,
sysclk_source=wm8960.SYSCLK_PLL,
mclk_freq=24_000_000,
left_input=wm8960.INPUT_MIC1,
right_input=wm8960.INPUT_CLOSED)

Play with a Sparkfun WM8960 breakout board with Teensy in secondary mode (default):

# The breakout board uses a fixed 24MHz MCLK. Therefore the internal
# PLL must be used as sysclk, which is the master audio clock.
# The Sparkfun board has the WS pins for RX and TX connected on the
# board. Therefore adc_sync must be set to sync_adc, to configure
# it's ADCLRC pin as input.

from machine import I2C


i2c=I2C(0)
import wm8960
wm=wm8960.WM8960(i2c, sample_rate=44_100,
adc_sync=wm8960.SYNC_ADC,
sysclk_source=wm8960.SYSCLK_PLL,
mclk_freq=24_000_000)
wm.set_volume(wm8960.MODULE_HEADPHONE, 100)

1.3 Port-specific libraries

In some cases the following port/board-specific libraries have functions or classes similar to those in the machine library.
Where this occurs, the entry in the port specific library exposes hardware functionality unique to that platform.
To write portable code use functions and classes from the machine module. To access platform-specific hardware use
the appropriate library, e.g. pyb in the case of the Pyboard.

1.3. Port-specific libraries 125


MicroPython Documentation, Release v1.22.0

1.3.1 Libraries specific to the pyboard

The following libraries are specific to the pyboard.

pyb — functions related to the board

The pyb module contains specific functions related to the board.

Time related functions

pyb.delay(ms)
Delay for the given number of milliseconds.
pyb.udelay(us)
Delay for the given number of microseconds.
pyb.millis()
Returns the number of milliseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days)
this will start to return negative numbers.
Note that if pyb.stop() is issued the hardware counter supporting this function will pause for the duration of
the “sleeping” state. This will affect the outcome of pyb.elapsed_millis().
pyb.micros()
Returns the number of microseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8 min-
utes) this will start to return negative numbers.
Note that if pyb.stop() is issued the hardware counter supporting this function will pause for the duration of
the “sleeping” state. This will affect the outcome of pyb.elapsed_micros().
pyb.elapsed_millis(start)
Returns the number of milliseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods up to about 12.4 days.
Example:
start = pyb.millis()
while pyb.elapsed_millis(start) < 1000:
# Perform some operation

pyb.elapsed_micros(start)
Returns the number of microseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods up to about 17.8 minutes.
Example:
start = pyb.micros()
while pyb.elapsed_micros(start) < 1000:
# Perform some operation
pass

126 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Reset related functions

pyb.hard_reset()
Resets the pyboard in a manner similar to pushing the external RESET button.
pyb.bootloader()
Activate the bootloader without BOOT* pins.
pyb.fault_debug(value)
Enable or disable hard-fault debugging. A hard-fault is when there is a fatal error in the underlying system, like an
invalid memory access.
If the value argument is False then the board will automatically reset if there is a hard fault.
If value is True then, when the board has a hard fault, it will print the registers and the stack trace, and then cycle
the LEDs indefinitely.
The default value is disabled, i.e. to automatically reset.

Interrupt related functions

pyb.disable_irq()
Disable interrupt requests. Returns the previous IRQ state: False/True for disabled/enabled IRQs respectively.
This return value can be passed to enable_irq to restore the IRQ to its original state.
pyb.enable_irq(state=True)
Enable interrupt requests. If state is True (the default value) then IRQs are enabled. If state is False then
IRQs are disabled. The most common use of this function is to pass it the value returned by disable_irq to
exit a critical section.

Power related functions

pyb.freq([sysclk[, hclk[, pclk1[, pclk2 ]]]])


If given no arguments, returns a tuple of clock frequencies: (sysclk, hclk, pclk1, pclk2). These correspond to:
• sysclk: frequency of the CPU
• hclk: frequency of the AHB bus, core memory and DMA
• pclk1: frequency of the APB1 bus
• pclk2: frequency of the APB2 bus
If given any arguments then the function sets the frequency of the CPU, and the buses if additional arguments are
given. Frequencies are given in Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note that
not all values are supported and the largest supported frequency not greater than the given value will be selected.
Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 72, 84, 96, 108, 120,
144, 168.
The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is 84MHz. Be sure not to set
frequencies above these values.
The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency using a prescaler (divider). Supported
prescalers for hclk are: 1, 2, 4, 8, 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1, 2, 4, 8.
A prescaler will be chosen to best match the requested frequency.

1.3. Port-specific libraries 127


MicroPython Documentation, Release v1.22.0

A sysclk frequency of 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI (internal oscillator)
directly. The higher frequencies use the HSE to drive the PLL (phase locked loop), and then use the output of the
PLL.
Note that if you change the frequency while the USB is enabled then the USB may become unreliable. It is best
to change the frequency in boot.py, before the USB peripheral is started. Also note that sysclk frequencies below
36MHz do not allow the USB to function correctly.
pyb.wfi()
Wait for an internal or external interrupt.
This executes a wfi instruction which reduces power consumption of the MCU until any interrupt occurs (be it
internal or external), at which point execution continues. Note that the system-tick interrupt occurs once every
millisecond (1000Hz) so this function will block for at most 1ms.
pyb.stop()
Put the pyboard in a “sleeping” state.
This reduces power consumption to less than 500 uA. To wake from this sleep state requires an external interrupt
or a real-time-clock event. Upon waking execution continues where it left off.
See rtc.wakeup() to configure a real-time-clock wakeup event.
pyb.standby()
Put the pyboard into a “deep sleep” state.
This reduces power consumption to less than 50 uA. To wake from this sleep state requires a real-time-clock event,
or an external interrupt on X1 (PA0=WKUP) or X18 (PC13=TAMP1). Upon waking the system undergoes a hard
reset.
See rtc.wakeup() to configure a real-time-clock wakeup event.

Miscellaneous functions

pyb.have_cdc()
Return True if USB is connected as a serial device, False otherwise.

Note: This function is deprecated. Use pyb.USB_VCP().isconnected() instead.

pyb.hid((buttons, x, y, z))
Takes a 4-tuple (or list) and sends it to the USB host (the PC) to signal a HID mouse-motion event.

Note: This function is deprecated. Use pyb.USB_HID.send() instead.

pyb.info([dump_alloc_table ])
Print out lots of information about the board.
pyb.main(filename)
Set the filename of the main script to run after boot.py is finished. If this function is not called then the default file
main.py will be executed.
It only makes sense to call this function from within boot.py.

128 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

pyb.mount(device, mountpoint, *, readonly=False, mkfs=False)

Note: This function is deprecated. Mounting and unmounting devices should be performed by os.mount()
and os.umount() instead.

Mount a block device and make it available as part of the filesystem. device must be an object that provides the
block protocol. (The following is also deprecated. See os.AbstractBlockDev for the correct way to create
a block device.)
• readblocks(self, blocknum, buf)
• writeblocks(self, blocknum, buf) (optional)
• count(self)
• sync(self) (optional)
readblocks and writeblocks should copy data between buf and the block device, starting from block
number blocknum on the device. buf will be a bytearray with length a multiple of 512. If writeblocks is
not defined then the device is mounted read-only. The return value of these two functions is ignored.
count should return the number of blocks available on the device. sync, if implemented, should sync the data
on the device.
The parameter mountpoint is the location in the root of the filesystem to mount the device. It must begin with
a forward-slash.
If readonly is True, then the device is mounted read-only, otherwise it is mounted read-write.
If mkfs is True, then a new filesystem is created if one does not already exist.
pyb.repl_uart(uart)
Get or set the UART object where the REPL is repeated on.
pyb.rng()
Return a 30-bit hardware generated random number.
pyb.sync()
Sync all file systems.
pyb.unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU.
pyb.usb_mode([modestr, ]port=-1, vid=0xf055, pid=-1, msc=(), hid=pyb.hid_mouse, high_speed=False)
If called with no arguments, return the current USB mode as a string.
If called with modestr provided, attempts to configure the USB mode. The following values of modestr are under-
stood:
• None: disables USB
• 'VCP': enable with VCP (Virtual COM Port) interface
• 'MSC': enable with MSC (mass storage device class) interface
• 'VCP+MSC': enable with VCP and MSC
• 'VCP+HID': enable with VCP and HID (human interface device)
• 'VCP+MSC+HID': enabled with VCP, MSC and HID (only available on PYBD boards)

1.3. Port-specific libraries 129


MicroPython Documentation, Release v1.22.0

For backwards compatibility, 'CDC' is understood to mean 'VCP' (and similarly for 'CDC+MSC' and
'CDC+HID').
The port parameter should be an integer (0, 1, …) and selects which USB port to use if the board supports multiple
ports. A value of -1 uses the default or automatically selected port.
The vid and pid parameters allow you to specify the VID (vendor id) and PID (product id). A pid value of -1 will
select a PID based on the value of modestr.
If enabling MSC mode, the msc parameter can be used to specify a list of SCSI LUNs to expose on the mass storage
interface. For example msc=(pyb.Flash(), pyb.SDCard()).
If enabling HID mode, you may also specify the HID details by passing the hid keyword parameter. It takes a tuple
of (subclass, protocol, max packet length, polling interval, report descriptor). By default it will set appropriate
values for a USB mouse. There is also a pyb.hid_keyboard constant, which is an appropriate tuple for a USB
keyboard.
The high_speed parameter, when set to True, enables USB HS mode if it is supported by the hardware.

Constants

pyb.hid_mouse
pyb.hid_keyboard
A tuple of (subclass, protocol, max packet length, polling interval, report descriptor) to set appropriate values for
a USB mouse or keyboard.

Classes

class Accel – accelerometer control

Accel is an object that controls the accelerometer. Example usage:

accel = pyb.Accel()
for i in range(10):
print(accel.x(), accel.y(), accel.z())

Raw values are between -32 and 31.

Constructors

class pyb.Accel
Create and return an accelerometer object.

130 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Methods

Accel.filtered_xyz()
Get a 3-tuple of filtered x, y and z values.
Implementation note: this method is currently implemented as taking the sum of 4 samples, sampled from the 3
previous calls to this function along with the sample from the current call. Returned values are therefore 4 times
the size of what they would be from the raw x(), y() and z() calls.
Accel.tilt()
Get the tilt register.
Accel.x()
Get the x-axis value.
Accel.y()
Get the y-axis value.
Accel.z()
Get the z-axis value.

Hardware Note

The accelerometer uses I2C bus 1 to communicate with the processor. Consequently when readings are being taken pins
X9 and X10 should be unused (other than for I2C). Other devices using those pins, and which therefore cannot be used
concurrently, are UART 1 and Timer 4 channels 1 and 2.

class ADC – analog to digital conversion

Usage:

import pyb

adc = pyb.ADC(pin) # create an analog object from a pin


val = adc.read() # read an analog value

adc = pyb.ADCAll(resolution) # create an ADCAll object


adc = pyb.ADCAll(resolution, mask) # create an ADCAll object for selected analog␣
,→channels

val = adc.read_channel(channel) # read the given channel


val = adc.read_core_temp() # read MCU temperature
val = adc.read_core_vbat() # read MCU VBAT
val = adc.read_core_vref() # read MCU VREF
val = adc.read_vref() # read MCU supply voltage

1.3. Port-specific libraries 131


MicroPython Documentation, Release v1.22.0

Constructors

class pyb.ADC(pin)
Create an ADC object associated with the given pin. This allows you to then read analog values on that pin.

Methods

ADC.read()
Read the value on the analog pin and return it. The returned value will be between 0 and 4095.
ADC.read_timed(buf, timer)
Read analog values into buf at a rate set by the timer object.
buf can be bytearray or array.array for example. The ADC values have 12-bit resolution and are stored directly
into buf if its element size is 16 bits or greater. If buf has only 8-bit elements (eg a bytearray) then the sample
resolution will be reduced to 8 bits.
timer should be a Timer object, and a sample is read each time the timer triggers. The timer must already be
initialised and running at the desired sampling frequency.
To support previous behaviour of this function, timer can also be an integer which specifies the frequency (in Hz)
to sample at. In this case Timer(6) will be automatically configured to run at the given frequency.
Example using a Timer object (preferred way):

adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19


tim = pyb.Timer(6, freq=10) # create a timer running at 10Hz
buf = bytearray(100) # creat a buffer to store the samples
adc.read_timed(buf, tim) # sample 100 values, taking 10s

Example using an integer for the frequency:

adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19


buf = bytearray(100) # create a buffer of 100 bytes
adc.read_timed(buf, 10) # read analog values into buf at 10Hz
# this will take 10 seconds to finish
for val in buf: # loop over all values
print(val) # print the value out

This function does not allocate any heap memory. It has blocking behaviour: it does not return to the calling
program until the buffer is full.
ADC.read_timed_multi((adcx, adcy, ...), (bufx, bufy, ...), timer)
This is a static method. It can be used to extract relative timing or phase data from multiple ADC’s.
It reads analog values from multiple ADC’s into buffers at a rate set by the timer object. Each time the timer triggers
a sample is rapidly read from each ADC in turn.
ADC and buffer instances are passed in tuples with each ADC having an associated buffer. All buffers must be of
the same type and length and the number of buffers must equal the number of ADC’s.
Buffers can be bytearray or array.array for example. The ADC values have 12-bit resolution and are
stored directly into the buffer if its element size is 16 bits or greater. If buffers have only 8-bit elements (eg a
bytearray) then the sample resolution will be reduced to 8 bits.
timer must be a Timer object. The timer must already be initialised and running at the desired sampling frequency.
Example reading 3 ADC’s:

132 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

adc0 = pyb.ADC(pyb.Pin.board.X1) # Create ADC's


adc1 = pyb.ADC(pyb.Pin.board.X2)
adc2 = pyb.ADC(pyb.Pin.board.X3)
tim = pyb.Timer(8, freq=100) # Create timer
rx0 = array.array('H', (0 for i in range(100))) # ADC buffers of
rx1 = array.array('H', (0 for i in range(100))) # 100 16-bit words
rx2 = array.array('H', (0 for i in range(100)))
# read analog values into buffers at 100Hz (takes one second)
pyb.ADC.read_timed_multi((adc0, adc1, adc2), (rx0, rx1, rx2), tim)
for n in range(len(rx0)):
print(rx0[n], rx1[n], rx2[n])

This function does not allocate any heap memory. It has blocking behaviour: it does not return to the calling
program until the buffers are full.
The function returns True if all samples were acquired with correct timing. At high sample rates the time taken
to acquire a set of samples can exceed the timer period. In this case the function returns False, indicating a loss
of precision in the sample interval. In extreme cases samples may be missed.
The maximum rate depends on factors including the data width and the number of ADC’s being read. In testing
two ADC’s were sampled at a timer rate of 210kHz without overrun. Samples were missed at 215kHz. For three
ADC’s the limit is around 140kHz, and for four it is around 110kHz. At high sample rates disabling interrupts for
the duration can reduce the risk of sporadic data loss.

The ADCAll Object

Instantiating this changes all masked ADC pins to analog inputs. The preprocessed MCU temperature, VREF and VBAT
data can be accessed on ADC channels 16, 17 and 18 respectively. Appropriate scaling is handled according to reference
voltage used (usually 3.3V). The temperature sensor on the chip is factory calibrated and allows to read the die temperature
to +/- 1 degree centigrade. Although this sounds pretty accurate, don’t forget that the MCU’s internal temperature is
measured. Depending on processing loads and I/O subsystems active the die temperature may easily be tens of degrees
above ambient temperature. On the other hand a pyboard woken up after a long standby period will show correct ambient
temperature within limits mentioned above.
The ADCAll read_core_vbat(), read_vref() and read_core_vref() methods read the backup battery
voltage, reference voltage and the (1.21V nominal) reference voltage using the actual supply as a reference. All results
are floating point numbers giving direct voltage values.
read_core_vbat() returns the voltage of the backup battery. This voltage is also adjusted according to the actual
supply voltage. To avoid analog input overload the battery voltage is measured via a voltage divider and scaled according
to the divider value. To prevent excessive loads to the backup battery, the voltage divider is only active during ADC
conversion.
read_vref() is evaluated by measuring the internal voltage reference and backscale it using factory calibration value
of the internal voltage reference. In most cases the reading would be close to 3.3V. If the pyboard is operated from a
battery, the supply voltage may drop to values below 3.3V. The pyboard will still operate fine as long as the operating
conditions are met. With proper settings of MCU clock, flash access speed and programming mode it is possible to run
the pyboard down to 2 V and still get useful ADC conversion.
It is very important to make sure analog input voltages never exceed actual supply voltage.
Other analog input channels (0..15) will return unscaled integer values according to the selected precision.
To avoid unwanted activation of analog inputs (channel 0..15) a second parameter can be specified. This parameter is
a binary pattern where each requested analog input has the corresponding bit set. The default value is 0xffffffff which
means all analog inputs are active. If just the internal channels (16..18) are required, the mask value should be 0x70000.
Example:

1.3. Port-specific libraries 133


MicroPython Documentation, Release v1.22.0

adcall = pyb.ADCAll(12, 0x70000) # 12 bit resolution, internal channels


temp = adcall.read_core_temp()

class CAN – controller area network communication bus

CAN implements support for classic CAN (available on F4, F7 MCUs) and CAN FD (H7 series) controllers. At the
physical level CAN bus consists of 2 lines: RX and TX. Note that to connect the pyboard to a CAN bus you must use a
CAN transceiver to convert the CAN logic signals from the pyboard to the correct voltage levels on the bus.
Example usage for classic CAN controller in Loopback (transceiver-less) mode:

from pyb import CAN


can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive␣
,→messages with id=123, 124, 125 and 126

can.send('message!', 123) # send a message with id 123


can.recv(0) # receive message on FIFO 0

Example usage for CAN FD controller with all of the possible options enabled:

# FD frame + BRS mode + Extended frame ID. 500 Kbit/s for arbitration phase, 1Mbit/s␣
,→for data phase.

can = CAN(1, CAN.NORMAL, baudrate=500_000, brs_baudrate=1_000_000, sample_point=80)


can.setfilter(0, CAN.RANGE, 0, (0xFFF0, 0xFFFF))
can.send('a'*64, 0xFFFF, fdf=True, brs=True, extframe=True)
can.recv(0)

The following CAN module functions and their arguments are available for both classic and FD CAN controllers, unless
otherwise stated.

Constructors

class pyb.CAN(bus, ...)


Construct a CAN object on the given bus. bus can be 1-2, or 'YA' or 'YB'. With no additional parameters, the
CAN object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra
arguments are given, the bus is initialised. See CAN.init() for parameters of initialisation.
The physical pins of the CAN buses are:
• CAN(1) is on YA: (RX, TX) = (Y3, Y4) = (PB8, PB9)
• CAN(2) is on YB: (RX, TX) = (Y5, Y6) = (PB12, PB13)

Methods

CAN.init(mode, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False,


baudrate=0, sample_point=75,
num_filter_banks=14, brs_sjw=1, brs_bs1=8, brs_bs2=3, brs_baudrate=0,
brs_sample_point=75)
Initialise the CAN bus with the given parameters:
• mode is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK

134 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• prescaler is the value by which the CAN input clock is divided to generate the nominal bit time quanta. The
prescaler can be a value between 1 and 1024 inclusive for classic CAN, and between 1 and 512 inclusive for
CAN FD.
• sjw is the resynchronisation jump width in units of time quanta for nominal bits; it can be a value between 1
and 4 inclusive for classic CAN, and between 1 and 128 inclusive for CAN FD.
• bs1 defines the location of the sample point in units of the time quanta for nominal bits; it can be a value
between 1 and 16 inclusive for classic CAN, and between 2 and 256 inclusive for CAN FD.
• bs2 defines the location of the transmit point in units of the time quanta for nominal bits; it can be a value
between 1 and 8 inclusive for classic CAN, and between 2 and 128 inclusive for CAN FD.
• auto_restart sets whether the controller will automatically try and restart communications after entering the
bus-off state; if this is disabled then restart() can be used to leave the bus-off state
• baudrate if a baudrate other than 0 is provided, this function will try to automatically calculate the CAN nom-
inal bit time (overriding prescaler, bs1 and bs2) that satisfies both the baudrate and the desired sample_point.
• sample_point given in a percentage of the nominal bit time, the sample_point specifies the position of the bit
sample with respect to the whole nominal bit time. The default sample_point is 75%.
• num_filter_banks for classic CAN, this is the number of banks that will be assigned to CAN(1), the rest of
the 28 are assigned to CAN(2).
• brs_prescaler is the value by which the CAN FD input clock is divided to generate the data bit time quanta.
The prescaler can be a value between 1 and 32 inclusive.
• brs_sjw is the resynchronisation jump width in units of time quanta for data bits; it can be a value between 1
and 16 inclusive
• brs_bs1 defines the location of the sample point in units of the time quanta for data bits; it can be a value
between 1 and 32 inclusive
• brs_bs2 defines the location of the transmit point in units of the time quanta for data bits; it can be a value
between 1 and 16 inclusive
• brs_baudrate if a baudrate other than 0 is provided, this function will try to automatically calculate the CAN
data bit time (overriding brs_prescaler, brs_bs1 and brs_bs2) that satisfies both the baudrate and the desired
brs_sample_point.
• brs_sample_point given in a percentage of the data bit time, the brs_sample_point specifies the position of the
bit sample with respect to the whole data bit time. The default brs_sample_point is 75%.
The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN prescaler value divided by PCLK1
(the frequency of internal peripheral bus 1); see pyb.freq() to determine PCLK1.
A single bit is made up of the synchronisation segment, which is always 1 tq. Then follows bit segment 1, then bit
segment 2. The sample point is after bit segment 1 finishes. The transmit point is after bit segment 2 finishes. The
baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied by the time quanta tq.
For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of tq is 2.38 microseconds.
The bittime is 35.7 microseconds, and the baudrate is 28kHz.
See page 680 of the STM32F405 datasheet for more details.
CAN.deinit()
Turn off the CAN bus.
CAN.restart()
Force a software restart of the CAN controller without resetting its configuration.

1.3. Port-specific libraries 135


MicroPython Documentation, Release v1.22.0

If the controller enters the bus-off state then it will no longer participate in bus activity. If the controller is not
configured to automatically restart (see init()) then this method can be used to trigger a restart, and the controller
will follow the CAN protocol to leave the bus-off state and go into the error active state.
CAN.state()
Return the state of the controller. The return value can be one of:
• CAN.STOPPED – the controller is completely off and reset;
• CAN.ERROR_ACTIVE – the controller is on and in the Error Active state (both TEC and REC are less than
96);
• CAN.ERROR_WARNING – the controller is on and in the Error Warning state (at least one of TEC or REC
is 96 or greater);
• CAN.ERROR_PASSIVE – the controller is on and in the Error Passive state (at least one of TEC or REC is
128 or greater);
• CAN.BUS_OFF – the controller is on but not participating in bus activity (TEC overflowed beyond 255).
CAN.info([list ])
Get information about the controller’s error states and TX and RX buffers. If list is provided then it should be a list
object with at least 8 entries, which will be filled in with the information. Otherwise a new list will be created and
filled in. In both cases the return value of the method is the populated list.
The values in the list are:
• TEC value
• REC value
• number of times the controller enterted the Error Warning state (wrapped around to 0 after 65535)
• number of times the controller enterted the Error Passive state (wrapped around to 0 after 65535)
• number of times the controller enterted the Bus Off state (wrapped around to 0 after 65535)
• number of pending TX messages
• number of pending RX messages on fifo 0
• number of pending RX messages on fifo 1
CAN.setfilter(bank, mode, fifo, params, *, rtr, extframe=False)
Configure a filter bank:
• bank is the classic CAN controller filter bank, or CAN FD filter index, to configure.
• mode is the mode the filter should operate in, see the tables below.
• fifo is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
• params is an array of values the defines the filter. The contents of the array depends on the mode argument.

136 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

mode Contents of params array for classic CAN con-


troller
CAN.LIST16 Four 16 bit ids that will be accepted
CAN.LIST32 Two 32 bit ids that will be accepted
CAN.MASK16
Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4)
The first pair, 1 and 3 will accept all ids
that have bit 0 = 1 and bit 1 = 0.
The second pair, 4 and 4, will accept all ids
that have bit 2 = 1.

CAN.MASK32 As with CAN.MASK16 but with only one 32 bit


id/mask pair.

mode Contents of params array for CAN FD controller


CAN.RANGE Two ids that represent a range of accepted ids.
CAN.DUAL Two ids that will be accepted. For example (1, 2)
CAN.MASK One filter ID and a mask. For example (0x111, 0x7FF)

• rtr For classic CAN controllers, this is an array of booleans that states if a filter should accept a remote
transmission request message. If this argument is not given then it defaults to False for all entries. The
length of the array depends on the mode argument. For CAN FD, this argument is ignored.

mode length of rtr array


CAN.LIST16 4
CAN.LIST32 2
CAN.MASK16 2
CAN.MASK32 1

• extframe If True the frame will have an extended identifier (29 bits), otherwise a standard identifier (11 bits)
is used.

CAN.clearfilter(bank, extframe=False)
Clear and disables a filter bank:
• bank is the classic CAN controller filter bank, or CAN FD filter index, to clear.
• extframe For CAN FD controllers, if True, clear an extended filter (configured with extframe=True), other-
wise the clear a standard identifier (configured with extframe=False).
CAN.any(fifo)
Return True if any message waiting on the FIFO, else False.
CAN.recv(fifo, list=None, *, timeout=5000)
Receive data on the bus:
• fifo is an integer, which is the FIFO to receive on
• list is an optional list object to be used as the return value

1.3. Port-specific libraries 137


MicroPython Documentation, Release v1.22.0

• timeout is the timeout in milliseconds to wait for the receive.


Return value: A tuple containing five values.
• The id of the message.
• A boolean that indicates if the message ID is standard or extended.
• A boolean that indicates if the message is an RTR message.
• The FMI (Filter Match Index) value.
• An array containing the data.
If list is None then a new tuple will be allocated, as well as a new bytes object to contain the data (as the fifth
element in the tuple).
If list is not None then it should be a list object with a least five elements. The fifth element should be a memoryview
object which is created from either a bytearray or an array of type ‘B’ or ‘b’, and this array must have enough room
for at least 8 bytes. The list object will then be populated with the first four return values above, and the memoryview
object will be resized inplace to the size of the data and filled in with that data. The same list and memoryview
objects can be reused in subsequent calls to this method, providing a way of receiving data without using the heap.
For example:

buf = bytearray(8)
lst = [0, 0, 0, 0, memoryview(buf)]
# No heap memory is allocated in the following call
can.recv(0, lst)

CAN.send(data, id, *, timeout=0, rtr=False, extframe=False, fdf=False, brs=False)


Send a message on the bus:
• data is the data to send (an integer to send, or a buffer object).
• id is the id of the message to be sent.
• timeout is the timeout in milliseconds to wait for the send.
• rtr is a boolean that specifies if the message shall be sent as a remote transmission request. If rtr
is True then only the length of data is used to fill in the DLC slot of the frame; the actual bytes in
data are unused.
• extframe if True the frame will have an extended identifier (29 bits), otherwise a standard identifier
(11 bits) is used.
• fdf for CAN FD controllers, if set to True, the frame will have an FD frame format, which supports
data payloads up to 64 bytes.
• brs for CAN FD controllers, if set to True, the bitrate switching mode is enabled, in which the data
phase is transmitted at a different bitrate. See CAN.init() for the data bit timing configuration
parameters.
If timeout is 0 the message is placed in a buffer in one of three hardware buffers and the method returns
immediately. If all three buffers are in use an exception is thrown. If timeout is not 0, the method
waits until the message is transmitted. If the message can’t be transmitted within the specified time an
exception is thrown.
Return value: None.
CAN.rxcallback(fifo, fun)
Register a function to be called when a message is accepted into a empty fifo:
• fifo is the receiving fifo.

138 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• fun is the function to be called when the fifo becomes non empty.
The callback function takes two arguments the first is the can object it self the second is a integer that indicates the
reason for the callback.

Reason
0 A message has been accepted into a empty FIFO.
1 The FIFO is full
2 A message has been lost due to a full FIFO

Example use of rxcallback:

def cb0(bus, reason):


print('cb0')
if reason == 0:
print('pending')
if reason == 1:
print('full')
if reason == 2:
print('overflow')

can = CAN(1, CAN.LOOPBACK)


can.rxcallback(0, cb0)

Constants

CAN.NORMAL
CAN.LOOPBACK
CAN.SILENT
CAN.SILENT_LOOPBACK
The mode of the CAN bus used in init().
CAN.STOPPED
CAN.ERROR_ACTIVE
CAN.ERROR_WARNING
CAN.ERROR_PASSIVE
CAN.BUS_OFF
Possible states of the CAN controller returned from state().
CAN.LIST16
CAN.MASK16
CAN.LIST32
CAN.MASK32
The operation mode of a filter used in setfilter() for classic CAN.
CAN.DUAL
CAN.RANGE
CAN.MASK
The operation mode of a filter used in setfilter() for CAN FD.

1.3. Port-specific libraries 139


MicroPython Documentation, Release v1.22.0

class DAC – digital to analog conversion

The DAC is used to output analog values (a specific voltage) on pin X5 or pin X6. The voltage will be between 0 and
3.3V.
This module will undergo changes to the API.
Example usage:

from pyb import DAC

dac = DAC(1) # create DAC 1 on pin X5


dac.write(128) # write a value to the DAC (makes X5 1.65V)

dac = DAC(1, bits=12) # use 12 bit resolution


dac.write(4095) # output maximum value, 3.3V

To output a continuous sine-wave:

import math
from pyb import DAC

# create a buffer containing a sine-wave


buf = bytearray(100)
for i in range(len(buf)):
buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf)))

# output the sine-wave at 400Hz


dac = DAC(1)
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)

To output a continuous sine-wave at 12-bit resolution:

import math
from array import array
from pyb import DAC

# create a buffer containing a sine-wave, using half-word samples


buf = array('H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in␣
,→range(128))

# output the sine-wave at 400Hz


dac = DAC(1, bits=12)
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)

Constructors

class pyb.DAC(port, bits=8, *, buffering=None)


Construct a new DAC object.
port can be a pin object, or an integer (1 or 2). DAC(1) is on pin X5 and DAC(2) is on pin X6.
bits is an integer specifying the resolution, and can be 8 or 12. The maximum value for the write and write_timed
methods will be 2**``bits``-1.
The buffering parameter selects the behaviour of the DAC op-amp output buffer, whose purpose is to reduce the out-
put impedance. It can be None to select the default (buffering enabled for DAC.noise(), DAC.triangle()

140 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

and DAC.write_timed(), and disabled for DAC.write()), False to disable buffering completely, or
True to enable output buffering.
When buffering is enabled the DAC pin can drive loads down to 5KΩ. Otherwise it has an output impedance of
15KΩ maximum: consequently to achieve a 1% accuracy without buffering requires the applied load to be less than
1.5MΩ. Using the buffer incurs a penalty in accuracy, especially near the extremes of range.

Methods

DAC.init(bits=8, *, buffering=None)
Reinitialise the DAC. bits can be 8 or 12. buffering can be None, False or True; see above constructor for the
meaning of this parameter.
DAC.deinit()
De-initialise the DAC making its pin available for other uses.
DAC.noise(freq)
Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given frequency.
DAC.triangle(freq)
Generate a triangle wave. The value on the DAC output changes at the given frequency and ramps through the full
12-bit range (up and down). Therefore the frequency of the repeating triangle wave itself is 8192 times smaller.
DAC.write(value)
Direct access to the DAC output. The minimum value is 0. The maximum value is 2**``bits``-1, where bits is
set when creating the DAC object or by using the init method.
DAC.write_timed(data, freq, *, mode=DAC.NORMAL)
Initiates a burst of RAM to DAC using a DMA transfer. The input data is treated as an array of bytes in 8-bit
mode, and an array of unsigned half-words (array typecode ‘H’) in 12-bit mode.
freq can be an integer specifying the frequency to write the DAC samples at, using Timer(6). Or it can be an
already-initialised Timer object which is used to trigger the DAC sample. Valid timers are 2, 4, 5, 6, 7 and 8.
mode can be DAC.NORMAL or DAC.CIRCULAR.
Example using both DACs at the same time:

dac1 = DAC(1)
dac2 = DAC(2)
dac1.write_timed(buf1, pyb.Timer(6, freq=100), mode=DAC.CIRCULAR)
dac2.write_timed(buf2, pyb.Timer(7, freq=200), mode=DAC.CIRCULAR)

Constants

DAC.NORMAL
NORMAL mode does a single transmission of the waveform in the data buffer,
DAC.CIRCULAR
CIRCULAR mode does a transmission of the waveform in the data buffer, and wraps around to the start of the
data buffer every time it reaches the end of the table.

1.3. Port-specific libraries 141


MicroPython Documentation, Release v1.22.0

class ExtInt – configure I/O pins to interrupt on external events

There are a total of 22 interrupt lines. 16 of these can come from GPIO pins and the remaining 6 are from internal
sources.
For lines 0 through 15, a given line can map to the corresponding line from an arbitrary port. So line 0 can map to Px0
where x is A, B, C, … and line 1 can map to Px1 where x is A, B, C, …

def callback(line):
print("line =", line)

Note: ExtInt will automatically configure the gpio line as an input.

extint = pyb.ExtInt(pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, callback)

Now every time a falling edge is seen on the X1 pin, the callback will be called. Caution: mechanical pushbuttons have
“bounce” and pushing or releasing a switch will often generate multiple edges. See: http://www.eng.utah.edu/~cs5780/
debouncing.pdf for a detailed explanation, along with various techniques for debouncing.
Trying to register 2 callbacks onto the same pin will throw an exception.
If pin is passed as an integer, then it is assumed to map to one of the internal interrupt sources, and must be in the range
16 through 22.
All other pin objects go through the pin mapper to come up with one of the gpio pins.

extint = pyb.ExtInt(pin, mode, pull, callback)

Valid modes are pyb.ExtInt.IRQ_RISING, pyb.ExtInt.IRQ_FALLING, pyb.ExtInt.IRQ_RISING_FALLING,


pyb.ExtInt.EVT_RISING, pyb.ExtInt.EVT_FALLING, and pyb.ExtInt.EVT_RISING_FALLING.
Only the IRQ_xxx modes have been tested. The EVT_xxx modes have something to do with sleep mode and the WFE
instruction.
Valid pull values are pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN, pyb.Pin.PULL_NONE.
There is also a C API, so that drivers which require EXTI interrupt lines can also use this code. See extint.h for the
available functions and usrsw.h for an example of using this.

Constructors

class pyb.ExtInt(pin, mode, pull, callback)


Create an ExtInt object:
• pin is the pin on which to enable the interrupt (can be a pin object or any valid pin name).
• mode can be one of: - ExtInt.IRQ_RISING - trigger on a rising edge; - ExtInt.IRQ_FALLING -
trigger on a falling edge; - ExtInt.IRQ_RISING_FALLING - trigger on a rising or falling edge.
• pull can be one of: - pyb.Pin.PULL_NONE - no pull up or down resistors; - pyb.Pin.PULL_UP -
enable the pull-up resistor; - pyb.Pin.PULL_DOWN - enable the pull-down resistor.
• callback is the function to call when the interrupt triggers. The callback function must accept exactly 1
argument, which is the line that triggered the interrupt.

142 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Class methods

classmethod ExtInt.regs()
Dump the values of the EXTI registers.

Methods

ExtInt.disable()
Disable the interrupt associated with the ExtInt object. This could be useful for debouncing.
ExtInt.enable()
Enable a disabled interrupt.
ExtInt.line()
Return the line number that the pin is mapped to.
ExtInt.swint()
Trigger the callback from software.

Constants

ExtInt.IRQ_FALLING
interrupt on a falling edge
ExtInt.IRQ_RISING
interrupt on a rising edge
ExtInt.IRQ_RISING_FALLING
interrupt on a rising or falling edge

class Flash – access to built-in flash storage

The Flash class allows direct access to the primary flash device on the pyboard.
In most cases, to store persistent data on the device, you’ll want to use a higher-level abstraction, for example the filesystem
via Python’s standard file API, but this interface is useful to customise the filesystem configuration or implement a low-level
storage system for your application.

Constructors

class pyb.Flash
Create and return a block device that represents the flash device presented to the USB mass storage interface.
It includes a virtual partition table at the start, and the actual flash starts at block 0x100.
This constructor is deprecated and will be removed in a future version of MicroPython.
class pyb.Flash(*, start=-1, len=-1)
Create and return a block device that accesses the flash at the specified offset. The length defaults to the remaining
size of the device.
The start and len offsets are in bytes, and must be a multiple of the block size (typically 512 for internal flash).

1.3. Port-specific libraries 143


MicroPython Documentation, Release v1.22.0

Methods

Flash.readblocks(block_num, buf)
Flash.readblocks(block_num, buf, offset)

Flash.writeblocks(block_num, buf)
Flash.writeblocks(block_num, buf, offset)

Flash.ioctl(cmd, arg)
These methods implement the simple and extended block protocol defined by os.AbstractBlockDev.

Hardware Note

On boards with external spiflash (e.g. Pyboard D), the MicroPython firmware will be configured to use that as the primary
flash storage. On all other boards, the internal flash inside the MCU will be used.

class I2C – a two-wire serial protocol

I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and
SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on.
Example:

from pyb import I2C

i2c = I2C(1) # create on bus 1


i2c = I2C(1, I2C.CONTROLLER) # create and init as a controller
i2c.init(I2C.CONTROLLER, baudrate=20000) # init as a controller
i2c.init(I2C.PERIPHERAL, addr=0x42) # init as a peripheral with given address
i2c.deinit() # turn off the I2C unit

Printing the i2c object gives you information about its configuration.
The basic methods are send and recv:

i2c.send('abc') # send 3 bytes


i2c.send(0x42) # send a single byte, given by the number
data = i2c.recv(3) # receive 3 bytes

To receive inplace, first create a bytearray:

data = bytearray(3) # create a buffer


i2c.recv(data) # receive 3 bytes, writing them into data

You can specify a timeout (in ms):

i2c.send(b'123', timeout=2000) # timeout after 2 seconds

A controller must specify the recipient’s address:

i2c.init(I2C.CONTROLLER)
i2c.send('123', 0x42) # send 3 bytes to peripheral with address 0x42
i2c.send(b'456', addr=0x42) # keyword for address

144 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Master also has other methods:

i2c.is_ready(0x42) # check if peripheral 0x42 is ready


i2c.scan() # scan for peripherals on the bus, returning
# a list of valid addresses
i2c.mem_read(3, 0x42, 2) # read 3 bytes from memory of peripheral 0x42,
# starting at address 2 in the peripheral
i2c.mem_write('abc', 0x42, 2, timeout=1000) # write 'abc' (3 bytes) to memory of␣
,→peripheral 0x42

# starting at address 2 in the peripheral,


,→ timeout after 1 second

Constructors

class pyb.I2C(bus, ...)


Construct an I2C object on the given bus. bus can be 1 or 2, ‘X’ or ‘Y’. With no additional parameters, the
I2C object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra
arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the I2C buses on Pyboards V1.0 and V1.1 are:
• I2C(1) is on the X position: (SCL, SDA) = (X9, X10) = (PB6, PB7)
• I2C(2) is on the Y position: (SCL, SDA) = (Y9, Y10) = (PB10, PB11)
On the Pyboard Lite:
• I2C(1) is on the X position: (SCL, SDA) = (X9, X10) = (PB6, PB7)
• I2C(3) is on the Y position: (SCL, SDA) = (Y9, Y10) = (PA8, PB8)
Calling the constructor with ‘X’ or ‘Y’ enables portability between Pyboard types.

Methods

I2C.deinit()
Turn off the I2C bus.
I2C.init(mode, *, addr=0x12, baudrate=400000, gencall=False, dma=False)
Initialise the I2C bus with the given parameters:
• mode must be either I2C.CONTROLLER or I2C.PERIPHERAL
• addr is the 7-bit address (only sensible for a peripheral)
• baudrate is the SCL clock rate (only sensible for a controller)
• gencall is whether to support general call mode
• dma is whether to allow the use of DMA for the I2C transfers (note that DMA transfers have more
precise timing but currently do not handle bus errors properly)
The actual clock frequency may be lower than the requested frequency. This is dependent on the plat-
form hardware. The actual rate may be determined by printing the I2C object.
I2C.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in controller mode.

1.3. Port-specific libraries 145


MicroPython Documentation, Release v1.22.0

I2C.mem_read(data, addr, memaddr, *, timeout=5000, addr_size=8)


Read from the memory of an I2C device:
• data can be an integer (number of bytes to read) or a buffer to read into
• addr is the I2C device address
• memaddr is the memory location within the I2C device
• timeout is the timeout in milliseconds to wait for the read
• addr_size selects width of memaddr: 8 or 16 bits
Returns the read data. This is only valid in controller mode.
I2C.mem_write(data, addr, memaddr, *, timeout=5000, addr_size=8)
Write to the memory of an I2C device:
• data can be an integer or a buffer to write from
• addr is the I2C device address
• memaddr is the memory location within the I2C device
• timeout is the timeout in milliseconds to wait for the write
• addr_size selects width of memaddr: 8 or 16 bits
Returns None. This is only valid in controller mode.
I2C.recv(recv, addr=0x00, *, timeout=5000)
Receive data on the bus:
• recv can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes
• addr is the address to receive from (only required in controller mode)
• timeout is the timeout in milliseconds to wait for the receive
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the same buffer that was
passed in to recv.
I2C.send(send, addr=0x00, *, timeout=5000)
Send data on the bus:
• send is the data to send (an integer to send, or a buffer object)
• addr is the address to send to (only required in controller mode)
• timeout is the timeout in milliseconds to wait for the send
Return value: None.
I2C.scan()
Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Only valid when in controller
mode.

146 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

I2C.CONTROLLER
for initialising the bus to controller mode
I2C.PERIPHERAL
for initialising the bus to peripheral mode

class LCD – LCD control for the LCD touch-sensor pyskin

The LCD class is used to control the LCD on the LCD touch-sensor pyskin, LCD32MKv1.0. The LCD is a 128x32 pixel
monochrome screen, part NHD-C12832A1Z.
The pyskin must be connected in either the X or Y positions, and then an LCD object is made using:

lcd = pyb.LCD('X') # if pyskin is in the X position


lcd = pyb.LCD('Y') # if pyskin is in the Y position

Then you can use:

lcd.light(True) # turn the backlight on


lcd.write('Hello world!\n') # print text to the screen

This driver implements a double buffer for setting/getting pixels. For example, to make a bouncing dot, try:

x = y = 0
dx = dy = 1
while True:
# update the dot's position
x += dx
y += dy

# make the dot bounce of the edges of the screen


if x <= 0 or x >= 127: dx = -dx
if y <= 0 or y >= 31: dy = -dy

lcd.fill(0) # clear the buffer


lcd.pixel(x, y, 1) # draw the dot
lcd.show() # show the buffer
pyb.delay(50) # pause for 50ms

Constructors

class pyb.LCD(skin_position)
Construct an LCD object in the given skin position. skin_position can be ‘X’ or ‘Y’, and should match the
position where the LCD pyskin is plugged in.

1.3. Port-specific libraries 147


MicroPython Documentation, Release v1.22.0

Methods

LCD.command(instr_data, buf)
Send an arbitrary command to the LCD. Pass 0 for instr_data to send an instruction, otherwise pass 1 to send
data. buf is a buffer with the instructions/data to send.
LCD.contrast(value)
Set the contrast of the LCD. Valid values are between 0 and 47.
LCD.fill(colour)
Fill the screen with the given colour (0 or 1 for white or black).
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.get(x, y)
Get the pixel at the position (x, y). Returns 0 or 1.
This method reads from the visible buffer.
LCD.light(value)
Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off.
LCD.pixel(x, y, colour)
Set the pixel at (x, y) to the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.show()
Show the hidden buffer on the screen.
LCD.text(str, x, y, colour)
Draw the given text to the position (x, y) using the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.write(str)
Write the string str to the screen. It will appear immediately.

class LED – LED object

The LED object controls an individual LED (Light Emitting Diode).

Constructors

class pyb.LED(id)
Create an LED object associated with the given LED:
• id is the LED number, 1-4.

148 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Methods

LED.intensity([value ])
Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given, return the
LED intensity. If an argument is given, set the LED intensity and return None.
Note: Only LED(3) and LED(4) can have a smoothly varying intensity, and they use timer PWM to implement it.
LED(3) uses Timer(2) and LED(4) uses Timer(3). These timers are only configured for PWM if the intensity of
the relevant LED is set to a value between 1 and 254. Otherwise the timers are free for general purpose use.
LED.off()
Turn the LED off.
LED.on()
Turn the LED on, to maximum intensity.
LED.toggle()
Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is considered
“on” and toggle will turn it off.

class Pin – control I/O pins

A pin is the basic object to control I/O pins. It has methods to set the mode of the pin (input, output, etc) and methods
to get and set the digital logic level. For analog control of a pin, see the ADC class.
Usage Model:
All Board Pins are predefined as pyb.Pin.board.Name:

x1_pin = pyb.Pin.board.X1

g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)

CPU pins which correspond to the board pins are available as pyb.Pin.cpu.Name. For the CPU pins, the names are
the port letter followed by the pin number. On the PYBv1.0, pyb.Pin.board.X1 and pyb.Pin.cpu.A0 are the
same pin.
You can also use strings:

g = pyb.Pin('X1', pyb.Pin.OUT_PP)

Users can add their own names:

MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 }


pyb.Pin.dict(MyMapperDict)
g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD)

and can query mappings:

pin = pyb.Pin("LeftMotorDir")

Users can also add their own mapping function:

def MyMapper(pin_name):
if pin_name == "LeftMotorDir":
return pyb.Pin.cpu.A0
(continues on next page)

1.3. Port-specific libraries 149


MicroPython Documentation, Release v1.22.0

(continued from previous page)

pyb.Pin.mapper(MyMapper)

So, if you were to call: pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP) then "LeftMotorDir" is passed


directly to the mapper function.
To summarise, the following order determines how things get mapped into an ordinal pin number:
1. Directly specify a pin object
2. User supplied mapping function
3. User supplied mapping (object must be usable as a dictionary key)
4. Supply a string which matches a board pin
5. Supply a string which matches a CPU port/pin
You can set pyb.Pin.debug(True) to get some debug information about how a particular object gets mapped to a
pin.
All pin objects go through the pin mapper to come up with one of the gpio pins.

Constructors

class pyb.Pin(id, ...)


Create a new Pin object associated with the id. If additional arguments are given, they are used to initialise the pin.
See pin.init().

Class methods

classmethod Pin.debug([state ])
Get or set the debugging state (True or False for on or off).
classmethod Pin.dict([dict ])
Get or set the pin mapper dictionary.
classmethod Pin.mapper([fun ])
Get or set the pin mapper function.

Methods

Pin.init(mode, pull=Pin.PULL_NONE, *, value=None, alt=-1)


Initialise the pin:
• mode can be one of:
– Pin.IN - configure the pin for input;
– Pin.OUT_PP - configure the pin for output, with push-pull control;
– Pin.OUT_OD - configure the pin for output, with open-drain control;
– Pin.ALT - configure the pin for alternate function, input or output;
– Pin.AF_PP - configure the pin for alternate function, push-pull;

150 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

– Pin.AF_OD - configure the pin for alternate function, open-drain;


– Pin.ANALOG - configure the pin for analog.
• pull can be one of:
– Pin.PULL_NONE - no pull up or down resistors;
– Pin.PULL_UP - enable the pull-up resistor;
– Pin.PULL_DOWN - enable the pull-down resistor.
When a pin has the Pin.PULL_UP or Pin.PULL_DOWN pull-mode enabled, that pin has an effective 40k
Ohm resistor pulling it to 3V3 or GND respectively (except pin Y5 which has 11k Ohm resistors).
• value if not None will set the port output value before enabling the pin.
• alt can be used when mode is Pin.ALT , Pin.AF_PP or Pin.AF_OD to set the index or name of one
of the alternate functions associated with a pin. This arg was previously called af which can still be used if
needed.
Returns: None.
Pin.value([value ])
Get or set the digital logic level of the pin:
• With no argument, return 0 or 1 depending on the logic level of the pin.
• With value given, set the logic level of the pin. value can be anything that converts to a boolean. If it
converts to True, the pin is set high, otherwise it is set low.
Pin.__str__()
Return a string describing the pin object.
Pin.af()
Returns the currently configured alternate-function of the pin. The integer returned will match one of the allowed
constants for the af argument to the init function.
Pin.af_list()
Returns an array of alternate functions available for this pin.
Pin.gpio()
Returns the base address of the GPIO block associated with this pin.
Pin.mode()
Returns the currently configured mode of the pin. The integer returned will match one of the allowed constants for
the mode argument to the init function.
Pin.name()
Get the pin name.
Pin.names()
Returns the cpu and board names for this pin.
Pin.pin()
Get the pin number.
Pin.port()
Get the pin port.
Pin.pull()
Returns the currently configured pull of the pin. The integer returned will match one of the allowed constants for
the pull argument to the init function.

1.3. Port-specific libraries 151


MicroPython Documentation, Release v1.22.0

Constants

Pin.ALT
initialise the pin to alternate-function mode for input or output
Pin.AF_OD
initialise the pin to alternate-function mode with an open-drain drive
Pin.AF_PP
initialise the pin to alternate-function mode with a push-pull drive
Pin.ANALOG
initialise the pin to analog mode
Pin.IN
initialise the pin to input mode
Pin.OUT_OD
initialise the pin to output mode with an open-drain drive
Pin.OUT_PP
initialise the pin to output mode with a push-pull drive
Pin.PULL_DOWN
enable the pull-down resistor on the pin
Pin.PULL_NONE
don’t enable any pull up or down resistors on the pin
Pin.PULL_UP
enable the pull-up resistor on the pin

class PinAF – Pin Alternate Functions

A Pin represents a physical pin on the microprocessor. Each pin can have a variety of functions (GPIO, I2C SDA, etc).
Each PinAF object represents a particular function for a pin.
Usage Model:

x3 = pyb.Pin.board.X3
x3_af = x3.af_list()

x3_af will now contain an array of PinAF objects which are available on pin X3.
For the pyboard, x3_af would contain:
[Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the alternate function automatically, but sometimes the same function is avail-
able on multiple pins, and having more control is desired.
To configure X3 to expose TIM2_CH3, you could use:

pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.ALT, alt=pyb.Pin.AF1_TIM2)

or:

152 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.ALT, alt=1)

Methods

pinaf.__str__()
Return a string describing the alternate function.
pinaf.index()
Return the alternate function index.
pinaf.name()
Return the name of the alternate function.
pinaf.reg()
Return the base register associated with the peripheral assigned to this alternate function. For example, if the
alternate function were TIM2_CH3 this would return stm.TIM2

class RTC – real time clock

The RTC is an independent clock that keeps track of the date and time.
Example usage:

rtc = pyb.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.datetime())

Constructors

class pyb.RTC
Create an RTC object.

Methods

RTC.datetime([datetimetuple ])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being an
8-tuple) it sets the date and time (and subseconds is reset to 255).
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
weekday is 1-7 for Monday through Sunday.
subseconds counts down from 255 to 0

1.3. Port-specific libraries 153


MicroPython Documentation, Release v1.22.0

RTC.wakeup(timeout, callback=None)
Set the RTC wakeup timer to trigger repeatedly at every timeout milliseconds. This trigger can wake the pyboard
from both the sleep states: pyb.stop() and pyb.standby().
If timeout is None then the wakeup timer is disabled.
If callback is given then it is executed at every trigger of the wakeup timer. callback must take exactly one
argument.
RTC.info()
Get information about the startup time and reset source.
• The lower 0xffff are the number of milliseconds the RTC took to start up.
• Bit 0x10000 is set if a power-on reset occurred.
• Bit 0x20000 is set if an external reset occurred
RTC.calibration(cal)
Get or set RTC calibration.
With no arguments, calibration() returns the current calibration value, which is an integer in the range [-511
: 512]. With one argument it sets the RTC calibration.
The RTC Smooth Calibration mechanism adjusts the RTC clock rate by adding or subtracting the given number
of ticks from the 32768 Hz clock over a 32 second period (corresponding to 2^20 clock ticks.) Each tick added
will speed up the clock by 1 part in 2^20, or 0.954 ppm; likewise the RTC clock it slowed by negative values. The
usable calibration range is: (-511 * 0.954) ~= -487.5 ppm up to (512 * 0.954) ~= 488.5 ppm

class Servo – 3-wire hobby servo driver

Servo objects control standard hobby servo motors with 3-wires (ground, power, signal). There are 4 positions on the
pyboard where these motors can be plugged in: pins X1 through X4 are the signal pins, and next to them are 4 sets of
power and ground pins.
Example usage:

import pyb

s1 = pyb.Servo(1) # create a servo object on position X1


s2 = pyb.Servo(2) # create a servo object on position X2

s1.angle(45) # move servo 1 to 45 degrees


s2.angle(0) # move servo 2 to 0 degrees

# move servo1 and servo2 synchronously, taking 1500ms


s1.angle(-60, 1500)
s2.angle(30, 1500)

Note: The Servo objects use Timer(5) to produce the PWM output. You can use Timer(5) for Servo control, or your
own purposes, but not both at the same time.

154 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constructors

class pyb.Servo(id)
Create a servo object. id is 1-4, and corresponds to pins X1 through X4.

Methods

Servo.angle([angle, time=0 ])
If no arguments are given, this function returns the current angle.
If arguments are given, this function sets the angle of the servo:
• angle is the angle to move to in degrees.
• time is the number of milliseconds to take to get to the specified angle. If omitted, then the servo moves as
quickly as possible to its new position.
Servo.speed([speed, time=0 ])
If no arguments are given, this function returns the current speed.
If arguments are given, this function sets the speed of the servo:
• speed is the speed to change to, between -100 and 100.
• time is the number of milliseconds to take to get to the specified speed. If omitted, then the servo accelerates
as quickly as possible.
Servo.pulse_width([value ])
If no arguments are given, this function returns the current raw pulse-width value.
If an argument is given, this function sets the raw pulse-width value.
Servo.calibration([pulse_min, pulse_max, pulse_centre[, pulse_angle_90, pulse_speed_100 ]])
If no arguments are given, this function returns the current calibration data, as a 5-tuple.
If arguments are given, this function sets the timing calibration:
• pulse_min is the minimum allowed pulse width.
• pulse_max is the maximum allowed pulse width.
• pulse_centre is the pulse width corresponding to the centre/zero position.
• pulse_angle_90 is the pulse width corresponding to 90 degrees.
• pulse_speed_100 is the pulse width corresponding to a speed of 100.

class SPI – a controller-driven serial protocol

SPI is a serial protocol that is driven by a controller. At the physical level there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is parameters to init the SPI bus:

from pyb import SPI


spi = SPI(1, SPI.CONTROLLER, baudrate=600000, polarity=1, phase=0, crc=0x7)

1.3. Port-specific libraries 155


MicroPython Documentation, Release v1.22.0

Only required parameter is mode, SPI.CONTROLLER or SPI.PERIPHERAL. Polarity can be 0 or 1, and is the level
the idle clock line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively. Crc can be
None for no CRC, or a polynomial specifier.
Additional methods for SPI:

data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes


buf = bytearray(4)
spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf

Constructors

class pyb.SPI(bus, ...)


Construct an SPI object on the given bus. bus can be 1 or 2, or ‘X’ or ‘Y’. With no additional parameters, the
SPI object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra
arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the SPI buses are:
• SPI(1) is on the X position: (NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4,
PA5, PA6, PA7)
• SPI(2) is on the Y position: (NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12,
PB13, PB14, PB15)
At the moment, the NSS pin is not used by the SPI driver and is free for other use.

Methods

SPI.deinit()
Turn off the SPI bus.
SPI.init(mode, baudrate=328125, *, prescaler=-1, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False,
crc=None)
Initialise the SPI bus with the given parameters:
• mode must be either SPI.CONTROLLER or SPI.PERIPHERAL.
• baudrate is the SCK clock rate (only sensible for a controller).
• prescaler is the prescaler to use to derive SCK from the APB bus frequency; use of prescaler over-
rides baudrate.
• polarity can be 0 or 1, and is the level the idle clock line sits at.
• phase can be 0 or 1 to sample data on the first or second clock edge respectively.
• bits can be 8 or 16, and is the number of bits in each transferred word.
• firstbit can be SPI.MSB or SPI.LSB.
• ti True indicates Texas Instruments, as opposed to Motorola, signal conventions.
• crc can be None for no CRC, or a polynomial specifier.
Note that the SPI clock frequency will not always be the requested baudrate. The hardware only supports baudrates
that are the APB bus frequency (see pyb.freq()) divided by a prescaler, which can be 2, 4, 8, 16, 32, 64, 128

156 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise control over the SPI clock frequency, specify
prescaler instead of baudrate.
Printing the SPI object will show you the computed baudrate and the chosen prescaler.
SPI.recv(recv, *, timeout=5000)
Receive data on the bus:
• recv can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
• timeout is the timeout in milliseconds to wait for the receive.
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the same buffer that was
passed in to recv.
SPI.send(send, *, timeout=5000)
Send data on the bus:
• send is the data to send (an integer to send, or a buffer object).
• timeout is the timeout in milliseconds to wait for the send.
Return value: None.
SPI.send_recv(send, recv=None, *, timeout=5000)
Send and receive data on the bus at the same time:
• send is the data to send (an integer to send, or a buffer object).
• recv is a mutable buffer which will be filled with received bytes. It can be the same as send, or omitted.
If omitted, a new buffer will be created.
• timeout is the timeout in milliseconds to wait for the receive.
Return value: the buffer with the received bytes.

Constants

SPI.CONTROLLER

SPI.PERIPHERAL
for initialising the SPI bus to controller or peripheral mode
SPI.LSB

SPI.MSB
set the first bit to be the least or most significant bit

class Switch – switch object

A Switch object is used to control a push-button switch.


Usage:

sw = pyb.Switch() # create a switch object


sw.value() # get state (True if pressed, False otherwise)
sw() # shorthand notation to get the switch state
sw.callback(f) # register a callback to be called when the
(continues on next page)

1.3. Port-specific libraries 157


MicroPython Documentation, Release v1.22.0

(continued from previous page)


# switch is pressed down
sw.callback(None) # remove the callback

Example:

pyb.Switch().callback(lambda: pyb.LED(1).toggle())

Constructors

class pyb.Switch
Create and return a switch object.

Methods

Switch.__call__()
Call switch object directly to get its state: True if pressed down, False otherwise.
Switch.value()
Get the switch state. Returns True if pressed down, otherwise False.
Switch.callback(fun)
Register the given function to be called when the switch is pressed down. If fun is None, then it disables the
callback.

class Timer – control internal timers

Timers can be used for a great variety of tasks. At the moment, only the simplest case is implemented: that of calling a
function periodically.
Each timer consists of a counter that counts up at a certain rate. The rate at which it counts is the peripheral clock
frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and the
counter resets back to zero. By using the callback method, the timer event can call a Python function.
Example usage to toggle an LED at a fixed frequency:

tim = pyb.Timer(4) # create a timer object using timer 4


tim.init(freq=2) # trigger at 2Hz
tim.callback(lambda t:pyb.LED(1).toggle())

Example using named function for the callback:

def tick(timer): # we will receive the timer object when being called
print(timer.counter()) # show current timer's counter value
tim = pyb.Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function

Further examples:

tim = pyb.Timer(4, freq=100) # freq in Hz


tim = pyb.Timer(4, prescaler=0, period=99)
tim.counter() # get counter (can also set)
(continues on next page)

158 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

(continued from previous page)


tim.prescaler(2) # set prescaler (can also get)
tim.period(199) # set period (can also get)
tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
tim.callback(None) # clear callback

Note: Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) and LED(4) respectively. But these timers
are only configured for PWM if the intensity of the relevant LED is set to a value between 1 and 254. If the intensity
feature of the LEDs is not used then these timers are free for general purpose use. Similarly, Timer(5) controls the servo
driver, and Timer(6) is used for timed ADC/DAC reading/writing. It is recommended to use the other timers in your
programs.
Note: Memory can’t be allocated during a callback (an interrupt) and so exceptions raised within a callback don’t give much
information. See micropython.alloc_emergency_exception_buf() for how to get around this limitation.

Constructors

class pyb.Timer(id, ...)


Construct a new timer object of the given id. If additional arguments are given, then the timer is initialised by
init(...). id can be 1 to 14.

Methods

Timer.init(*, freq, prescaler, period, mode=Timer.UP, div=1, callback=None, deadtime=0,


brk=Timer.BRK_OFF)
Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period:

tim.init(freq=100) # set the timer to trigger at 100Hz


tim.init(prescaler=83, period=999) # set the prescaler and period directly

Keyword arguments:
• freq — specifies the periodic frequency of the timer. You might also view this as the frequency
with which the timer goes through one complete cycle.
• prescaler [0-0xffff] - specifies the value to be loaded into the timer’s Prescaler Register (PSC).
The timer clock source is divided by (prescaler + 1) to arrive at the timer clock. Timers 2-7
and 12-14 have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11 have a clock
source of 168 MHz (pyb.freq()[3] * 2).
• period [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. Specifies the value
to be loaded into the timer’s AutoReload Register (ARR). This determines the period of the timer
(i.e. when the counter cycles). The timer counter will roll-over after period + 1 timer clock
cycles.
• mode can be one of:
– Timer.UP - configures the timer to count from 0 to ARR (default)
– Timer.DOWN - configures the timer to count from ARR down to 0.
– Timer.CENTER - configures the timer to count from 0 to ARR and then back down to 0.
• div can be one of 1, 2, or 4. Divides the timer clock to determine the sampling clock used by the
digital filters.
• callback - as per Timer.callback()

1.3. Port-specific libraries 159


MicroPython Documentation, Release v1.22.0

• deadtime - specifies the amount of “dead” or inactive time between transitions on complimentary
channels (both channels will be inactive) for this time). deadtime may be an integer between 0
and 1008, with the following restrictions: 0-128 in steps of 1. 128-256 in steps of 2, 256-512 in
steps of 8, and 512-1008 in steps of 16. deadtime measures ticks of source_freq divided
by div clock ticks. deadtime is only available on timers 1 and 8.
• brk - specifies if the break mode is used to kill the output of the PWM when the BRK_IN input
is asserted. The value of this argument determines if break is enabled and what the polarity is,
and can be one of Timer.BRK_OFF, Timer.BRK_LOW or Timer.BRK_HIGH. To select the
BRK_IN pin construct a Pin object with mode=Pin.ALT, alt=Pin.AFn_TIMx. The pin’s
GPIO input features are available in alt mode - pull= , value() and irq().
You must either specify freq or both of period and prescaler.
Timer.deinit()
Deinitialises the timer.
Disables the callback (and the associated irq).
Disables any channel callbacks (and the associated irq). Stops the timer, and disables the timer peripheral.
Timer.callback(fun)
Set the function to be called when the timer triggers. fun is passed 1 argument, the timer object. If fun is None
then the callback will be disabled.
Timer.channel(channel, mode, ...)
If only a channel number is passed, then a previously initialized channel object is returned (or None if there is no
previous channel).
Otherwise, a TimerChannel object is initialized and returned.
Each channel can be configured to perform pwm, output compare, or input capture. All channels share the same
underlying timer, which means that they share the same timer clock.
Keyword arguments:
• mode can be one of:
– Timer.PWM — configure the timer in PWM mode (active high).
– Timer.PWM_INVERTED — configure the timer in PWM mode (active low).
– Timer.OC_TIMING — indicates that no pin is driven.
– Timer.OC_ACTIVE — the pin will be made active when a compare match occurs (active is determined
by polarity)
– Timer.OC_INACTIVE — the pin will be made inactive when a compare match occurs.
– Timer.OC_TOGGLE — the pin will be toggled when an compare match occurs.
– Timer.OC_FORCED_ACTIVE — the pin is forced active (compare match is ignored).
– Timer.OC_FORCED_INACTIVE — the pin is forced inactive (compare match is ignored).
– Timer.IC — configure the timer in Input Capture mode.
– Timer.ENC_A — configure the timer in Encoder mode. The counter only changes when CH1 changes.
– Timer.ENC_B — configure the timer in Encoder mode. The counter only changes when CH2 changes.
– Timer.ENC_AB — configure the timer in Encoder mode. The counter changes when CH1 or CH2
changes.
• callback - as per TimerChannel.callback()

160 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• pin None (the default) or a Pin object. If specified (and not None) this will cause the alternate function of
the the indicated pin to be configured for this timer channel. An error will be raised if the pin doesn’t support
any alternate functions for this timer channel.
Keyword arguments for Timer.PWM modes:
• pulse_width - determines the initial pulse width value to use.
• pulse_width_percent - determines the initial pulse width percentage to use.
Keyword arguments for Timer.OC modes:
• compare - determines the initial value of the compare register.
• polarity can be one of:
– Timer.HIGH - output is active high
– Timer.LOW - output is active low
Optional keyword arguments for Timer.IC modes:
• polarity can be one of:
– Timer.RISING - captures on rising edge.
– Timer.FALLING - captures on falling edge.
– Timer.BOTH - captures on both edges.
Note that capture only works on the primary channel, and not on the complimentary channels.
Notes for Timer.ENC modes:
• Requires 2 pins, so one or both pins will need to be configured to use the appropriate timer AF using the Pin
API.
• Read the encoder value using the timer.counter() method.
• Only works on CH1 and CH2 (and not on CH1N or CH2N)
• The channel number is ignored when setting the encoder mode.
PWM Example:

timer = pyb.Timer(2, freq=1000)


ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000)
ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000)

PWM Motor Example with complementary outputs, dead time, break input and break callback:

from pyb import Timer


from machine import Pin # machine.Pin supports alt mode and irq on the same pin.
pin_t8_1 = Pin(Pin.board.Y1, mode=Pin.ALT, af=Pin.AF3_TIM8) # Pin PC6, TIM8_CH1
pin_t8_1n = Pin(Pin.board.X8, mode=Pin.ALT, af=Pin.AF3_TIM8) # Pin PA7, TIM8_CH1N
pin_bkin = Pin(Pin.board.X7, mode=Pin.ALT, af=Pin.AF3_TIM8) # Pin PA6, TIM8_BKIN
pin_bkin.irq(handler=break_callabck, trigger=Pin.IRQ_FALLING)
timer = pyb.Timer(8, freq=1000, deadtime=1008, brk=Timer.BRK_LOW)
ch1 = timer.channel(1, pyb.Timer.PWM, pulse_width_percent=30)

Timer.counter([value ])
Get or set the timer counter.
Timer.freq([value ])
Get or set the frequency for the timer (changes prescaler and period if set).

1.3. Port-specific libraries 161


MicroPython Documentation, Release v1.22.0

Timer.period([value ])
Get or set the period of the timer.
Timer.prescaler([value ])
Get or set the prescaler for the timer.
Timer.source_freq()
Get the frequency of the source of the timer.

class TimerChannel — setup a channel for a timer

Timer channels are used to generate/capture a signal using a timer.


TimerChannel objects are created using the Timer.channel() method.

Methods

timerchannel.callback(fun)
Set the function to be called when the timer channel triggers. fun is passed 1 argument, the timer object. If fun
is None then the callback will be disabled.
timerchannel.capture([value ])
Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases for the
same function. capture is the logical name to use when the channel is in input capture mode.
timerchannel.compare([value ])
Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases for the
same function. compare is the logical name to use when the channel is in output compare mode.
timerchannel.pulse_width([value ])
Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all aliases for
the same function. pulse_width is the logical name to use when the channel is in PWM mode.
In edge aligned mode, a pulse_width of period + 1 corresponds to a duty cycle of 100% In center aligned
mode, a pulse width of period corresponds to a duty cycle of 100%
timerchannel.pulse_width_percent([value ])
Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100 and
sets the percentage of the timer period for which the pulse is active. The value can be an integer or floating-point
number for more accuracy. For example, a value of 25 gives a duty cycle of 25%.

Constants

Timer.UP
Timer.DOWN
Timer.CENTER
Configures the timer to count Up, Down, or from 0 to ARR and then back down to 0.
Timer.BRK_OFF
Timer.BRK_LOW
Timer.BRK_HIGH
Configures the break mode when passed to the brk keyword argument.

162 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class UART – duplex serial communication bus

UART implements the standard UART/USART duplex serial communications protocol. At the physical level it consists
of 2 lines: RX and TX. The unit of communication is a character (not to be confused with a string character) which can
be 8 or 9 bits wide.
UART objects can be created and initialised using:

from pyb import UART

uart = UART(1, 9600) # init with given baudrate


uart.init(9600, bits=8, parity=None, stop=1) # init with given parameters

Bits can be 7, 8 or 9. Parity can be None, 0 (even) or 1 (odd). Stop can be 1 or 2.


Note: with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported.
A UART object acts like a stream object and reading and writing is done using the standard stream methods:

uart.read(10) # read 10 characters, returns a bytes object


uart.read() # read all available characters
uart.readline() # read a line
uart.readinto(buf) # read and store into the given buffer
uart.write('abc') # write the 3 characters

Individual characters can be read/written using:

uart.readchar() # read 1 character and returns it as an integer


uart.writechar(42) # write 1 character

To check if there is anything to be read, use:

uart.any() # returns the number of characters waiting

Note: The stream functions read, write, etc. are new in MicroPython v1.3.4. Earlier versions use uart.send and
uart.recv.

Constructors

class pyb.UART(bus, ...)


Construct a UART object on the given bus. For Pyboard bus can be 1-4, 6, ‘XA’, ‘XB’, ‘YA’, or ‘YB’. For Pyboard
Lite bus can be 1, 2, 6, ‘XB’, or ‘YA’. For Pyboard D bus can be 1-4, ‘XA’, ‘YA’ or ‘YB’. With no additional
parameters, the UART object is created but not initialised (it has the settings from the last initialisation of the bus,
if any). If extra arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the UART buses on Pyboard are:
• UART(4) is on XA: (TX, RX) = (X1, X2) = (PA0, PA1)
• UART(1) is on XB: (TX, RX) = (X9, X10) = (PB6, PB7)
• UART(6) is on YA: (TX, RX) = (Y1, Y2) = (PC6, PC7)
• UART(3) is on YB: (TX, RX) = (Y9, Y10) = (PB10, PB11)
• UART(2) is on: (TX, RX) = (X3, X4) = (PA2, PA3)
The Pyboard Lite supports UART(1), UART(2) and UART(6) only, pins are:
• UART(1) is on XB: (TX, RX) = (X9, X10) = (PB6, PB7)

1.3. Port-specific libraries 163


MicroPython Documentation, Release v1.22.0

• UART(6) is on YA: (TX, RX) = (Y1, Y2) = (PC6, PC7)


• UART(2) is on: (TX, RX) = (X1, X2) = (PA2, PA3)
The Pyboard D supports UART(1), UART(2), UART(3) and UART(4) only, pins are:
• UART(4) is on XA: (TX, RX) = (X1, X2) = (PA0, PA1)
• UART(1) is on YA: (TX, RX) = (Y1, Y2) = (PA9, PA10)
• UART(3) is on YB: (TX, RX) = (Y9, Y10) = (PB10, PB11)
• UART(2) is on: (TX, RX) = (X3, X4) = (PA2, PA3)
Note: Pyboard D has UART(1) on YA, unlike Pyboard and Pyboard Lite that both have UART(1) on XB and
UART(6) on YA.

Methods

UART.init(baudrate, bits=8, parity=None, stop=1, *, timeout=0, flow=0, timeout_char=0, read_buf_len=64)


Initialise the UART bus with the given parameters:
• baudrate is the clock rate.
• bits is the number of bits per character, 7, 8 or 9.
• parity is the parity, None, 0 (even) or 1 (odd).
• stop is the number of stop bits, 1 or 2.
• flow sets the flow control type. Can be 0, UART.RTS, UART.CTS or UART.RTS | UART.CTS.
• timeout is the timeout in milliseconds to wait for writing/reading the first character.
• timeout_char is the timeout in milliseconds to wait between characters while writing or reading.
• read_buf_len is the character length of the read buffer (0 to disable).
This method will raise an exception if the baudrate could not be set within 5% of the desired value. The minimum
baudrate is dictated by the frequency of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest
are on APB1. The default bus frequencies give a minimum baudrate of 1300 for UART(1) and UART(6) and 650
for the others. Use pyb.freq to reduce the bus frequencies to get lower baudrates.
Note: with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported.
UART.deinit()
Turn off the UART bus.
UART.any()
Returns the number of bytes waiting (may be 0).
UART.read([nbytes ])
Read characters. If nbytes is specified then read at most that many bytes. If nbytes are available in the buffer,
returns immediately, otherwise returns when sufficient characters arrive or the timeout elapses.
If nbytes is not given then the method reads as much data as possible. It returns after the timeout has elapsed.
Note: for 9 bit characters each character takes two bytes, nbytes must be even, and the number of characters is
nbytes/2.
Return value: a bytes object containing the bytes read in. Returns None on timeout.

164 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

UART.readchar()
Receive a single character on the bus.
Return value: The character read, as an integer. Returns -1 on timeout.
UART.readinto(buf [, nbytes ])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most
len(buf) bytes.
Return value: number of bytes read and stored into buf or None on timeout.
UART.readline()
Read a line, ending in a newline character. If such a line exists, return is immediate. If the timeout elapses, all
available data is returned regardless of whether a newline exists.
Return value: the line read or None on timeout if no data is available.
UART.write(buf)
Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide then each byte is one character. If characters
are 9 bits wide then two bytes are used for each character (little endian), and buf must contain an even number of
bytes.
Return value: number of bytes written. If a timeout occurs and no bytes were written returns None.
UART.writechar(char)
Write a single character on the bus. char is an integer to write. Return value: None. See note below if CTS flow
control is used.
UART.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: None.

Constants

UART.RTS
UART.CTS
to select the flow control type.

Flow Control

On Pyboards V1 and V1.1 UART(2) and UART(3) support RTS/CTS hardware flow control using the following pins:
• UART(2) is on: (TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)
• UART(3) is on :(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14,
PB13)
On the Pyboard Lite only UART(2) supports flow control on these pins:
(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)
In the following paragraphs the term “target” refers to the device connected to the UART.
When the UART’s init() method is called with flow set to one or both of UART.RTS and UART.CTS the relevant
flow control pins are configured. nRTS is an active low output, nCTS is an active low input with pullup enabled. To
achieve flow control the Pyboard’s nCTS signal should be connected to the target’s nRTS and the Pyboard’s nRTS to the
target’s nCTS.

1.3. Port-specific libraries 165


MicroPython Documentation, Release v1.22.0

CTS: target controls Pyboard transmitter

If CTS flow control is enabled the write behaviour is as follows:


If the Pyboard’s UART.write(buf) method is called, transmission will stall for any periods when nCTS is False.
This will result in a timeout if the entire buffer was not transmitted in the timeout period. The method returns the number
of bytes written, enabling the user to write the remainder of the data if required. In the event of a timeout, a character
will remain in the UART pending nCTS. The number of bytes composing this character will be included in the return
value.
If UART.writechar() is called when nCTS is False the method will time out unless the target asserts nCTS in
time. If it times out OSError 116 will be raised. The character will be transmitted as soon as the target asserts nCTS.

RTS: Pyboard controls target’s transmitter

If RTS flow control is enabled, behaviour is as follows:


If buffered input is used (read_buf_len > 0), incoming characters are buffered. If the buffer becomes full, the next
character to arrive will cause nRTS to go False: the target should cease transmission. nRTS will go True when
characters are read from the buffer.
Note that the any() method returns the number of bytes in the buffer. Assume a buffer length of N bytes. If the buffer
becomes full, and another character arrives, nRTS will be set False, and any() will return the count N. When characters
are read the additional character will be placed in the buffer and will be included in the result of a subsequent any()
call.
If buffered input is not used (read_buf_len == 0) the arrival of a character will cause nRTS to go False until the
character is read.

class USB_HID – USB Human Interface Device (HID)

The USB_HID class allows creation of an object representing the USB Human Interface Device (HID) interface. It can
be used to emulate a peripheral such as a mouse or keyboard.
Before you can use this class, you need to use pyb.usb_mode() to set the USB mode to include the HID interface.

Constructors

class pyb.USB_HID
Create a new USB_HID object.

Methods

USB_HID.recv(data, *, timeout=5000)
Receive data on the bus:
• data can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
• timeout is the timeout in milliseconds to wait for the receive.
Return value: if data is an integer then a new buffer of the bytes received, otherwise the number of bytes read
into data is returned.

166 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

USB_HID.send(data)
Send data over the USB HID interface:
• data is the data to send (a tuple/list of integers, or a bytearray).

class USB_VCP – USB virtual comm port

The USB_VCP class allows creation of a stream-like object representing the USB virtual comm port. It can be used
to read and write data over USB to the connected host.

Constructors

class pyb.USB_VCP(id=0)
Create a new USB_VCP object. The id argument specifies which USB VCP port to use.

Methods

USB_VCP.init(*, flow=-1)
Configure the USB VCP port. If the flow argument is not -1 then the value sets the flow control, which can be a
bitwise-or of USB_VCP.RTS and USB_VCP.CTS. RTS is used to control read behaviour and CTS, to control
write behaviour.
USB_VCP.setinterrupt(chr)
Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a CTRL-C
character is received over the USB VCP port, a KeyboardInterrupt exception is raised.
Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB VCP port.
USB_VCP.isconnected()
Return True if USB is connected as a serial device, else False.
USB_VCP.any()
Return True if any characters waiting, else False.
USB_VCP.close()
This method does nothing. It exists so the USB_VCP object can act as a file.
USB_VCP.read([nbytes ])
Read at most nbytes from the serial device and return them as a bytes object. If nbytes is not specified then
the method reads all available bytes from the serial device. USB_VCP stream implicitly works in non-blocking
mode, so if no pending data available, this method will return immediately with None value.
USB_VCP.readinto(buf [, maxlen ])
Read bytes from the serial device and store them into buf, which should be a buffer-like object. At most
len(buf) bytes are read. If maxlen is given and then at most min(maxlen, len(buf)) bytes are read.
Returns the number of bytes read and stored into buf or None if no pending data available.
USB_VCP.readline()
Read a whole line from the serial device.
Returns a bytes object containing the data, including the trailing newline character or None if no pending data
available.

1.3. Port-specific libraries 167


MicroPython Documentation, Release v1.22.0

USB_VCP.readlines()
Read as much data as possible from the serial device, breaking it into lines.
Returns a list of bytes objects, each object being one of the lines. Each line will include the newline character.
USB_VCP.write(buf)
Write the bytes from buf to the serial device.
Returns the number of bytes written.
USB_VCP.recv(data, *, timeout=5000)
Receive data on the bus:
• data can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
• timeout is the timeout in milliseconds to wait for the receive.
Return value: if data is an integer then a new buffer of the bytes received, otherwise the number of bytes read
into data is returned.
USB_VCP.send(data, *, timeout=5000)
Send data over the USB VCP:
• data is the data to send (an integer to send, or a buffer object).
• timeout is the timeout in milliseconds to wait for the send.
Return value: number of bytes sent.
USB_VCP.irq(handler=None, trigger=IRQ_RX, hard=False)
Register handler to be called whenever an event specified by trigger occurs. The handler function must take exactly
one argument, which will be the USB VCP object. Pass in None to disable the callback.
Valid values for trigger are:
• USB_VCP.IRQ_RX: new data is available for reading from the USB VCP object.

Constants

USB_VCP.RTS
USB_VCP.CTS
to select the flow control type.
USB_VCP.IRQ_RX
IRQ trigger values for USB_VCP.irq().

stm — functionality specific to STM32 MCUs

This module provides functionality specific to STM32 microcontrollers, including direct access to peripheral registers.

168 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Memory access

The module exposes three objects used for raw memory access.
stm.mem8
Read/write 8 bits of memory.
stm.mem16
Read/write 16 bits of memory.
stm.mem32
Read/write 32 bits of memory.
Use subscript notation [...] to index these objects with the address of interest.
These memory objects can be used in combination with the peripheral register constants to read and write registers of the
MCU hardware peripherals, as well as all other areas of address space.

Peripheral register constants

The module defines constants for registers which are generated from CMSIS header files, and the constants available
depend on the microcontroller series that is being compiled for. Examples of some constants include:
stm.GPIOA
Base address of the GPIOA peripheral.
stm.GPIOB
Base address of the GPIOB peripheral.
stm.GPIO_BSRR
Offset of the GPIO bit set/reset register.
stm.GPIO_IDR
Offset of the GPIO input data register.
stm.GPIO_ODR
Offset of the GPIO output data register.
Constants that are named after a peripheral, like GPIOA, are the absolute address of that peripheral. Constants that have
a prefix which is the name of a peripheral, like GPIO_BSRR, are relative offsets of the register. Accessing peripheral
registers requires adding the absolute base address of the peripheral and the relative register offset. For example GPIOA
+ GPIO_BSRR is the full, absolute address of the GPIOA->BSRR register.
Example use:

# set PA2 high


stm.mem32[stm.GPIOA + stm.GPIO_BSRR] = 1 << 2

# read PA3
value = (stm.mem32[stm.GPIOA + stm.GPIO_IDR] >> 3) & 1

1.3. Port-specific libraries 169


MicroPython Documentation, Release v1.22.0

Functions specific to STM32WBxx MCUs

These functions are available on STM32WBxx microcontrollers, and interact with the second CPU, the RF core.
stm.rfcore_status()
Returns the status of the second CPU as an integer (the first word of device info table).
stm.rfcore_fw_version(id)
Get the version of the firmware running on the second CPU. Pass in 0 for id to get the FUS version, and 1 to get
the WS version.
Returns a 5-tuple with the full version number.
stm.rfcore_sys_hci(ogf, ocf, data, timeout_ms=0)
Execute a HCI command on the SYS channel. The execution is synchronous.
Returns a bytes object with the result of the SYS command.

Functions specific to STM32WLxx MCUs

These functions are available on STM32WLxx microcontrollers, and interact with the integrated “SUBGHZ” radio mo-
dem peripheral.
stm.subghz_cs(level)
Sets the internal SPI CS pin attached to the radio peripheral. The level argument is active-low: a truthy value
means “CS pin high” and de-asserts the signal, a falsey value means “CS pin low” and asserts the signal.
The internal-only SPI bus corresponding to this CS signal can be instantiated using machine.SPI() id value "SUB-
GHZ".
stm.subghz_irq(handler)
Sets the internal SUBGHZ radio interrupt handler to the provided function. The handler function is called as a
“hard” interrupt in response to radio peripheral interrupts. See Writing interrupt handlers for more information
about interrupt handlers in MicroPython.
Calling this function with the handler argument set to None disables the IRQ.
Due to a hardware limitation, each time this IRQ fires MicroPython disables it before calling the handler. In order
to receive another interrupt, Python code should call subghz_irq() to set the handler again. This has the side
effect of re-enabling the IRQ.
stm.subghz_is_busy()
Return a bool corresponding to the internal “RFBUSYS” signal from the radio peripheral. Before sending a new
command to the radio over SPI then this function should be polled until it returns False, to confirm the busy
signal is de-asserted.

lcd160cr — control of LCD160CR display

This module provides control of the MicroPython LCD160CR display.

170 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Further resources are available via the following links:


• LCD160CRv1.0 reference manual (100KiB PDF)
• LCD160CRv1.0 schematics (1.6MiB PDF)

class LCD160CR

The LCD160CR class provides an interface to the display. Create an instance of this class and use its methods to draw
to the LCD and get the status of the touch panel.
For example:

import lcd160cr

lcd = lcd160cr.LCD160CR('X')
lcd.set_orient(lcd160cr.PORTRAIT)
lcd.set_pos(0, 0)
lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0))
lcd.set_font(1)
lcd.write('Hello MicroPython!')
print('touch:', lcd.get_touch())

1.3. Port-specific libraries 171


MicroPython Documentation, Release v1.22.0

Constructors

class lcd160cr.LCD160CR(connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98)


Construct an LCD160CR object. The parameters are:
• connect is a string specifying the physical connection of the LCD display to the board; valid values are “X”,
“Y”, “XY”, “YX”. Use “X” when the display is connected to a pyboard in the X-skin position, and “Y” when
connected in the Y-skin position. “XY” and “YX” are used when the display is connected to the right or left
side of the pyboard, respectively.
• pwr is a Pin object connected to the LCD’s power/enabled pin.
• i2c is an I2C object connected to the LCD’s I2C interface.
• spi is an SPI object connected to the LCD’s SPI interface.
• i2c_addr is the I2C address of the display.
One must specify either a valid connect or all of pwr, i2c and spi. If a valid connect is given then any of pwr, i2c
or spi which are not passed as parameters (i.e. they are None) will be created based on the value of connect. This
allows to override the default interface to the display if needed.
The default values are:
• “X” is for the X-skin and uses: pwr=Pin("X4"), i2c=I2C("X"), spi=SPI("X")
• “Y” is for the Y-skin and uses: pwr=Pin("Y4"), i2c=I2C("Y"), spi=SPI("Y")
• “XY” is for the right-side and uses: pwr=Pin("X4"), i2c=I2C("Y"), spi=SPI("X")
• “YX” is for the left-side and uses: pwr=Pin("Y4"), i2c=I2C("X"), spi=SPI("Y")
See this image for how the display can be connected to the pyboard.

Static methods

static LCD160CR.rgb(r, g, b)
Return a 16-bit integer representing the given rgb color values. The 16-bit value can be used to set the font color
(see LCD160CR.set_text_color()) pen color (see LCD160CR.set_pen()) and draw individual pixels.
LCD160CR.clip_line(data, w, h):
Clip the given line data. This is for internal use.

Instance members

The following instance members are publicly accessible.


LCD160CR.w

LCD160CR.h
The width and height of the display, respectively, in pixels. These members are updated when calling LCD160CR.
set_orient() and should be considered read-only.

172 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Setup commands

LCD160CR.set_power(on)
Turn the display on or off, depending on the given value of on: 0 or False will turn the display off, and 1 or True
will turn it on.
LCD160CR.set_orient(orient)
Set the orientation of the display. The orient parameter can be one of PORTRAIT, LANDSCAPE, POR-
TRAIT_UPSIDEDOWN, LANDSCAPE_UPSIDEDOWN.
LCD160CR.set_brightness(value)
Set the brightness of the display, between 0 and 31.
LCD160CR.set_i2c_addr(addr)
Set the I2C address of the display. The addr value must have the lower 2 bits cleared.
LCD160CR.set_uart_baudrate(baudrate)
Set the baudrate of the UART interface.
LCD160CR.set_startup_deco(value)
Set the start-up decoration of the display. The value parameter can be a logical or of STARTUP_DECO_NONE,
STARTUP_DECO_MLOGO, STARTUP_DECO_INFO.
LCD160CR.save_to_flash()
Save the following parameters to flash so they persist on restart and power up: initial decoration, orientation,
brightness, UART baud rate, I2C address.

Pixel access methods

The following methods manipulate individual pixels on the display.


LCD160CR.set_pixel(x, y, c)
Set the specified pixel to the given color. The color should be a 16-bit integer and can be created by LCD160CR.
rgb().
LCD160CR.get_pixel(x, y)
Get the 16-bit value of the specified pixel.
LCD160CR.get_line(x, y, buf)
Low-level method to get a line of pixels into the given buffer. To read n pixels buf should be 2*n+1 bytes in length.
The first byte is a dummy byte and should be ignored, and subsequent bytes represent the pixels in the line starting
at coordinate (x, y).
LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None)
Dump the contents of the screen to the given buffer. The parameters x and y specify the starting coordinate, and w
and h the size of the region. If w or h are None then they will take on their maximum values, set by the size of the
screen minus the given x and y values. buf should be large enough to hold 2*w*h bytes. If it’s smaller then only
the initial horizontal lines will be stored.
LCD160CR.screen_load(buf)
Load the entire screen from the given buffer.

1.3. Port-specific libraries 173


MicroPython Documentation, Release v1.22.0

Drawing text

To draw text one sets the position, color and font, and then uses LCD160CR.write to draw the text.
LCD160CR.set_pos(x, y)
Set the position for text output using LCD160CR.write(). The position is the upper-left corner of the text.
LCD160CR.set_text_color(fg, bg)
Set the foreground and background color of the text.
LCD160CR.set_font(font, scale=0, bold=0, trans=0, scroll=0)
Set the font for the text. Subsequent calls to write will use the newly configured font. The parameters are:
• font is the font family to use, valid values are 0, 1, 2, 3.
• scale is a scaling value for each character pixel, where the pixels are drawn as a square with side length equal
to scale + 1. The value can be between 0 and 63.
• bold controls the number of pixels to overdraw each character pixel, making a bold effect. The lower 2 bits of
bold are the number of pixels to overdraw in the horizontal direction, and the next 2 bits are for the vertical
direction. For example, a bold value of 5 will overdraw 1 pixel in both the horizontal and vertical directions.
• trans can be either 0 or 1 and if set to 1 the characters will be drawn with a transparent background.
• scroll can be either 0 or 1 and if set to 1 the display will do a soft scroll if the text moves to the next line.
LCD160CR.write(s)
Write text to the display, using the current position, color and font. As text is written the position is automatically
incremented. The display supports basic VT100 control codes such as newline and backspace.

Drawing primitive shapes

Primitive drawing commands use a foreground and background color set by the set_pen method.
LCD160CR.set_pen(line, fill)
Set the line and fill color for primitive shapes.
LCD160CR.erase()
Erase the entire display to the pen fill color.
LCD160CR.dot(x, y)
Draw a single pixel at the given location using the pen line color.
LCD160CR.rect(x, y, w, h)

LCD160CR.rect_outline(x, y, w, h)

LCD160CR.rect_interior(x, y, w, h)
Draw a rectangle at the given location and size using the pen line color for the outline, and the pen fill color for the
interior. The rect method draws the outline and interior, while the other methods just draw one or the other.
LCD160CR.line(x1, y1, x2, y2)
Draw a line between the given coordinates using the pen line color.
LCD160CR.dot_no_clip(x, y)

LCD160CR.rect_no_clip(x, y, w, h)

174 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

LCD160CR.rect_outline_no_clip(x, y, w, h)

LCD160CR.rect_interior_no_clip(x, y, w, h)

LCD160CR.line_no_clip(x1, y1, x2, y2)


These methods are as above but don’t do any clipping on the input coordinates. They are faster than the clipping
versions and can be used when you know that the coordinates are within the display.
LCD160CR.poly_dot(data)
Draw a sequence of dots using the pen line color. The data should be a buffer of bytes, with each successive pair
of bytes corresponding to coordinate pairs (x, y).
LCD160CR.poly_line(data)
Similar to LCD160CR.poly_dot() but draws lines between the dots.

Touch screen methods

LCD160CR.touch_config(calib=False, save=False, irq=None)


Configure the touch panel:
• If calib is True then the call will trigger a touch calibration of the resistive touch sensor. This requires the
user to touch various parts of the screen.
• If save is True then the touch parameters will be saved to NVRAM to persist across reset/power up.
• If irq is True then the display will be configured to pull the IRQ line low when a touch force is detected. If
irq is False then this feature is disabled. If irq is None (the default value) then no change is made to this
setting.
LCD160CR.is_touched()
Returns a boolean: True if there is currently a touch force on the screen, False otherwise.
LCD160CR.get_touch()
Returns a 3-tuple of: (active, x, y). If there is currently a touch force on the screen then active is 1, otherwise it is
0. The x and y values indicate the position of the current or most recent touch.

Advanced commands

LCD160CR.set_spi_win(x, y, w, h)
Set the window that SPI data is written to.
LCD160CR.fast_spi(flush=True)
Ready the display to accept RGB pixel data on the SPI bus, resetting the location of the first byte to go to the
top-left corner of the window set by LCD160CR.set_spi_win(). The method returns an SPI object which
can be used to write the pixel data.
Pixels should be sent as 16-bit RGB values in the 5-6-5 format. The destination counter will increase as data is
sent, and data can be sent in arbitrary sized chunks. Once the destination counter reaches the end of the window
specified by LCD160CR.set_spi_win() it will wrap around to the top-left corner of that window.
LCD160CR.show_framebuf(buf)
Show the given buffer on the display. buf should be an array of bytes containing the 16-bit RGB values for the
pixels, and they will be written to the area specified by LCD160CR.set_spi_win(), starting from the top-left
corner.

1.3. Port-specific libraries 175


MicroPython Documentation, Release v1.22.0

The framebuf module can be used to construct frame buffers and provides drawing primitives. Using a frame buffer
will improve performance of animations when compared to drawing directly to the screen.
LCD160CR.set_scroll(on)
Turn scrolling on or off. This controls globally whether any window regions will scroll.
LCD160CR.set_scroll_win(win, x=-1, y=0, w=0, h=0, vec=0, pat=0, fill=0x07e0, color=0)
Configure a window region for scrolling:
• win is the window id to configure. There are 0..7 standard windows for general purpose use. Window 8 is the
text scroll window (the ticker).
• x, y, w, h specify the location of the window in the display.
• vec specifies the direction and speed of scroll: it is a 16-bit value of the form 0bF.ddSSSSSSSSSSSS. dd
is 0, 1, 2, 3 for +x, +y, -x, -y scrolling. F sets the speed format, with 0 meaning that the window is shifted S
% 256 pixel every frame, and 1 meaning that the window is shifted 1 pixel every S frames.
• pat is a 16-bit pattern mask for the background.
• fill is the fill color.
• color is the extra color, either of the text or pattern foreground.
LCD160CR.set_scroll_win_param(win, param, value)
Set a single parameter of a scrolling window region:
• win is the window id, 0..8.
• param is the parameter number to configure, 0..7, and corresponds to the parameters in the
set_scroll_win method.
• value is the value to set.
LCD160CR.set_scroll_buf(s)
Set the string for scrolling in window 8. The parameter s must be a string with length 32 or less.
LCD160CR.jpeg(buf)
Display a JPEG. buf should contain the entire JPEG data. JPEG data should not include EXIF information.
The following encodings are supported: Baseline DCT, Huffman coding, 8 bits per sample, 3 color components,
YCbCr4:2:2. The origin of the JPEG is set by LCD160CR.set_pos().
LCD160CR.jpeg_start(total_len)

LCD160CR.jpeg_data(buf)
Display a JPEG with the data split across multiple buffers. There must be a single call to jpeg_start to begin
with, specifying the total number of bytes in the JPEG. Then this number of bytes must be transferred to the display
using one or more calls to the jpeg_data command.
LCD160CR.feed_wdt()
The first call to this method will start the display’s internal watchdog timer. Subsequent calls will feed the watchdog.
The timeout is roughly 30 seconds.
LCD160CR.reset()
Reset the display.

176 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Constants

lcd160cr.PORTRAIT
lcd160cr.LANDSCAPE
lcd160cr.PORTRAIT_UPSIDEDOWN
lcd160cr.LANDSCAPE_UPSIDEDOWN
Orientations of the display, used by LCD160CR.set_orient().
lcd160cr.STARTUP_DECO_NONE
lcd160cr.STARTUP_DECO_MLOGO
lcd160cr.STARTUP_DECO_INFO
Types of start-up decoration, can be OR’ed together, used by LCD160CR.set_startup_deco().

1.3.2 Libraries specific to the WiPy

The following libraries and classes are specific to the WiPy.

wipy – WiPy specific features

The wipy module contains functions to control specific features of the WiPy, such as the heartbeat LED.

Functions

wipy.heartbeat([enable ])
Get or set the state (enabled or disabled) of the heartbeat LED. Accepts and returns boolean values (True or
False).

class ADCWiPy – analog to digital conversion

Note: This class is a non-standard ADC implementation for the WiPy. It is available simply as machine.ADC on
the WiPy but is named in the documentation below as machine.ADCWiPy to distinguish it from the more general
machine.ADC class.

Usage:

import machine

adc = machine.ADC() # create an ADC object


apin = adc.channel(pin='GP3') # create an analog pin on GP3
val = apin() # read an analog value

1.3. Port-specific libraries 177


MicroPython Documentation, Release v1.22.0

Constructors

class machine.ADCWiPy(id=0, *, bits=12)


Create an ADC object associated with the given pin. This allows you to then read analog values on that pin. For
more info check the pinout and alternate functions table.

Warning: ADC pin input range is 0-1.4V (being 1.8V the absolute maximum that it can withstand). When
GP2, GP3, GP4 or GP5 are remapped to the ADC block, 1.8 V is the maximum. If these pins are used in
digital mode, then the maximum allowed input is 3.6V.

Methods

ADCWiPy.channel(id, *, pin)
Create an analog pin. If only channel ID is given, the correct pin will be selected. Alternatively, only the pin can
be passed and the correct channel will be selected. Examples:

# all of these are equivalent and enable ADC channel 1 on GP3


apin = adc.channel(1)
apin = adc.channel(pin='GP3')
apin = adc.channel(id=1, pin='GP3')

ADCWiPy.init()
Enable the ADC block.
ADCWiPy.deinit()
Disable the ADC block.

class ADCChannel — read analog values from internal or external sources

ADC channels can be connected to internal points of the MCU or to GPIO pins. ADC channels are created using the
ADC.channel method.
machine.adcchannel()
Fast method to read the channel value.
adcchannel.value()
Read the channel value.
adcchannel.init()
Re-init (and effectively enable) the ADC channel.
adcchannel.deinit()
Disable the ADC channel.

178 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

class TimerWiPy – control hardware timers

Note: This class is a non-standard Timer implementation for the WiPy. It is available simply as machine.Timer on
the WiPy but is named in the documentation below as machine.TimerWiPy to distinguish it from the more general
machine.Timer class.

Hardware timers deal with timing of periods and events. Timers are perhaps the most flexible and heterogeneous kind of
hardware in MCUs and SoCs, differently greatly from a model to a model. MicroPython’s Timer class defines a baseline
operation of executing a callback with a given period (or once after some delay), and allow specific boards to define more
non-standard behaviour (which thus won’t be portable to other boards).
See discussion of important constraints on Timer callbacks.

Note: Memory can’t be allocated inside irq handlers (an interrupt) and so exceptions raised within a handler don’t
give much information. See micropython.alloc_emergency_exception_buf() for how to get around this
limitation.

Constructors

class machine.TimerWiPy(id, ...)


Construct a new timer object of the given id. Id of -1 constructs a virtual timer (if supported by a board).

Methods

TimerWiPy.init(mode, *, width=16)
Initialise the timer. Example:

tim.init(Timer.PERIODIC) # periodic 16-bit timer


tim.init(Timer.ONE_SHOT, width=32) # one shot 32-bit timer

Keyword arguments:
• mode can be one of:
– TimerWiPy.ONE_SHOT - The timer runs once until the configured period of the channel expires.
– TimerWiPy.PERIODIC - The timer runs periodically at the configured frequency of the channel.
– TimerWiPy.PWM - Output a PWM signal on a pin.
• width must be either 16 or 32 (bits). For really low frequencies < 5Hz (or large periods), 32-bit timers
should be used. 32-bit mode is only available for ONE_SHOT AND PERIODIC modes.
TimerWiPy.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
TimerWiPy.channel(channel, **, freq, period, polarity=TimerWiPy.POSITIVE, duty_cycle=0)
If only a channel identifier passed, then a previously initialized channel object is returned (or None if there is no
previous channel).
Otherwise, a TimerChannel object is initialized and returned.
The operating mode is is the one configured to the Timer object that was used to create the channel.

1.3. Port-specific libraries 179


MicroPython Documentation, Release v1.22.0

• channel if the width of the timer is 16-bit, then must be either TIMER.A, TIMER.B. If the width is 32-bit
then it must be TIMER.A | TIMER.B.
Keyword only arguments:
• freq sets the frequency in Hz.
• period sets the period in microseconds.

Note: Either freq or period must be given, never both.

• polarity this is applicable for PWM, and defines the polarity of the duty cycle
• duty_cycle only applicable to PWM. It’s a percentage (0.00-100.00). Since the WiPy doesn’t
support floating point numbers the duty cycle must be specified in the range 0-10000, where 10000
would represent 100.00, 5050 represents 50.50, and so on.

Note: When the channel is in PWM mode, the corresponding pin is assigned automatically, therefore there’s no
need to assign the alternate function of the pin via the Pin class. The pins which support PWM functionality are
the following:
• GP24 on Timer 0 channel A.
• GP25 on Timer 1 channel A.
• GP9 on Timer 2 channel B.
• GP10 on Timer 3 channel A.
• GP11 on Timer 3 channel B.

class TimerChannel — setup a channel for a timer

Timer channels are used to generate/capture a signal using a timer.


TimerChannel objects are created using the Timer.channel() method.

Methods

timerchannel.irq(*, trigger, priority=1, handler=None)


The behaviour of this callback is heavily dependent on the operating mode of the timer channel:
• If mode is TimerWiPy.PERIODIC the callback is executed periodically with the configured frequency or
period.
• If mode is TimerWiPy.ONE_SHOT the callback is executed once when the configured timer expires.
• If mode is TimerWiPy.PWM the callback is executed when reaching the duty cycle value.
The accepted params are:
• priority level of the interrupt. Can take values in the range 1-7. Higher values represent higher priorities.
• handler is an optional function to be called when the interrupt is triggered.

180 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• trigger must be TimerWiPy.TIMEOUT when the operating mode is either TimerWiPy.PERIODIC


or TimerWiPy.ONE_SHOT. In the case that mode is TimerWiPy.PWM then trigger must be equal to
TimerWiPy.MATCH.
Returns a callback object.
timerchannel.freq([value ])
Get or set the timer channel frequency (in Hz).
timerchannel.period([value ])
Get or set the timer channel period (in microseconds).
timerchannel.duty_cycle([value ])
Get or set the duty cycle of the PWM signal. It’s a percentage (0.00-100.00). Since the WiPy doesn’t support
floating point numbers the duty cycle must be specified in the range 0-10000, where 10000 would represent 100.00,
5050 represents 50.50, and so on.

Constants

TimerWiPy.ONE_SHOT

TimerWiPy.PERIODIC
Timer operating mode.

1.3.3 Libraries specific to the ESP8266 and ESP32

The following libraries are specific to the ESP8266 and ESP32.

esp — functions related to the ESP8266 and ESP32

The esp module contains specific functions related to both the ESP8266 and ESP32 modules. Some functions are only
available on one or the other of these ports.

Functions

esp.sleep_type([sleep_type ])
Note: ESP8266 only
Get or set the sleep type.
If the sleep_type parameter is provided, sets the sleep type to its value. If the function is called without parameters,
returns the current sleep type.
The possible sleep types are defined as constants:
• SLEEP_NONE – all functions enabled,
• SLEEP_MODEM – modem sleep, shuts down the WiFi Modem circuit.
• SLEEP_LIGHT – light sleep, shuts down the WiFi Modem circuit and suspends the processor periodically.
The system enters the set sleep mode automatically when possible.

1.3. Port-specific libraries 181


MicroPython Documentation, Release v1.22.0

esp.deepsleep(time_us=0, / )
Note: ESP8266 only - use machine.deepsleep() on ESP32
Enter deep sleep.
The whole module powers down, except for the RTC clock circuit, which can be used to restart the module after
the specified time if the pin 16 is connected to the reset pin. Otherwise the module will sleep until manually reset.
esp.flash_id()
Note: ESP8266 only
Read the device ID of the flash memory.
esp.flash_size()
Read the total size of the flash memory.
esp.flash_user_start()
Read the memory offset at which the user flash space begins.
esp.flash_read(byte_offset, length_or_buffer)

esp.flash_write(byte_offset, bytes)

esp.flash_erase(sector_no)

esp.osdebug(uart_no)

Note: This is the ESP8266 form of this function.

Change the level of OS serial debug log messages. On boot, OS serial debug log messages are disabled.
uart_no is the number of the UART peripheral which should receive OS-level output, or None to disable OS
serial debug log messages.
esp.osdebug(uart_no[, level ])

Note: This is the ESP32 form of this function.

Change the level of OS serial debug log messages. On boot, OS serial debug log messages are limited to Error
output only.
The behaviour of this function depends on the arguments passed to it. The following combinations are supported:
osdebug(None) restores the default OS debug log message level (LOG_ERROR).
osdebug(0) enables all available OS debug log messages (in the default build configuration this is LOG_INFO).
osdebug(0, level) sets the OS debug log message level to the
specified value. The log levels are defined as constants:
• LOG_NONE – No log output
• LOG_ERROR – Critical errors, software module can not recover on its own
• LOG_WARN – Error conditions from which recovery measures have been taken
• LOG_INFO – Information messages which describe normal flow of events
• LOG_DEBUG – Extra information which is not necessary for normal use (values, pointers, sizes, etc)

182 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

• LOG_VERBOSE – Bigger chunks of debugging information, or frequent messages which can potentially
flood the output

Note: LOG_DEBUG and LOG_VERBOSE are not compiled into the MicroPython binary by default, to save size.
A custom build with a modified “sdkconfig” source file is needed to see any output at these log levels.

Note: Log output on ESP32 is automatically suspended in “Raw REPL” mode, to prevent communications issues.
This means OS level logging is never seen when using mpremote run and similar tools.

esp.set_native_code_location(start, length)
Note: ESP8266 only
Set the location that native code will be placed for execution after it is compiled. Native code is emitted when the
@micropython.native, @micropython.viper and @micropython.asm_xtensa decorators are
applied to a function. The ESP8266 must execute code from either iRAM or the lower 1MByte of flash (which is
memory mapped), and this function controls the location.
If start and length are both None then the native code location is set to the unused portion of memory at the end
of the iRAM1 region. The size of this unused portion depends on the firmware and is typically quite small (around
500 bytes), and is enough to store a few very small functions. The advantage of using this iRAM1 region is that it
does not get worn out by writing to it.
If neither start nor length are None then they should be integers. start should specify the byte offset from the
beginning of the flash at which native code should be stored. length specifies how many bytes of flash from start
can be used to store native code. start and length should be multiples of the sector size (being 4096 bytes). The
flash will be automatically erased before writing to it so be sure to use a region of flash that is not otherwise used,
for example by the firmware or the filesystem.
When using the flash to store native code start+length must be less than or equal to 1MByte. Note that the flash
can be worn out if repeated erasures (and writes) are made so use this feature sparingly. In particular, native code
needs to be recompiled and rewritten to flash on each boot (including wake from deepsleep).
In both cases above, using iRAM1 or flash, if there is no more room left in the specified region then the use of
a native decorator on a function will lead to MemoryError exception being raised during compilation of that
function.

esp32 — functionality specific to the ESP32

The esp32 module contains functions and classes specifically aimed at controlling ESP32 modules.

Functions

esp32.wake_on_touch(wake)
Configure whether or not a touch will wake the device from sleep. wake should be a boolean value.
esp32.wake_on_ulp(wake)
Configure whether or not the Ultra-Low-Power co-processor can wake the device from sleep. wake should be a
boolean value.
esp32.wake_on_ext0(pin, level)
Configure how EXT0 wakes the device from sleep. pin can be None or a valid Pin object. level should be esp32.
WAKEUP_ALL_LOW or esp32.WAKEUP_ANY_HIGH.

1.3. Port-specific libraries 183


MicroPython Documentation, Release v1.22.0

esp32.wake_on_ext1(pins, level)
Configure how EXT1 wakes the device from sleep. pins can be None or a tuple/list of valid Pin objects. level
should be esp32.WAKEUP_ALL_LOW or esp32.WAKEUP_ANY_HIGH.
esp32.gpio_deep_sleep_hold(enable)
Configure whether non-RTC GPIO pin configuration is retained during deep-sleep mode for held pads. enable
should be a boolean value.
esp32.raw_temperature()
Read the raw value of the internal temperature sensor, returning an integer.
esp32.idf_heap_info(capabilities)
Returns information about the ESP-IDF heap memory regions. One of them contains the MicroPython heap and
the others are used by ESP-IDF, e.g., for network buffers and other data. This data is useful to get a sense of how
much memory is available to ESP-IDF and the networking stack in particular. It may shed some light on situations
where ESP-IDF operations fail due to allocation failures.
The capabilities parameter corresponds to ESP-IDF’s MALLOC_CAP_XXX values but the two most useful ones
are predefined as esp32.HEAP_DATA for data heap regions and esp32.HEAP_EXEC for executable regions
as used by the native code emitter.
The return value is a list of 4-tuples, where each 4-tuple corresponds to one heap and contains: the total bytes, the
free bytes, the largest free block, and the minimum free seen over time.
Example after booting:

>>> import esp32; esp32.idf_heap_info(esp32.HEAP_DATA)


[(240, 0, 0, 0), (7288, 0, 0, 0), (16648, 4, 4, 4), (79912, 35712, 35512, 35108),
(15072, 15036, 15036, 15036), (113840, 0, 0, 0)]

Note: Free IDF heap memory in the esp32.HEAP_DATA region is available to be automatically added to the
MicroPython heap to prevent a MicroPython allocation from failing. However, the information returned here
is otherwise not useful to troubleshoot Python allocation failures. micropython.mem_info() and gc.
mem_free() should be used instead:
The “max new split” value in micropython.mem_info() output corresponds to the largest free block of
ESP-IDF heap that could be automatically added on demand to the MicroPython heap.
The result of gc.mem_free() is the total of the current “free” and “max new split” values printed by
micropython.mem_info().

Flash partitions

This class gives access to the partitions in the device’s flash memory and includes methods to enable over-the-air (OTA)
updates.
class esp32.Partition(id, block_size=4096, / )
Create an object representing a partition. id can be a string which is the label of the partition to retrieve, or one of
the constants: BOOT or RUNNING. block_size specifies the byte size of an individual block.
classmethod Partition.find(type=TYPE_APP, subtype=0xff, label=None, block_size=4096)
Find a partition specified by type, subtype and label. Returns a (possibly empty) list of Partition objects. Note:
subtype=0xff matches any subtype and label=None matches any label.
block_size specifies the byte size of an individual block used by the returned objects.

184 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

Partition.info()
Returns a 6-tuple (type, subtype, addr, size, label, encrypted).
Partition.readblocks(block_num, buf)
Partition.readblocks(block_num, buf, offset)

Partition.writeblocks(block_num, buf)
Partition.writeblocks(block_num, buf, offset)

Partition.ioctl(cmd, arg)
These methods implement the simple and extended block protocol defined by os.AbstractBlockDev.
Partition.set_boot()
Sets the partition as the boot partition.

Note: Do not enter deepsleep after changing the OTA boot partition, without first performing a hard reset
or power cycle. This ensures the bootloader will validate the new image before booting.

Partition.get_next_update()
Gets the next update partition after this one, and returns a new Partition object. Typical usage is
Partition(Partition.RUNNING).get_next_update() which returns the next partition to update
given the current running one.
classmethod Partition.mark_app_valid_cancel_rollback()
Signals that the current boot is considered successful. Calling mark_app_valid_cancel_rollback
is required on the first boot of a new partition to avoid an automatic rollback at the next boot. This uses
the ESP-IDF “app rollback” feature with “CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE” and an
OSError(-261) is raised if called on firmware that doesn’t have the feature enabled. It is OK to call
mark_app_valid_cancel_rollback on every boot and it is not necessary when booting firmware that
was loaded using esptool.

Constants

Partition.BOOT
Partition.RUNNING
Used in the Partition constructor to fetch various partitions: BOOT is the partition that will be booted at the
next reset and RUNNING is the currently running partition.
Partition.TYPE_APP
Partition.TYPE_DATA
Used in Partition.find to specify the partition type: APP is for bootable firmware partitions (typically
labelled factory, ota_0, ota_1), and DATA is for other partitions, e.g. nvs, otadata, phy_init, vfs.
esp32.HEAP_DATA
esp32.HEAP_EXEC
Used in idf_heap_info.

1.3. Port-specific libraries 185


MicroPython Documentation, Release v1.22.0

RMT

The RMT (Remote Control) module, specific to the ESP32, was originally designed to send and receive infrared remote
control signals. However, due to a flexible design and very accurate (as low as 12.5ns) pulse generation, it can also be
used to transmit or receive many other types of digital signals:

import esp32
from machine import Pin

r = esp32.RMT(0, pin=Pin(18), clock_div=8)


r # RMT(channel=0, pin=18, source_freq=80000000, clock_div=8, idle_level=0)

# To apply a carrier frequency to the high output


r = esp32.RMT(0, pin=Pin(18), clock_div=8, tx_carrier=(38000, 50, 1))

# The channel resolution is 100ns (1/(source_freq/clock_div)).


r.write_pulses((1, 20, 2, 40), 0) # Send 0 for 100ns, 1 for 2000ns, 0 for 200ns, 1␣
,→for 4000ns

The input to the RMT module is an 80MHz clock (in the future it may be able to configure the input clock but, for now,
it’s fixed). clock_div divides the clock input which determines the resolution of the RMT channel. The numbers
specified in write_pulses are multiplied by the resolution to define the pulses.
clock_div is an 8-bit divider (0-255) and each pulse can be defined by multiplying the resolution by a 15-bit (1-
PULSE_MAX) number. There are eight channels (0-7) and each can have a different clock divider.
So, in the example above, the 80MHz clock is divided by 8. Thus the resolution is (1/(80Mhz/8)) 100ns. Since the start
level is 0 and toggles with each number, the bitstream is 0101 with durations of [100ns, 2000ns, 100ns, 4000ns].
For more details see Espressif’s ESP-IDF RMT documentation..

Warning: The current MicroPython RMT implementation lacks some features, most notably receiving pulses. RMT
should be considered a beta feature and the interface may change in the future.

class esp32.RMT(channel, *, pin=None, clock_div=8, idle_level=False, tx_carrier=None)


This class provides access to one of the eight RMT channels. channel is required and identifies which RMT channel
(0-7) will be configured. pin, also required, configures which Pin is bound to the RMT channel. clock_div is an 8-bit
clock divider that divides the source clock (80MHz) to the RMT channel allowing the resolution to be specified.
idle_level specifies what level the output will be when no transmission is in progress and can be any value that
converts to a boolean, with True representing high voltage and False representing low.
To enable the transmission carrier feature, tx_carrier should be a tuple of three positive integers: carrier frequency,
duty percent (0 to 100) and the output level to apply the carrier to (a boolean as per idle_level).
classmethod RMT.source_freq()
Returns the source clock frequency. Currently the source clock is not configurable so this will always return 80MHz.
RMT.clock_div()
Return the clock divider. Note that the channel resolution is 1 / (source_freq / clock_div).
RMT.wait_done(*, timeout=0)
Returns True if the channel is idle or False if a sequence of pulses started with RMT.write_pulses is being
transmitted. If the timeout keyword argument is given then block for up to this many milliseconds for transmission
to complete.

186 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

RMT.loop(enable_loop)
Configure looping on the channel. enable_loop is bool, set to True to enable looping on the next call to RMT.
write_pulses. If called with False while a looping sequence is currently being transmitted then the current
loop iteration will be completed and then transmission will stop.
RMT.write_pulses(duration, data=True)
Begin transmitting a sequence. There are three ways to specify this:
Mode 1: duration is a list or tuple of durations. The optional data argument specifies the initial output level. The
output level will toggle after each duration.
Mode 2: duration is a positive integer and data is a list or tuple of output levels. duration specifies a fixed duration
for each.
Mode 3: duration and data are lists or tuples of equal length, specifying individual durations and the output level
for each.
Durations are in integer units of the channel resolution (as described above), between 1 and PULSE_MAX units.
Output levels are any value that can be converted to a boolean, with True representing high voltage and False
representing low.
If transmission of an earlier sequence is in progress then this method will block until that transmission is complete
before beginning the new sequence.
If looping has been enabled with RMT.loop, the sequence will be repeated indefinitely. Further calls to this
method will block until the end of the current loop iteration before immediately beginning to loop the new sequence
of pulses. Looping sequences longer than 126 pulses is not supported by the hardware.
static RMT.bitstream_channel([value ])
Select which RMT channel is used by the machine.bitstream implementation. value can be None or a valid
RMT channel number. The default RMT channel is the highest numbered one.
Passing in None disables the use of RMT and instead selects a bit-banging implementation for machine.
bitstream.
Passing in no argument will not change the channel. This function returns the current channel number.

Constants

RMT.PULSE_MAX
Maximum integer that can be set for a pulse duration.

Ultra-Low-Power co-processor

This class gives access to the Ultra Low Power (ULP) co-processor on the ESP32, ESP32-S2 and ESP32-S3 chips.

Warning: This class does not provide access to the RISCV ULP co-processor available on the ESP32-S2 and
ESP32-S3 chips.

class esp32.ULP
This class provides access to the Ultra-Low-Power co-processor.
ULP.set_wakeup_period(period_index, period_us)
Set the wake-up period.

1.3. Port-specific libraries 187


MicroPython Documentation, Release v1.22.0

ULP.load_binary(load_addr, program_binary)
Load a program_binary into the ULP at the given load_addr.
ULP.run(entry_point)
Start the ULP running at the given entry_point.

Constants

esp32.WAKEUP_ALL_LOW
esp32.WAKEUP_ANY_HIGH
Selects the wake level for pins.

Non-Volatile Storage

This class gives access to the Non-Volatile storage managed by ESP-IDF. The NVS is partitioned into namespaces and
each namespace contains typed key-value pairs. The keys are strings and the values may be various integer types, strings,
and binary blobs. The driver currently only supports 32-bit signed integers and blobs.

Warning: Changes to NVS need to be committed to flash by calling the commit method. Failure to call commit
results in changes being lost at the next reset.

class esp32.NVS(namespace)
Create an object providing access to a namespace (which is automatically created if not present).
NVS.set_i32(key, value)
Sets a 32-bit signed integer value for the specified key. Remember to call commit!
NVS.get_i32(key)
Returns the signed integer value for the specified key. Raises an OSError if the key does not exist or has a different
type.
NVS.set_blob(key, value)
Sets a binary blob value for the specified key. The value passed in must support the buffer protocol, e.g. bytes,
bytearray, str. (Note that esp-idf distinguishes blobs and strings, this method always writes a blob even if a string
is passed in as value.) Remember to call commit!
NVS.get_blob(key, buffer)
Reads the value of the blob for the specified key into the buffer, which must be a bytearray. Returns the actual
length read. Raises an OSError if the key does not exist, has a different type, or if the buffer is too small.
NVS.erase_key(key)
Erases a key-value pair.
NVS.commit()
Commits changes made by set_xxx methods to flash.

188 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

espnow — support for the ESP-NOW wireless protocol

This module provides an interface to the ESP-NOW protocol provided by Espressif on ESP32 and ESP8266 devices (API
docs).

Table of Contents:

• Introduction
• Configuration
• Sending and Receiving Data
• Peer Management
• Callback Methods
• Exceptions
• Constants
• Wifi Signal Strength (RSSI) - (ESP32 Only)
• Supporting asyncio
• Broadcast and Multicast
• ESPNow and Wifi Operation
• ESPNow and Sleep Modes

Introduction

ESP-NOW is a connection-less wireless communication protocol supporting:


• Direct communication between up to 20 registered peers:
– Without the need for a wireless access point (AP),
• Encrypted and unencrypted communication (up to 6 encrypted peers),
• Message sizes up to 250 bytes,
• Can operate alongside Wifi operation (network.WLAN) on ESP32 and ESP8266 devices.
It is especially useful for small IoT networks, latency sensitive or power sensitive applications (such as battery operated
devices) and for long-range communication between devices (hundreds of metres).
This module also supports tracking the Wifi signal strength (RSSI) of peer devices.
A simple example would be:
Sender:

import network
import espnow

# A WLAN interface must be active to send()/recv()


sta = network.WLAN(network.STA_IF) # Or network.AP_IF
sta.active(True)
sta.disconnect() # For ESP8266

(continues on next page)

1.3. Port-specific libraries 189


MicroPython Documentation, Release v1.22.0

(continued from previous page)


e = espnow.ESPNow()
e.active(True)
peer = b'\xbb\xbb\xbb\xbb\xbb\xbb' # MAC address of peer's wifi interface
e.add_peer(peer) # Must add_peer() before send()

e.send(peer, "Starting...")
for i in range(100):
e.send(peer, str(i)*20, True)
e.send(peer, b'end')

Receiver:

import network
import espnow

# A WLAN interface must be active to send()/recv()


sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.disconnect() # Because ESP8266 auto-connects to last Access Point

e = espnow.ESPNow()
e.active(True)

while True:
host, msg = e.recv()
if msg: # msg == None if timeout in recv()
print(host, msg)
if msg == b'end':
break

class ESPNow

Constructor

class espnow.ESPNow
Returns the singleton ESPNow object. As this is a singleton, all calls to espnow.ESPNow() return a reference
to the same object.

Note: Some methods are available only on the ESP32 due to code size restrictions on the ESP8266 and differences
in the Espressif API.

Configuration

ESPNow.active([flag ])
Initialise or de-initialise the ESP-NOW communication protocol depending on the value of the flag optional
argument.
Arguments:

• flag: Any python value which can be converted to a boolean type.

190 Chapter 1. MicroPython libraries


MicroPython Documentation, Release v1.22.0

– True: Prepare the software and hardware for use of the ESP-NOW communication protocol, in-
cluding:
∗ initialise the ESPNow data structures,
∗ allocate the recv data buffer,
∗ invoke esp_now_init() and
∗ register the send and recv callbacks.
– False: De-initialise the Espressif ESP-NOW software stack (esp_now_deinit()), disable callbacks,
deallocate the recv data buffer and deregister all peers.
If flag is not provided, return the current status of the ESPNow interface.
Returns:
True if interface is currently active, else False.
ESPNow.config(param=value, ...)
ESPNow.config('param') (ESP32 only)
Set or get configuration values of the ESPNow interface. To set values, use the keyword syntax, and one or more
parameters can be set at a time. To get a value the parameter name should be quoted as a string, and just one
parameter is queried at a time.
Note: Getting parameters is not supported on the ESP8266.
Options:
rxbuf: (default=526) Get/set the size in bytes of the internal buffer used to store incoming ESPNow
packet data. The default size is selected to fit two max-sized ESPNow packets (250 bytes) with associated
mac_address (6 bytes), a message byte count (1 byte) and RSSI data plus buffer overhead. Increase this if
you expect to receive a lot of large packets or expect bursty incoming traffic.
Note: The recv buffer is allocated by ESPNow.active(). Changing this value will have no effect until
the next call of ESPNow.active(True).
timeout_ms: (default=300,000) Default timeout (in milliseconds) for receiving ESPNow messages. If
timeout_ms is less than zero, then wait forever. The timeout can also be provided as arg to
recv()/irecv()/recvinto().
rate: (ESP32 only, IDF>=4.3.0 only) Set the transmission speed for ESPNow packets. Must be set to a
number from the allowed numeric values in enum wifi_phy_rate_t.
Returns:
None or the value of the parameter being queried.
Raises:

• OSError(num, "ESP_ERR_ESPNOW_NOT_INIT") if not initialised.


• ValueError() on invalid configuration options or values.

1.3. Port-specific libraries 191


MicroPython Documentation, Release v1.22.0

Sending and Receiving Data

A wifi interface (network.STA_IF or network.AP_IF) must be active()