# Table of Contents - [re – simple regular expressions — MicroPython latest documentation](#re-simple-regular-expressions-micropython-latest-documentation) - [MicroPython libraries — MicroPython latest documentation](#micropython-libraries-micropython-latest-documentation) - [marshal – Python object serialization — MicroPython latest documentation](#marshal-python-object-serialization-micropython-latest-documentation) - [Overview — MicroPython latest documentation](#overview-micropython-latest-documentation) - [array – arrays of numeric data — MicroPython latest documentation](#array-arrays-of-numeric-data-micropython-latest-documentation) - [binascii – binary/ASCII conversions — MicroPython latest documentation](#binascii-binary-ascii-conversions-micropython-latest-documentation) - [ssl – SSL/TLS module — MicroPython latest documentation](#ssl-ssl-tls-module-micropython-latest-documentation) - [cmath – mathematical functions for complex numbers — MicroPython latest documentation](#cmath-mathematical-functions-for-complex-numbers-micropython-latest-documentation) - [builtins – builtin functions and exceptions — MicroPython latest documentation](#builtins-builtin-functions-and-exceptions-micropython-latest-documentation) - [asyncio — asynchronous I/O scheduler — MicroPython latest documentation](#asyncio-asynchronous-i-o-scheduler-micropython-latest-documentation) - [sys – system specific functions — MicroPython latest documentation](#sys-system-specific-functions-micropython-latest-documentation) - [errno – system error codes — MicroPython latest documentation](#errno-system-error-codes-micropython-latest-documentation) - [collections – collection and container types — MicroPython latest documentation](#collections-collection-and-container-types-micropython-latest-documentation) - [gc – control the garbage collector — MicroPython latest documentation](#gc-control-the-garbage-collector-micropython-latest-documentation) - [hashlib – hashing algorithms — MicroPython latest documentation](#hashlib-hashing-algorithms-micropython-latest-documentation) - [gzip – gzip compression & decompression — MicroPython latest documentation](#gzip-gzip-compression-decompression-micropython-latest-documentation) - [os – basic “operating system” services — MicroPython latest documentation](#os-basic-operating-system-services-micropython-latest-documentation) - [random – generate random numbers — MicroPython latest documentation](#random-generate-random-numbers-micropython-latest-documentation) - [socket – socket module — MicroPython latest documentation](#socket-socket-module-micropython-latest-documentation) - [struct – pack and unpack primitive data types — MicroPython latest documentation](#struct-pack-and-unpack-primitive-data-types-micropython-latest-documentation) - [heapq – heap queue algorithm — MicroPython latest documentation](#heapq-heap-queue-algorithm-micropython-latest-documentation) - [select – wait for events on a set of streams — MicroPython latest documentation](#select-wait-for-events-on-a-set-of-streams-micropython-latest-documentation) - [io – input/output streams — MicroPython latest documentation](#io-input-output-streams-micropython-latest-documentation) - [platform – access to underlying platform’s identifying data — MicroPython latest documentation](#platform-access-to-underlying-platform-s-identifying-data-micropython-latest-documentation) - [json – JSON encoding and decoding — MicroPython latest documentation](#json-json-encoding-and-decoding-micropython-latest-documentation) - [math – mathematical functions — MicroPython latest documentation](#math-mathematical-functions-micropython-latest-documentation) - [time – time related functions — MicroPython latest documentation](#time-time-related-functions-micropython-latest-documentation) - [zlib – zlib compression & decompression — MicroPython latest documentation](#zlib-zlib-compression-decompression-micropython-latest-documentation) - [MicroPython language and implementation — MicroPython latest documentation](#micropython-language-and-implementation-micropython-latest-documentation) - [_thread – multithreading support — MicroPython latest documentation](#-thread-multithreading-support-micropython-latest-documentation) - [MicroPython differences from CPython — MicroPython latest documentation](#micropython-differences-from-cpython-micropython-latest-documentation) - [MicroPython Internals — MicroPython latest documentation](#micropython-internals-micropython-latest-documentation) - [MicroPython license information — MicroPython latest documentation](#micropython-license-information-micropython-latest-documentation) - [Quick reference for the pyboard — MicroPython latest documentation](#quick-reference-for-the-pyboard-micropython-latest-documentation) - [btree – simple BTree database — MicroPython latest documentation](#btree-simple-btree-database-micropython-latest-documentation) - [Quick reference for the ESP8266 — MicroPython latest documentation](#quick-reference-for-the-esp8266-micropython-latest-documentation) - [bluetooth — low-level Bluetooth — MicroPython latest documentation](#bluetooth-low-level-bluetooth-micropython-latest-documentation) - [Quick reference for the ESP32 — MicroPython latest documentation](#quick-reference-for-the-esp32-micropython-latest-documentation) - [cryptolib – cryptographic ciphers — MicroPython latest documentation](#cryptolib-cryptographic-ciphers-micropython-latest-documentation) - [Quick reference for the RP2 — MicroPython latest documentation](#quick-reference-for-the-rp2-micropython-latest-documentation) - [Quick reference for the WiPy — MicroPython latest documentation](#quick-reference-for-the-wipy-micropython-latest-documentation) - [Quick reference for the UNIX and Windows ports — MicroPython latest documentation](#quick-reference-for-the-unix-and-windows-ports-micropython-latest-documentation) - [machine — functions related to the hardware — MicroPython latest documentation](#machine-functions-related-to-the-hardware-micropython-latest-documentation) - [micropython – access and control MicroPython internals — MicroPython latest documentation](#micropython-access-and-control-micropython-internals-micropython-latest-documentation) - [deflate – deflate compression & decompression — MicroPython latest documentation](#deflate-deflate-compression-decompression-micropython-latest-documentation) - [framebuf — frame buffer manipulation — MicroPython latest documentation](#framebuf-frame-buffer-manipulation-micropython-latest-documentation) - [Quick reference for the i.MXRT family — MicroPython latest documentation](#quick-reference-for-the-i-mxrt-family-micropython-latest-documentation) - [neopixel — control of WS2812 / NeoPixel LEDs — MicroPython latest documentation](#neopixel-control-of-ws2812-neopixel-leds-micropython-latest-documentation) - [Quick reference for the Zephyr port — MicroPython latest documentation](#quick-reference-for-the-zephyr-port-micropython-latest-documentation) - [Quick reference for the Renesas RA — MicroPython latest documentation](#quick-reference-for-the-renesas-ra-micropython-latest-documentation) --- # re – simple regular expressions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `re` – simple regular expressions * [View page source](../_sources/library/re.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`re`](#module-re "re: regular expressions") – simple regular expressions[¶](#module-re "Link to this heading") ================================================================================================================= _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`re`](https://docs.python.org/3.5/library/re.html#module-re "(in Python v3.5)") . 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()`](#re.match.group "re.match.group") method). `\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...)`) * 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', '', ''\] Functions[¶](#functions "Link to this heading") ------------------------------------------------ re.compile(_regex\_str_\[, _flags_\])[¶](#re.compile "Link to this definition") Compile regular expression, return [regex](#regex) object. re.match(_regex\_str_, _string_)[¶](#re.match "Link to this definition") Compile _regex\_str_ and match against _string_. Match always happens from starting position in a string. re.search(_regex\_str_, _string_)[¶](#re.search "Link to this definition") Compile _regex\_str_ and search it in a _string_. Unlike [`match`](#re.match "re.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_, _/_)[¶](#re.sub "Link to this definition") 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 `\` and `\g` 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](../reference/glossary.html#term-MicroPython-port) . re.DEBUG[¶](#re.DEBUG "Link to this definition") Flag value, display debug information about compiled expression. (Availability depends on [MicroPython port](../reference/glossary.html#term-MicroPython-port) .) Regex objects[¶](#regex-objects "Link to this heading") -------------------------------------------------------- Compiled regular expression. Instances of this class are created using [`re.compile()`](#re.compile "re.compile") . regex.match(_string_)[¶](#re.regex.match "Link to this definition") regex.search(_string_)[¶](#re.regex.search "Link to this definition") regex.sub(_replace_, _string_, _count\=0_, _flags\=0_, _/_)[¶](#re.regex.sub "Link to this definition") Similar to the module-level functions [`match()`](#re.match "re.match") , [`search()`](#re.search "re.search") and [`sub()`](#re.sub "re.sub") . Using methods is (much) more efficient if the same regex is applied to multiple strings. regex.split(_string_, _max\_split\=\-1_, _/_)[¶](#re.regex.split "Link to this definition") 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 "Link to this heading") -------------------------------------------------------- Match objects as returned by [`match()`](#re.match "re.match") and [`search()`](#re.search "re.search") methods, and passed to the replacement function in [`sub()`](#re.sub "re.sub") . match.group(_index_)[¶](#re.match.group "Link to this definition") Return matching (sub)string. _index_ is 0 for entire match, 1 and above for each capturing group. Only numeric groups are supported. match.groups()[¶](#re.match.groups "Link to this definition") Return a tuple containing all the substrings of the groups of the match. Note: availability of this method depends on [MicroPython port](../reference/glossary.html#term-MicroPython-port) . match.start(\[_index_\])[¶](#re.match.start "Link to this definition") match.end(\[_index_\])[¶](#re.match.end "Link to this definition") 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](../reference/glossary.html#term-MicroPython-port) . match.span(\[_index_\])[¶](#re.match.span "Link to this definition") Returns the 2-tuple `(match.start(index), match.end(index))`. Note: availability of this method depends on [MicroPython port](../reference/glossary.html#term-MicroPython-port) . Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # MicroPython libraries — MicroPython latest documentation * [](../index.html) * MicroPython libraries * [View page source](../_sources/library/index.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython libraries[¶](#micropython-libraries "Link to this heading") ======================================================================== Warning Important summary of this section * MicroPython provides built-in modules that mirror the functionality of the [Python standard library](#micropython-lib-python) (e.g. [`os`](os.html#module-os "os: basic "operating system" services") , [`time`](time.html#module-time "time: time related functions") ), as well as [MicroPython-specific modules](#micropython-lib-micropython) (e.g. [`bluetooth`](bluetooth.html#module-bluetooth "bluetooth: Low-level Bluetooth radio functionality") , [`machine`](machine.html#module-machine "machine: functions related to the hardware") ). * 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`](array.html#module-array "array: efficient arrays of numeric data") , [`os`](os.html#module-os "os: basic "operating system" services") ) * Due to resource constraints or other limitations, some ports or firmware versions may not include all the functionality documented here. * To allow for extensibility, some built-in modules can be [extended from Python code](#micropython-lib-extending) 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](../reference/glossary.html#term-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](../reference/glossary.html#term-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](../reference/glossary.html#term-micropython-lib) . Python standard libraries and micro-libraries[¶](#python-standard-libraries-and-micro-libraries "Link to this heading") ------------------------------------------------------------------------------------------------------------------------ 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. * [`array` – arrays of numeric data](array.html) * [`asyncio` — asynchronous I/O scheduler](asyncio.html) * [`binascii` – binary/ASCII conversions](binascii.html) * [`builtins` – builtin functions and exceptions](builtins.html) * [`cmath` – mathematical functions for complex numbers](cmath.html) * [`collections` – collection and container types](collections.html) * [`errno` – system error codes](errno.html) * [`gc` – control the garbage collector](gc.html) * [`gzip` – gzip compression & decompression](gzip.html) * [`hashlib` – hashing algorithms](hashlib.html) * [`heapq` – heap queue algorithm](heapq.html) * [`io` – input/output streams](io.html) * [`json` – JSON encoding and decoding](json.html) * [`marshal` – Python object serialization](marshal.html) * [`math` – mathematical functions](math.html) * [`os` – basic “operating system” services](os.html) * [`platform` – access to underlying platform’s identifying data](platform.html) * [`random` – generate random numbers](random.html) * [`re` – simple regular expressions](re.html) * [`select` – wait for events on a set of streams](select.html) * [`socket` – socket module](socket.html) * [`ssl` – SSL/TLS module](ssl.html) * [`struct` – pack and unpack primitive data types](struct.html) * [`sys` – system specific functions](sys.html) * [`time` – time related functions](time.html) * [`zlib` – zlib compression & decompression](zlib.html) * [`_thread` – multithreading support](_thread.html) MicroPython-specific libraries[¶](#micropython-specific-libraries "Link to this heading") ------------------------------------------------------------------------------------------ Functionality specific to the MicroPython implementation is available in the following libraries. * [`bluetooth` — low-level Bluetooth](bluetooth.html) * [`btree` – simple BTree database](btree.html) * [`cryptolib` – cryptographic ciphers](cryptolib.html) * [`deflate` – deflate compression & decompression](deflate.html) * [`framebuf` — frame buffer manipulation](framebuf.html) * [`machine` — functions related to the hardware](machine.html) * [`micropython` – access and control MicroPython internals](micropython.html) * [`neopixel` — control of WS2812 / NeoPixel LEDs](neopixel.html) * [`network` — network configuration](network.html) * [`openamp` – provides standard Asymmetric Multiprocessing (AMP) support](openamp.html) * [`uctypes` – access binary data in a structured way](uctypes.html) * [`vfs` – virtual filesystem control](vfs.html) The following libraries provide drivers for hardware components. * [`WM8960` – Driver for the WM8960 codec](wm8960.html) Port-specific libraries[¶](#port-specific-libraries "Link to this heading") ---------------------------------------------------------------------------- In some cases the following port/board-specific libraries have functions or classes similar to those in the [`machine`](machine.html#module-machine "machine: functions related to the hardware") 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`](machine.html#module-machine "machine: functions related to the hardware") module. To access platform-specific hardware use the appropriate library, e.g. [`pyb`](pyb.html#module-pyb "pyb: functions related to the board") in the case of the Pyboard. ### Libraries specific to the pyboard[¶](#libraries-specific-to-the-pyboard "Link to this heading") The following libraries are specific to the pyboard. * [`pyb` — functions related to the board](pyb.html) * [Time related functions](pyb.html#time-related-functions) * [Reset related functions](pyb.html#reset-related-functions) * [Interrupt related functions](pyb.html#interrupt-related-functions) * [Power related functions](pyb.html#power-related-functions) * [Miscellaneous functions](pyb.html#miscellaneous-functions) * [Constants](pyb.html#constants) * [Classes](pyb.html#classes) * [`stm` — functionality specific to STM32 MCUs](stm.html) * [Memory access](stm.html#memory-access) * [Peripheral register constants](stm.html#peripheral-register-constants) * [Functions specific to STM32WBxx MCUs](stm.html#functions-specific-to-stm32wbxx-mcus) * [Functions specific to STM32WLxx MCUs](stm.html#functions-specific-to-stm32wlxx-mcus) * [`lcd160cr` — control of LCD160CR display](lcd160cr.html) * [class LCD160CR](lcd160cr.html#class-lcd160cr) * [Constructors](lcd160cr.html#constructors) * [Static methods](lcd160cr.html#static-methods) * [Instance members](lcd160cr.html#instance-members) * [Setup commands](lcd160cr.html#setup-commands) * [Pixel access methods](lcd160cr.html#pixel-access-methods) * [Drawing text](lcd160cr.html#drawing-text) * [Drawing primitive shapes](lcd160cr.html#drawing-primitive-shapes) * [Touch screen methods](lcd160cr.html#touch-screen-methods) * [Advanced commands](lcd160cr.html#advanced-commands) * [Constants](lcd160cr.html#constants) ### Libraries specific to the WiPy[¶](#libraries-specific-to-the-wipy "Link to this heading") The following libraries and classes are specific to the WiPy. * [`wipy` – WiPy specific features](wipy.html) * [Functions](wipy.html#functions) * [class ADCWiPy – analog to digital conversion](machine.ADCWiPy.html) * [Constructors](machine.ADCWiPy.html#constructors) * [Methods](machine.ADCWiPy.html#methods) * [class ADCChannel — read analog values from internal or external sources](machine.ADCWiPy.html#class-adcchannel-read-analog-values-from-internal-or-external-sources) * [`adcchannel()`](machine.ADCWiPy.html#machine.adcchannel) * [`adcchannel.value()`](machine.ADCWiPy.html#machine.adcchannel.value) * [`adcchannel.init()`](machine.ADCWiPy.html#machine.adcchannel.init) * [`adcchannel.deinit()`](machine.ADCWiPy.html#machine.adcchannel.deinit) * [class TimerWiPy – control hardware timers](machine.TimerWiPy.html) * [Constructors](machine.TimerWiPy.html#constructors) * [Methods](machine.TimerWiPy.html#methods) * [class TimerChannel — setup a channel for a timer](machine.TimerWiPy.html#class-timerchannel-setup-a-channel-for-a-timer) * [Methods](machine.TimerWiPy.html#id1) * [Constants](machine.TimerWiPy.html#constants) ### Libraries specific to the ESP8266 and ESP32[¶](#libraries-specific-to-the-esp8266-and-esp32 "Link to this heading") The following libraries are specific to the ESP8266 and ESP32. * [`esp` — functions related to the ESP8266 and ESP32](esp.html) * [Functions](esp.html#functions) * [`esp32` — functionality specific to the ESP32](esp32.html) * [Functions](esp32.html#functions) * [Flash partitions](esp32.html#flash-partitions) * [RMT](esp32.html#rmt) * [Constants](esp32.html#id1) * [Ultra-Low-Power co-processor](esp32.html#ultra-low-power-co-processor) * [Constants](esp32.html#id2) * [Non-Volatile Storage](esp32.html#non-volatile-storage) * [`espnow` — support for the ESP-NOW wireless protocol](espnow.html) ### Libraries specific to the RP2040[¶](#libraries-specific-to-the-rp2040 "Link to this heading") The following libraries are specific to the RP2040, as used in the Raspberry Pi Pico. * [`rp2` — functionality specific to the RP2040](rp2.html) * [PIO related functions](rp2.html#pio-related-functions) * [PIO assembly language instructions](rp2.html#pio-assembly-language-instructions) * [Classes](rp2.html#classes) ### Libraries specific to Zephyr[¶](#libraries-specific-to-zephyr "Link to this heading") The following libraries are specific to the Zephyr port. * [`zephyr` — functionality specific to the Zephyr port](zephyr.html) * [Functions](zephyr.html#functions) * [Classes](zephyr.html#classes) * [Additional Modules](zephyr.html#additional-modules) Extending built-in libraries from Python[¶](#extending-built-in-libraries-from-python "Link to this heading") -------------------------------------------------------------------------------------------------------------- A subset of the built-in modules are able to be extended by Python code by providing a module of the same name in the filesystem. This extensibility applies to the following Python standard library modules which are built-in to the firmware: `array`, `binascii`, `collections`, `errno`, `gzip`, `hashlib`, `heapq`, `io`, `json`, `os`, `platform`, `random`, `re`, `select`, `socket`, `ssl`, `struct`, `time` `zlib`, as well as the MicroPython-specific `machine` module. All other built-in modules cannot be extended from the filesystem. This allows the user to provide an extended implementation of a built-in library (perhaps to provide additional CPython compatibility or missing functionality). This is used extensively in [micropython-lib](../reference/glossary.html#term-micropython-lib) , see [Package management](../reference/packages.html#packages) for more information. The filesystem module will typically do a wildcard import of the built-in module in order to inherit all the globals (classes, functions and variables) from the built-in. In MicroPython v1.21.0 and higher, to prevent the filesystem module from importing itself, it can force an import of the built-in module it by temporarily clearing `sys.path` during the import. For example, to extend the `time` module from Python, a file named `time.py` on the filesystem would do the following: \_path \= sys.path sys.path \= () try: from time import \* finally: sys.path \= \_path del \_path def extra\_method(): pass The result is that `time.py` contains all the globals of the built-in `time` module, but adds `extra_method`. In earlier versions of MicroPython, you can force an import of a built-in module by appending a `u` to the start of its name. For example, `import utime` instead of `import time`. For example, `time.py` on the filesystem could look like: from utime import \* def extra\_method(): pass This way is still supported, but the `sys.path` method described above is now preferred as the `u`\-prefix will be removed from the names of built-in modules in a future version of MicroPython. _Other than when it specifically needs to force the use of the built-in module, code should always use_ `import module` _rather than_ `import umodule`. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # marshal – Python object serialization — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `marshal` – Python object serialization * [View page source](../_sources/library/marshal.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`marshal`](#module-marshal "marshal: Convert Python objects to and from a binary format") – Python object serialization[¶](#module-marshal "Link to this heading") ===================================================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`marshal`](https://docs.python.org/3.5/library/marshal.html#module-marshal "(in Python v3.5)") . This module implements conversion between Python objects and a binary format. The format is specific to MicroPython but does not depend on the machine architecture, so the data can be transferred and used on a different MicroPython instance, as long as the version of the binary data matches (it’s currently versioned as the mpy file version, see [MicroPython .mpy files](../reference/mpyfiles.html#mpy-files) ). Functions[¶](#functions "Link to this heading") ------------------------------------------------ marshal.dumps(_value_, _/_)[¶](#marshal.dumps "Link to this definition") Convert the given _value_ to binary format and return a corresponding `bytes` object. Currently, code objects are the only supported values that can be converted. marshal.loads(_data_, _/_)[¶](#marshal.loads "Link to this definition") Convert the given bytes-like _data_ to its corresponding Python object, and return it. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Overview — MicroPython latest documentation * [](#) * Overview * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython documentation ========================= Welcome! This is the documentation for MicroPython, last updated 12 Apr 2025. MicroPython runs on a variety of systems and hardware platforms. Here you can read the general documentation which applies to all systems, as well as specific information about the various platforms - also known as [ports](reference/glossary.html#term-micropython-port) - that MicroPython runs on. **General documentation for MicroPython:** | | | | --- | --- | | [Library Reference](library/index.html)

MicroPython libraries and modules

[MicroPython Differences](genrst/index.html)

MicroPython operations which differ from CPython | [Language Reference](reference/index.html)

information about MicroPython specific language features

[License](license.html)

MicroPython license information | **References and tutorials for specific platforms:** [Quick reference for the pyboard](pyboard/quickref.html) pinout for the pyboard, snippets of useful code, and a tutorial [Quick reference for the ESP8266](esp8266/quickref.html) pinout for ESP8266-based boards, snippets of useful code, and a tutorial [Quick reference for the ESP32](esp32/quickref.html) pinout for ESP32-based boards, snippets of useful code, and a tutorial [Quick reference for the Raspberry Pi RP2xxx](rp2/quickref.html) pinout for rp2xxx-based boards, snippets of useful code, and a tutorial [Quick reference for the NXP i.MXRT 10xx](mimxrt/quickref.html) general introduction, snippets of useful code, and a tutorial [Quick reference for the WiPy/CC3200](wipy/quickref.html) pinout for the WiPy/CC3200, snippets of useful code, and a tutorial [Quick reference for UNIX and Windows](unix/quickref.html) command-line reference [Quick reference for the Zephyr port](zephyr/quickref.html) snippets of useful code and a tutorial [Quick reference for the Renesas RA](renesas-ra/quickref.html) general information for Renesas RA based boards, snippets of useful code, and a tutorial [Quick reference for the SAMD21/SAMD51](samd/quickref.html) general information for SAMD21/SAMD51 based boards, snippets of useful code, and a tutorial **Indices and tables:** | | | | --- | --- | | [Module index](py-modindex.html)

quick access to all modules

[Full index](genindex.html)

all functions, classes, constants | [Glossary](reference/glossary.html)

MicroPython terms explained

[Table of contents](#)

a list of all sections and subsections | **External links:** | | | | --- | --- | | [MicroPython homepage](http://micropython.org)

the official MicroPython site

[GitHub Discussions](https://github.com/orgs/micropython/discussions)

community discussion for all things related to MicroPython | [MicroPython on GitHub](https://github.com/micropython)

contribute to the source code on GitHub | Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # array – arrays of numeric data — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `array` – arrays of numeric data * [View page source](../_sources/library/array.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`array`](#module-array "array: efficient arrays of numeric data") – arrays of numeric data[¶](#module-array "Link to this heading") ====================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`array`](https://docs.python.org/3.5/library/array.html#module-array "(in Python v3.5)") . 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[¶](#classes "Link to this heading") -------------------------------------------- _class_ array.array(_typecode_\[, _iterable_\])[¶](#array.array "Link to this definition") 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. In addition to the methods below, array objects also implement the buffer protocol. This means the contents of the entire array can be accessed as raw bytes via a [`memoryview`](builtins.html#memoryview "memoryview") or other interfaces which use this protocol. append(_val_)[¶](#array.array.append "Link to this definition") Append new element _val_ to the end of array, growing it. extend(_iterable_)[¶](#array.array.extend "Link to this definition") Append new elements as contained in _iterable_ to the end of array, growing it. \_\_getitem\_\_(_index_)[¶](#array.array.__getitem__ "Link to this definition") 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_)[¶](#array.array.__setitem__ "Link to this definition") 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\_\_()[¶](#array.array.__len__ "Link to this definition") 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_)[¶](#array.array.__add__ "Link to this definition") 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. \_\_iadd\_\_(_other_)[¶](#array.array.__iadd__ "Link to this definition") 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\_\_()[¶](#array.array.__repr__ "Link to this definition") Returns the string representation of the array, called as `str(a)` or `` repr(a)` `` (where `a` is an `array`). Returns the string `"array(, [])"`, where `` is the type code letter for the array and `` 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # binascii – binary/ASCII conversions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `binascii` – binary/ASCII conversions * [View page source](../_sources/library/binascii.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`binascii`](#module-binascii "binascii: binary/ASCII conversions") – binary/ASCII conversions[¶](#module-binascii "Link to this heading") ============================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`binascii`](https://docs.python.org/3.5/library/binascii.html#module-binascii "(in Python v3.5)") . This module implements conversions between binary data and various encodings of it in ASCII form (in both directions). Functions[¶](#functions "Link to this heading") ------------------------------------------------ binascii.hexlify(_data_\[, _sep_\])[¶](#binascii.hexlify "Link to this definition") 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_)[¶](#binascii.unhexlify "Link to this definition") Convert hexadecimal data to binary representation. Returns bytes string. (i.e. inverse of hexlify) binascii.a2b\_base64(_data_)[¶](#binascii.a2b_base64 "Link to this definition") Decode base64-encoded data, ignoring invalid characters in the input. Conforms to [RFC 2045 s.6.8](https://tools.ietf.org/html/rfc2045#section-6.8) . Returns a bytes object. binascii.b2a\_base64(_data_, _\*_, _newline\=True_)[¶](#binascii.b2a_base64 "Link to this definition") Encode binary data in base64 format, as in [RFC 3548](https://tools.ietf.org/html/rfc3548.html) . Returns the encoded data followed by a newline character if newline is true, as a bytes object. binascii.crc32(_data_\[, _value_\])[¶](#binascii.crc32 "Link to this definition") Compute CRC-32, the 32-bit checksum of _data_, starting with an initial CRC of _value_. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # ssl – SSL/TLS module — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `ssl` – SSL/TLS module * [View page source](../_sources/library/ssl.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`ssl`](#module-ssl "ssl: TLS/SSL wrapper for socket objects") – SSL/TLS module[¶](#module-ssl "Link to this heading") ======================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`ssl`](https://docs.python.org/3.5/library/ssl.html#module-ssl "(in Python v3.5)") . This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. Functions[¶](#functions "Link to this heading") ------------------------------------------------ ssl.wrap\_socket(_sock_, _server\_side\=False_, _key\=None_, _cert\=None_, _cert\_reqs\=CERT\_NONE_, _cadata\=None_, _server\_hostname\=None_, _do\_handshake\=True_)[¶](#ssl.ssl.wrap_socket "Link to this definition") > Wrap the given _sock_ and return a new wrapped-socket object. The implementation of this function is to first create an [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") > and then call the [`SSLContext.wrap_socket`](#ssl.SSLContext.wrap_socket "ssl.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](../reference/glossary.html#term-MicroPython-port) , some or all keyword arguments above may be not supported. class SSLContext[¶](#class-sslcontext "Link to this heading") -------------------------------------------------------------- _class_ ssl.SSLContext(_protocol_, _/_)[¶](#ssl.SSLContext "Link to this definition") Create a new SSLContext instance. The _protocol_ argument must be one of the `PROTOCOL_*` constants. SSLContext.load\_cert\_chain(_certfile_, _keyfile_)[¶](#ssl.SSLContext.load_cert_chain "Link to this definition") 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_)[¶](#ssl.SSLContext.load_verify_locations "Link to this definition") 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()[¶](#ssl.SSLContext.get_ciphers "Link to this definition") Get a list of enabled ciphers, returned as a list of strings. SSLContext.set\_ciphers(_ciphers_)[¶](#ssl.SSLContext.set_ciphers "Link to this definition") Set the available ciphers for sockets created with this context. _ciphers_ should be a list of strings in the [IANA cipher suite format](https://wiki.mozilla.org/Security/Cipher_Suites) . SSLContext.wrap\_socket(_sock_, _\*_, _server\_side\=False_, _do\_handshake\_on\_connect\=True_, _server\_hostname\=None_)[¶](#ssl.SSLContext.wrap_socket "Link to this definition") Takes a [`stream`](../reference/glossary.html#term-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`](../reference/glossary.html#term-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()`](socket.html#socket.socket.accept "socket.socket.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 handshake 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 connection 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[¶](#ssl.SSLContext.verify_mode "Link to this definition") 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](../reference/mpremote.html#mpremote-command-rtc) or `ntptime`, and `server_hostname` must be specified when on the client side. Exceptions[¶](#exceptions "Link to this heading") -------------------------------------------------- ssl.SSLError[¶](#ssl.ssl.SSLError "Link to this definition") This exception does NOT exist. Instead its base class, OSError, is used. DTLS support[¶](#dtls-support "Link to this heading") ------------------------------------------------------ Difference to CPython This is a MicroPython extension. This module supports DTLS in client and server mode via the [`PROTOCOL_DTLS_CLIENT`](#ssl.ssl.PROTOCOL_DTLS_CLIENT "ssl.ssl.PROTOCOL_DTLS_CLIENT") and [`PROTOCOL_DTLS_SERVER`](#ssl.ssl.PROTOCOL_DTLS_SERVER "ssl.ssl.PROTOCOL_DTLS_SERVER") constants that can be used as the `protocol` argument of [`SSLContext`](#ssl.SSLContext "ssl.SSLContext") . In this case the underlying socket is expected to behave as a datagram socket (i.e. like the socket opened with `socket.socket` with `socket.AF_INET` as `af` and `socket.SOCK_DGRAM` as `type`). DTLS is only supported on ports that use mbed TLS, and it is not enabled by default: it requires enabling `MBEDTLS_SSL_PROTO_DTLS` in the specific port configuration. Constants[¶](#constants "Link to this heading") ------------------------------------------------ ssl.PROTOCOL\_TLS\_CLIENT[¶](#ssl.ssl.PROTOCOL_TLS_CLIENT "Link to this definition") ssl.PROTOCOL\_TLS\_SERVER[¶](#ssl.ssl.PROTOCOL_TLS_SERVER "Link to this definition") ssl.PROTOCOL\_DTLS\_CLIENT(_when DTLS support is enabled_)[¶](#ssl.ssl.PROTOCOL_DTLS_CLIENT "Link to this definition") ssl.PROTOCOL\_DTLS\_SERVER(_when DTLS support is enabled_)[¶](#ssl.ssl.PROTOCOL_DTLS_SERVER "Link to this definition") Supported values for the _protocol_ parameter. ssl.CERT\_NONE[¶](#ssl.ssl.CERT_NONE "Link to this definition") ssl.CERT\_OPTIONAL[¶](#ssl.ssl.CERT_OPTIONAL "Link to this definition") ssl.CERT\_REQUIRED[¶](#ssl.ssl.CERT_REQUIRED "Link to this definition") Supported values for _cert\_reqs_ parameter, and the [`SSLContext.verify_mode`](#ssl.SSLContext.verify_mode "ssl.SSLContext.verify_mode") attribute. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # cmath – mathematical functions for complex numbers — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `cmath` – mathematical functions for complex numbers * [View page source](../_sources/library/cmath.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`cmath`](#module-cmath "cmath: mathematical functions for complex numbers") – mathematical functions for complex numbers[¶](#module-cmath "Link to this heading") ==================================================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`cmath`](https://docs.python.org/3.5/library/cmath.html#module-cmath "(in Python v3.5)") . 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[¶](#functions "Link to this heading") ------------------------------------------------ cmath.cos(_z_)[¶](#cmath.cos "Link to this definition") Return the cosine of `z`. cmath.exp(_z_)[¶](#cmath.exp "Link to this definition") Return the exponential of `z`. cmath.log(_z_)[¶](#cmath.log "Link to this definition") Return the natural logarithm of `z`. The branch cut is along the negative real axis. cmath.log10(_z_)[¶](#cmath.log10 "Link to this definition") Return the base-10 logarithm of `z`. The branch cut is along the negative real axis. cmath.phase(_z_)[¶](#cmath.phase "Link to this definition") Returns the phase of the number `z`, in the range (-pi, +pi\]. cmath.polar(_z_)[¶](#cmath.polar "Link to this definition") Returns, as a tuple, the polar form of `z`. cmath.rect(_r_, _phi_)[¶](#cmath.rect "Link to this definition") Returns the complex number with modulus `r` and phase `phi`. cmath.sin(_z_)[¶](#cmath.sin "Link to this definition") Return the sine of `z`. cmath.sqrt(_z_)[¶](#cmath.sqrt "Link to this definition") Return the square-root of `z`. Constants[¶](#constants "Link to this heading") ------------------------------------------------ cmath.e[¶](#cmath.e "Link to this definition") base of the natural logarithm cmath.pi[¶](#cmath.pi "Link to this definition") the ratio of a circle’s circumference to its diameter Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # builtins – builtin functions and exceptions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `builtins` – builtin functions and exceptions * [View page source](../_sources/library/builtins.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`builtins`](https://docs.python.org/3.5/library/builtins.html#module-builtins "(in Python v3.5)") – builtin functions and exceptions[¶](#builtins-builtin-functions-and-exceptions "Link to this heading") ============================================================================================================================================================================================================= All builtin functions and exceptions are described here. They are also available via `builtins` module. Functions and types[¶](#functions-and-types "Link to this heading") -------------------------------------------------------------------- abs()[¶](#abs "Link to this definition") all()[¶](#all "Link to this definition") any()[¶](#any "Link to this definition") bin()[¶](#bin "Link to this definition") _class_ bool[¶](#bool "Link to this definition") _class_ bytearray[¶](#bytearray "Link to this definition") See CPython documentation: [`bytearray`](https://docs.python.org/3.5/library/functions.html#bytearray "(in Python v3.5)") . _class_ bytes[¶](#bytes "Link to this definition") See CPython documentation: [`bytes`](https://docs.python.org/3.5/library/functions.html#bytes "(in Python v3.5)") . callable()[¶](#callable "Link to this definition") chr()[¶](#chr "Link to this definition") classmethod()[¶](#classmethod "Link to this definition") compile()[¶](#compile "Link to this definition") _class_ complex[¶](#complex "Link to this definition") delattr(_obj_, _name_)[¶](#delattr "Link to this definition") The argument _name_ should be a string, and this function deletes the named attribute from the object given by _obj_. _class_ dict[¶](#dict "Link to this definition") dir()[¶](#dir "Link to this definition") divmod()[¶](#divmod "Link to this definition") enumerate()[¶](#enumerate "Link to this definition") eval()[¶](#eval "Link to this definition") exec()[¶](#exec "Link to this definition") filter()[¶](#filter "Link to this definition") _class_ float[¶](#float "Link to this definition") _class_ frozenset[¶](#frozenset "Link to this definition") getattr()[¶](#getattr "Link to this definition") globals()[¶](#globals "Link to this definition") hasattr()[¶](#hasattr "Link to this definition") hash()[¶](#hash "Link to this definition") hex()[¶](#hex "Link to this definition") id()[¶](#id "Link to this definition") input()[¶](#input "Link to this definition") _class_ int[¶](#int "Link to this definition") _classmethod_ from\_bytes(_bytes_, _byteorder_)[¶](#int.from_bytes "Link to this definition") In MicroPython, [`byteorder`](sys.html#sys.byteorder "sys.byteorder") parameter must be positional (this is compatible with CPython). to\_bytes(_size_, _byteorder_)[¶](#int.to_bytes "Link to this definition") In MicroPython, [`byteorder`](sys.html#sys.byteorder "sys.byteorder") parameter must be positional (this is compatible with CPython). Note The optional `signed` kwarg from CPython is not supported. MicroPython currently converts negative integers as signed, and positive as unsigned. ([Details](../genrst/builtin_types.html#cpydiff-types-int-to-bytes) .) isinstance()[¶](#isinstance "Link to this definition") issubclass()[¶](#issubclass "Link to this definition") iter()[¶](#iter "Link to this definition") len()[¶](#len "Link to this definition") _class_ list[¶](#list "Link to this definition") locals()[¶](#locals "Link to this definition") map()[¶](#map "Link to this definition") max()[¶](#max "Link to this definition") _class_ memoryview[¶](#memoryview "Link to this definition") See CPython documentation: [`memoryview`](https://docs.python.org/3.5/library/stdtypes.html#memoryview "(in Python v3.5)") . min()[¶](#min "Link to this definition") next()[¶](#next "Link to this definition") _class_ object[¶](#object "Link to this definition") oct()[¶](#oct "Link to this definition") open()[¶](#open "Link to this definition") ord()[¶](#ord "Link to this definition") pow()[¶](#pow "Link to this definition") print()[¶](#print "Link to this definition") property()[¶](#property "Link to this definition") range()[¶](#range "Link to this definition") repr()[¶](#repr "Link to this definition") reversed()[¶](#reversed "Link to this definition") round()[¶](#round "Link to this definition") _class_ set[¶](#set "Link to this definition") setattr()[¶](#setattr "Link to this definition") _class_ slice[¶](#slice "Link to this definition") The _slice_ builtin is the type that slice objects have. sorted()[¶](#sorted "Link to this definition") staticmethod()[¶](#staticmethod "Link to this definition") _class_ str[¶](#str "Link to this definition") sum()[¶](#sum "Link to this definition") super()[¶](#super "Link to this definition") _class_ tuple[¶](#tuple "Link to this definition") type()[¶](#type "Link to this definition") zip()[¶](#zip "Link to this definition") Exceptions[¶](#exceptions "Link to this heading") -------------------------------------------------- _exception_ AssertionError[¶](#AssertionError "Link to this definition") _exception_ AttributeError[¶](#AttributeError "Link to this definition") _exception_ Exception[¶](#Exception "Link to this definition") _exception_ ImportError[¶](#ImportError "Link to this definition") _exception_ IndexError[¶](#IndexError "Link to this definition") _exception_ KeyboardInterrupt[¶](#KeyboardInterrupt "Link to this definition") See CPython documentation: [`KeyboardInterrupt`](https://docs.python.org/3.5/library/exceptions.html#KeyboardInterrupt "(in Python v3.5)") . See also in the context of [Soft Bricking (failure to boot)](../reference/reset_boot.html#soft-bricking) . _exception_ KeyError[¶](#KeyError "Link to this definition") _exception_ MemoryError[¶](#MemoryError "Link to this definition") _exception_ NameError[¶](#NameError "Link to this definition") _exception_ NotImplementedError[¶](#NotImplementedError "Link to this definition") _exception_ OSError[¶](#OSError "Link to this definition") _exception_ RuntimeError[¶](#RuntimeError "Link to this definition") _exception_ StopIteration[¶](#StopIteration "Link to this definition") _exception_ SyntaxError[¶](#SyntaxError "Link to this definition") _exception_ SystemExit[¶](#SystemExit "Link to this definition") See CPython documentation: [`SystemExit`](https://docs.python.org/3.5/library/exceptions.html#SystemExit "(in Python v3.5)") . On non-embedded ports (i.e. Windows and Unix), an unhandled `SystemExit` exits the MicroPython process in a similar way to CPython. On embedded ports, an unhandled `SystemExit` currently causes a [Soft Reset](../reference/reset_boot.html#soft-reset) of MicroPython. _exception_ TypeError[¶](#TypeError "Link to this definition") See CPython documentation: [`TypeError`](https://docs.python.org/3.5/library/exceptions.html#TypeError "(in Python v3.5)") . _exception_ ValueError[¶](#ValueError "Link to this definition") _exception_ ZeroDivisionError[¶](#ZeroDivisionError "Link to this definition") Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # asyncio — asynchronous I/O scheduler — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `asyncio` — asynchronous I/O scheduler * [View page source](../_sources/library/asyncio.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`asyncio`](#module-asyncio "asyncio: asynchronous I/O scheduler for writing concurrent code") — asynchronous I/O scheduler[¶](#module-asyncio "Link to this heading") ======================================================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [asyncio](https://docs.python.org/3.8/library/asyncio.html) 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[¶](#core-functions "Link to this heading") ---------------------------------------------------------- asyncio.create\_task(_coro_)[¶](#asyncio.create_task "Link to this definition") Create a new task from the given coroutine and schedule it to run. Returns the corresponding [`Task`](#asyncio.Task "asyncio.Task") object. asyncio.current\_task()[¶](#asyncio.current_task "Link to this definition") Return the [`Task`](#asyncio.Task "asyncio.Task") object associated with the currently running task. asyncio.run(_coro_)[¶](#asyncio.run "Link to this definition") Create a new task from the given coroutine and run it until it completes. Returns the value returned by _coro_. asyncio.sleep(_t_)[¶](#asyncio.sleep "Link to this definition") Sleep for _t_ seconds (can be a float). This is a coroutine. asyncio.sleep\_ms(_t_)[¶](#asyncio.sleep_ms "Link to this definition") Sleep for _t_ milliseconds. This is a coroutine, and a MicroPython extension. Additional functions[¶](#additional-functions "Link to this heading") ---------------------------------------------------------------------- asyncio.wait\_for(_awaitable_, _timeout_)[¶](#asyncio.wait_for "Link to this definition") 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_)[¶](#asyncio.wait_for_ms "Link to this definition") Similar to [`wait_for`](#asyncio.wait_for "asyncio.wait_for") but _timeout_ is an integer in milliseconds. This is a coroutine, and a MicroPython extension. asyncio.gather(_\*awaitables_, _return\_exceptions\=False_)[¶](#asyncio.gather "Link to this definition") 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-task "Link to this heading") -------------------------------------------------- _class_ asyncio.Task[¶](#asyncio.Task "Link to this definition") 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`](#asyncio.create_task "asyncio.create_task") to create them. Task.cancel()[¶](#asyncio.Task.cancel "Link to this definition") 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`. class Event[¶](#class-event "Link to this heading") ---------------------------------------------------- _class_ asyncio.Event[¶](#asyncio.Event "Link to this definition") Create a new event which can be used to synchronise tasks. Events start in the cleared state. Event.is\_set()[¶](#asyncio.Event.is_set "Link to this definition") Returns `True` if the event is set, `False` otherwise. Event.set()[¶](#asyncio.Event.set "Link to this definition") 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`](#asyncio.ThreadSafeFlag "asyncio.ThreadSafeFlag") . Event.clear()[¶](#asyncio.Event.clear "Link to this definition") Clear the event. Event.wait()[¶](#asyncio.Event.wait "Link to this definition") Wait for the event to be set. If the event is already set then it returns immediately. This is a coroutine. class ThreadSafeFlag[¶](#class-threadsafeflag "Link to this heading") ---------------------------------------------------------------------- _class_ asyncio.ThreadSafeFlag[¶](#asyncio.ThreadSafeFlag "Link to this definition") 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. ThreadSafeFlag.set()[¶](#asyncio.ThreadSafeFlag.set "Link to this definition") Set the flag. If there is a task waiting on the flag, it will be scheduled to run. ThreadSafeFlag.clear()[¶](#asyncio.ThreadSafeFlag.clear "Link to this definition") Clear the flag. This may be used to ensure that a possibly previously-set flag is clear before waiting for it. ThreadSafeFlag.wait()[¶](#asyncio.ThreadSafeFlag.wait "Link to this definition") 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-lock "Link to this heading") -------------------------------------------------- _class_ asyncio.Lock[¶](#asyncio.Lock "Link to this definition") 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()[¶](#asyncio.Lock.locked "Link to this definition") Returns `True` if the lock is locked, otherwise `False`. Lock.acquire()[¶](#asyncio.Lock.acquire "Link to this definition") 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()[¶](#asyncio.Lock.release "Link to this definition") 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[¶](#tcp-stream-connections "Link to this heading") -------------------------------------------------------------------------- asyncio.open\_connection(_host_, _port_, _ssl\=None_)[¶](#asyncio.open_connection "Link to this definition") Open a TCP connection to the given _host_ and _port_. The _host_ address will be resolved using [`socket.getaddrinfo`](socket.html#socket.getaddrinfo "socket.getaddrinfo") , which is currently a blocking call. If _ssl_ is a [`ssl.SSLContext`](ssl.html#ssl.SSLContext "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_)[¶](#asyncio.start_server "Link to this definition") 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`](ssl.html#ssl.SSLContext "ssl.SSLContext") object, this context is used to create the transport. Returns a [`Server`](#asyncio.Server "asyncio.Server") object. This is a coroutine. _class_ asyncio.Stream[¶](#asyncio.Stream "Link to this definition") 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_)[¶](#asyncio.Stream.get_extra_info "Link to this definition") Get extra information about the stream, given by _v_. The valid values for _v_ are: `peername`. Stream.close()[¶](#asyncio.Stream.close "Link to this definition") Close the stream. Stream.wait\_closed()[¶](#asyncio.Stream.wait_closed "Link to this definition") Wait for the stream to close. This is a coroutine. Stream.read(_n\=\-1_)[¶](#asyncio.Stream.read "Link to this definition") 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_)[¶](#asyncio.Stream.readinto "Link to this definition") 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. Stream.readexactly(_n_)[¶](#asyncio.Stream.readexactly "Link to this definition") 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()[¶](#asyncio.Stream.readline "Link to this definition") Read a line and return it. This is a coroutine. Stream.write(_buf_)[¶](#asyncio.Stream.write "Link to this definition") Accumulated _buf_ to the output buffer. The data is only flushed when [`Stream.drain`](#asyncio.Stream.drain "asyncio.Stream.drain") is called. It is recommended to call [`Stream.drain`](#asyncio.Stream.drain "asyncio.Stream.drain") immediately after calling this function. Stream.drain()[¶](#asyncio.Stream.drain "Link to this definition") Drain (write) all buffered output data out to the stream. This is a coroutine. _class_ asyncio.Server[¶](#asyncio.Server "Link to this definition") This represents the server class returned from [`start_server`](#asyncio.start_server "asyncio.start_server") . It can be used in an `async with` statement to close the server upon exit. Server.close()[¶](#asyncio.Server.close "Link to this definition") Close the server. Server.wait\_closed()[¶](#asyncio.Server.wait_closed "Link to this definition") Wait for the server to close. This is a coroutine. Event Loop[¶](#event-loop "Link to this heading") -------------------------------------------------- asyncio.get\_event\_loop()[¶](#asyncio.get_event_loop "Link to this definition") Return the event loop used to schedule and run tasks. See [`Loop`](#asyncio.Loop "asyncio.Loop") . asyncio.new\_event\_loop()[¶](#asyncio.new_event_loop "Link to this definition") 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[¶](#asyncio.Loop "Link to this definition") This represents the object which schedules and runs tasks. It cannot be created, use [`get_event_loop`](#asyncio.get_event_loop "asyncio.get_event_loop") instead. Loop.create\_task(_coro_)[¶](#asyncio.Loop.create_task "Link to this definition") Create a task from the given _coro_ and return the new [`Task`](#asyncio.Task "asyncio.Task") object. Loop.run\_forever()[¶](#asyncio.Loop.run_forever "Link to this definition") Run the event loop until [`stop()`](#asyncio.Loop.stop "asyncio.Loop.stop") is called. Loop.run\_until\_complete(_awaitable_)[¶](#asyncio.Loop.run_until_complete "Link to this definition") Run the given _awaitable_ until it completes. If _awaitable_ is not a task then it will be promoted to one. Loop.stop()[¶](#asyncio.Loop.stop "Link to this definition") Stop the event loop. Loop.close()[¶](#asyncio.Loop.close "Link to this definition") Close the event loop. Loop.set\_exception\_handler(_handler_)[¶](#asyncio.Loop.set_exception_handler "Link to this definition") 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()[¶](#asyncio.Loop.get_exception_handler "Link to this definition") Get the current exception handler. Returns the handler, or `None` if no custom handler is set. Loop.default\_exception\_handler(_context_)[¶](#asyncio.Loop.default_exception_handler "Link to this definition") The default exception handler that is called. Loop.call\_exception\_handler(_context_)[¶](#asyncio.Loop.call_exception_handler "Link to this definition") Call the current exception handler. The argument _context_ is passed through and is a dictionary containing keys: `'message'`, `'exception'`, `'future'`. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # sys – system specific functions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `sys` – system specific functions * [View page source](../_sources/library/sys.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`sys`](#module-sys "sys: system specific functions") – system specific functions[¶](#module-sys "Link to this heading") ========================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`sys`](https://docs.python.org/3.5/library/sys.html#module-sys "(in Python v3.5)") . Functions[¶](#functions "Link to this heading") ------------------------------------------------ sys.exit(_retval\=0_, _/_)[¶](#sys.exit "Link to this definition") Terminate current program with a given exit code. Underlyingly, this function raises a [`SystemExit`](builtins.html#SystemExit "SystemExit") exception. If an argument is given, its value given as an argument to [`SystemExit`](builtins.html#SystemExit "SystemExit") . On embedded ports (i.e. all ports but Windows and Unix), an unhandled [`SystemExit`](builtins.html#SystemExit "SystemExit") currently causes a [Soft Reset](../reference/reset_boot.html#soft-reset) of MicroPython. sys.atexit(_func_)[¶](#sys.atexit "Link to this definition") 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`](https://docs.python.org/3.5/library/atexit.html#module-atexit "(in Python v3.5)") module in CPython. sys.print\_exception(_exc_, _file\=sys.stdout_, _/_)[¶](#sys.print_exception "Link to this definition") Print exception with a traceback to a file-like object _file_ (or [`sys.stdout`](#sys.stdout "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, exception value, and traceback object; _file_ argument should be positional; further arguments are not supported. CPython-compatible `traceback` module can be found in [`micropython-lib`](../reference/glossary.html#term-micropython-lib) . sys.settrace(_tracefunc_)[¶](#sys.settrace "Link to this definition") Enable tracing of bytecode execution. For details see the [CPython documentation](https://docs.python.org/3/library/sys.html#sys.settrace) . 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_. Constants[¶](#constants "Link to this heading") ------------------------------------------------ sys.argv[¶](#sys.argv "Link to this definition") A mutable list of arguments the current program was started with. sys.byteorder[¶](#sys.byteorder "Link to this definition") The byte order of the system (`"little"` or `"big"`). sys.implementation[¶](#sys.implementation "Link to this definition") Object with information about the current Python implementation. For MicroPython, it has following attributes: * _name_ - string “micropython” * _version_ - tuple (major, minor, micro, releaselevel), e.g. (1, 22, 0, ‘’) * _\_machine_ - string describing the underlying machine * _\_mpy_ - supported mpy file-format version (optional attribute) * _\_build_ - string that can help identify the configuration that MicroPython was built with 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). Starting with version 1.22.0-preview, the fourth node _releaselevel_ in _implementation.version_ is either an empty string or `"preview"`. The _\_build_ entry was added in version 1.25.0 and is a hyphen-separated set of elements. New elements may be appended in the future so it’s best to access this field using `sys.implementation._build.split("-")`. The elements that are currently used are: * On the unix, webassembly and windows ports the first element is the variant name, for example `'standard'`. * On microcontroller targets, the first element is the board name and the second element (if present) is the board variant, for example `'RPI_PICO2-RISCV'` Difference to CPython CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in MicroPython. sys.maxsize[¶](#sys.maxsize "Link to this definition") 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[¶](#sys.modules "Link to this definition") Dictionary of loaded modules. On some ports, it may not include builtin modules. sys.path[¶](#sys.path "Link to this definition") A mutable list of directories to search for imported modules. Difference to CPython On MicroPython, an entry with the value `".frozen"` will indicate that import should search [frozen modules](../reference/glossary.html#term-frozen-module) 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[¶](#sys.platform "Link to this definition") 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`](#sys.implementation "sys.implementation") instead. sys.ps1[¶](#sys.ps1 "Link to this definition") sys.ps2[¶](#sys.ps2 "Link to this definition") Mutable attributes holding strings, which are used for the REPL prompt. The defaults give the standard Python prompt of `>>>` and `...`. sys.stderr[¶](#sys.stderr "Link to this definition") Standard error [`stream`](../reference/glossary.html#term-stream) . sys.stdin[¶](#sys.stdin "Link to this definition") Standard input [`stream`](../reference/glossary.html#term-stream) . sys.stdout[¶](#sys.stdout "Link to this definition") Standard output [`stream`](../reference/glossary.html#term-stream) . sys.tracebacklimit[¶](#sys.tracebacklimit "Link to this definition") 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[¶](#sys.version "Link to this definition") Python language version that this implementation conforms to, as a string. sys.version\_info[¶](#sys.version_info "Link to this definition") 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # errno – system error codes — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `errno` – system error codes * [View page source](../_sources/library/errno.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`errno`](#module-errno "errno: system error codes") – system error codes[¶](#module-errno "Link to this heading") ==================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`errno`](https://docs.python.org/3.5/library/errno.html#module-errno "(in Python v3.5)") . This module provides access to symbolic error codes for [`OSError`](builtins.html#OSError "OSError") exception. A particular inventory of codes depends on [MicroPython port](../reference/glossary.html#term-MicroPython-port) . Constants[¶](#constants "Link to this heading") ------------------------------------------------ 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](../reference/glossary.html#term-MicroPython-port) . Errors are usually accessible as `exc.errno` where `exc` is an instance of [`OSError`](builtins.html#OSError "OSError") . Usage example: try: os.mkdir("my\_dir") except OSError as exc: if exc.errno \== errno.EEXIST: print("Directory already exists") errno.errorcode[¶](#errno.errorcode "Link to this definition") Dictionary mapping numeric error codes to strings with symbolic error code (see above): \>>> print(errno.errorcode\[errno.EEXIST\]) EEXIST Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # collections – collection and container types — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `collections` – collection and container types * [View page source](../_sources/library/collections.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`collections`](#module-collections "collections: collection and container types") – collection and container types[¶](#module-collections "Link to this heading") ==================================================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`collections`](https://docs.python.org/3.5/library/collections.html#module-collections "(in Python v3.5)") . This module implements advanced collection and container types to hold/accumulate various objects. Classes[¶](#classes "Link to this heading") -------------------------------------------- _class_ collections.deque(_iterable_, _maxlen_\[, _flags_\])[¶](#collections.deque "Link to this definition") 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_ is an iterable used to populate the deque when it is created. It can be an empty tuple or list to create a deque that is initially 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. > Deque objects support [`bool`](builtins.html#bool "bool") , [`len`](builtins.html#len "len") , iteration and subscript load and store. They also have the following methods: append(_x_)[¶](#collections.deque.append "Link to this definition") Add _x_ to the right side of the deque. Raises `IndexError` if overflow checking is enabled and there is no more room in the queue. appendleft(_x_)[¶](#collections.deque.appendleft "Link to this definition") Add _x_ to the left side of the deque. Raises `IndexError` if overflow checking is enabled and there is no more room in the queue. pop()[¶](#collections.deque.pop "Link to this definition") Remove and return an item from the right side of the deque. Raises `IndexError` if no items are present. popleft()[¶](#collections.deque.popleft "Link to this definition") Remove and return an item from the left side of the deque. Raises `IndexError` if no items are present. extend(_iterable_)[¶](#collections.deque.extend "Link to this definition") Extend the deque by appending all the items from _iterable_ to the right of the deque. Raises `IndexError` if overflow checking is enabled and there is no more room in the deque. collections.namedtuple(_name_, _fields_)[¶](#collections.namedtuple "Link to this definition") 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(_..._)[¶](#collections.OrderedDict "Link to this definition") `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) Output: z 1 a 2 w 5 b 3 Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # gc – control the garbage collector — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `gc` – control the garbage collector * [View page source](../_sources/library/gc.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`gc`](#module-gc "gc: control the garbage collector") – control the garbage collector[¶](#module-gc "Link to this heading") ============================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`gc`](https://docs.python.org/3.5/library/gc.html#module-gc "(in Python v3.5)") . Functions[¶](#functions "Link to this heading") ------------------------------------------------ gc.enable()[¶](#gc.enable "Link to this definition") Enable automatic garbage collection. gc.disable()[¶](#gc.disable "Link to this definition") Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be initiated manually using [`gc.collect()`](#gc.collect "gc.collect") . gc.collect()[¶](#gc.collect "Link to this definition") Run a garbage collection. gc.mem\_alloc()[¶](#gc.mem_alloc "Link to this definition") 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()[¶](#gc.mem_free "Link to this definition") 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_\])[¶](#gc.threshold "Link to this definition") 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # hashlib – hashing algorithms — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `hashlib` – hashing algorithms * [View page source](../_sources/library/hashlib.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`hashlib`](#module-hashlib "hashlib: hashing algorithms") – hashing algorithms[¶](#module-hashlib "Link to this heading") ============================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`hashlib`](https://docs.python.org/3.5/library/hashlib.html#module-hashlib "(in Python v3.5)") . 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[¶](#constructors "Link to this heading") ------------------------------------------------------ _class_ hashlib.sha256(\[_data_\])[¶](#hashlib.hashlib.sha256 "Link to this definition") Create an SHA256 hasher object and optionally feed `data` into it. _class_ hashlib.sha1(\[_data_\])[¶](#hashlib.hashlib.sha1 "Link to this definition") Create an SHA1 hasher object and optionally feed `data` into it. _class_ hashlib.md5(\[_data_\])[¶](#hashlib.hashlib.md5 "Link to this definition") Create an MD5 hasher object and optionally feed `data` into it. Methods[¶](#methods "Link to this heading") -------------------------------------------- hash.update(_data_)[¶](#hashlib.hash.update "Link to this definition") Feed more binary data into hash. hash.digest()[¶](#hashlib.hash.digest "Link to this definition") 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()[¶](#hashlib.hash.hexdigest "Link to this definition") This method is NOT implemented. Use `binascii.hexlify(hash.digest())` to achieve a similar effect. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # gzip – gzip compression & decompression — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `gzip` – gzip compression & decompression * [View page source](../_sources/library/gzip.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`gzip`](#module-gzip "gzip: gzip compression & decompression") – gzip compression & decompression[¶](#module-gzip "Link to this heading") ============================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`gzip`](https://docs.python.org/3.5/library/gzip.html#module-gzip "(in Python v3.5)") . This module allows compression and decompression of binary data with the [DEFLATE algorithm](https://en.wikipedia.org/wiki/DEFLATE) used by the gzip file format. Note Prefer to use [`deflate.DeflateIO`](deflate.html#deflate.DeflateIO "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`](deflate.html#module-deflate "deflate: deflate compression & decompression") module. * A copy of this module can be installed (or frozen) from [micropython-lib](../reference/glossary.html#term-micropython-lib) ([source](https://github.com/micropython/micropython-lib/blob/master/python-stdlib/gzip/gzip.py) ). See [Package management](../reference/packages.html#packages) for more information. This documentation describes that module. * Compression support will only be available if compression support is enabled in the built-in [`deflate`](deflate.html#module-deflate "deflate: deflate compression & decompression") module. Functions[¶](#functions "Link to this heading") ------------------------------------------------ gzip.open(_filename_, _mode_, _/_)[¶](#gzip.open "Link to this definition") Wrapper around built-in [`open()`](builtins.html#open "open") returning a GzipFile instance. gzip.decompress(_data_, _/_)[¶](#gzip.decompress "Link to this definition") Decompresses _data_ into a bytes object. gzip.compress(_data_, _/_)[¶](#gzip.compress "Link to this definition") Compresses _data_ into a bytes object. Classes[¶](#classes "Link to this heading") -------------------------------------------- _class_ gzip.GzipFile(_\*_, _fileobj_, _mode_)[¶](#gzip.GzipFile "Link to this definition") This class can be used to wrap a _fileobj_ which is any [stream-like](../reference/glossary.html#term-stream) object such as a file, socket, or stream (including [`io.BytesIO`](io.html#io.BytesIO "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[¶](#examples "Link to this heading") ---------------------------------------------- A typical use case for [`gzip.GzipFile`](#gzip.GzipFile "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 \# 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 documentation](deflate.html#deflate-wbits) . Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # os – basic “operating system” services — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `os` – basic “operating system” services * [View page source](../_sources/library/os.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`os`](#module-os "os: basic "operating system" services") – basic “operating system” services[¶](#module-os "Link to this heading") ====================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`os`](https://docs.python.org/3.5/library/os.html#module-os "(in Python v3.5)") . The `os` module contains functions for filesystem access and mounting, terminal redirection and duplication, and the `uname` and `urandom` functions. General functions[¶](#general-functions "Link to this heading") ---------------------------------------------------------------- os.uname()[¶](#os.uname "Link to this definition") 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_)[¶](#os.urandom "Link to this definition") Return a bytes object with _n_ random bytes. Whenever possible, it is generated by the hardware random number generator. Filesystem access[¶](#filesystem-access "Link to this heading") ---------------------------------------------------------------- os.chdir(_path_)[¶](#os.chdir "Link to this definition") Change current directory. os.getcwd()[¶](#os.getcwd "Link to this definition") Get the current directory. os.ilistdir(\[_dir_\])[¶](#os.ilistdir "Link to this definition") 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 representing the size of the file or -1 if unknown. Its meaning is currently undefined for directory entries. > os.listdir(\[_dir_\])[¶](#os.listdir "Link to this definition") With no argument, list the current directory. Otherwise list the given directory. os.mkdir(_path_)[¶](#os.mkdir "Link to this definition") Create a new directory. os.remove(_path_)[¶](#os.remove "Link to this definition") Remove a file. os.rmdir(_path_)[¶](#os.rmdir "Link to this definition") Remove a directory. os.rename(_old\_path_, _new\_path_)[¶](#os.rename "Link to this definition") Rename a file. os.stat(_path_)[¶](#os.stat "Link to this definition") Get the status of a file or directory. os.statvfs(_path_)[¶](#os.statvfs "Link to this definition") 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()[¶](#os.sync "Link to this definition") Sync all filesystems. Terminal redirection and duplication[¶](#terminal-redirection-and-duplication "Link to this heading") ------------------------------------------------------------------------------------------------------ os.dupterm(_stream\_object_, _index\=0_, _/_)[¶](#os.dupterm "Link to this definition") Duplicate or switch the MicroPython terminal (the REPL) on the given [`stream`](../reference/glossary.html#term-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. Filesystem mounting[¶](#filesystem-mounting "Link to this heading") -------------------------------------------------------------------- The following functions and classes have been moved to the [`vfs`](vfs.html#module-vfs "vfs: virtual filesystem control") module. They are provided in this module only for backwards compatibility and will be removed in version 2 of MicroPython. os.mount(_fsobj_, _mount\_point_, _\*_, _readonly_)[¶](#os.mount "Link to this definition") See [`vfs.mount`](vfs.html#vfs.mount "vfs.mount") . os.umount(_mount\_point_)[¶](#os.umount "Link to this definition") See [`vfs.umount`](vfs.html#vfs.umount "vfs.umount") . _class_ os.VfsFat(_block\_dev_)[¶](#os.VfsFat "Link to this definition") See [`vfs.VfsFat`](vfs.html#vfs.VfsFat "vfs.VfsFat") . _class_ os.VfsLfs1(_block\_dev_, _readsize\=32_, _progsize\=32_, _lookahead\=32_)[¶](#os.VfsLfs1 "Link to this definition") See [`vfs.VfsLfs1`](vfs.html#vfs.VfsLfs1 "vfs.VfsLfs1") . _class_ os.VfsLfs2(_block\_dev_, _readsize\=32_, _progsize\=32_, _lookahead\=32_, _mtime\=True_)[¶](#os.VfsLfs2 "Link to this definition") See [`vfs.VfsLfs2`](vfs.html#vfs.VfsLfs2 "vfs.VfsLfs2") . _class_ os.VfsPosix(_root\=None_)[¶](#os.VfsPosix "Link to this definition") See [`vfs.VfsPosix`](vfs.html#vfs.VfsPosix "vfs.VfsPosix") . Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # random – generate random numbers — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `random` – generate random numbers * [View page source](../_sources/library/random.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`random`](#module-random "random: random numbers") – generate random numbers[¶](#module-random "Link to this heading") ========================================================================================================================= This module implements a pseudo-random number generator (PRNG). _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`random`](https://docs.python.org/3.5/library/random.html#module-random "(in Python v3.5)") . 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()`](#random.randrange "random.randrange") , [`randint()`](#random.randint "random.randint") and [`choice()`](#random.choice "random.choice") functions are only available if the `MICROPY_PY_RANDOM_EXTRA_FUNCS` configuration option is enabled. Functions for integers[¶](#functions-for-integers "Link to this heading") -------------------------------------------------------------------------- random.getrandbits(_n_)[¶](#random.getrandbits "Link to this definition") Return an integer with _n_ random bits (0 <= n <= 32). random.randint(_a_, _b_)[¶](#random.randint "Link to this definition") Return a random integer in the range \[_a_, _b_\]. random.randrange(_stop_)[¶](#random.randrange "Link to this definition") 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[¶](#functions-for-floats "Link to this heading")\ \ ----------------------------------------------------------------------\ \ random.random()[¶](#random.random "Link to this definition")\ \ Return a random floating point number in the range \[0.0, 1.0).\ \ random.uniform(_a_, _b_)[¶](#random.uniform "Link to this definition")\ \ Return a random floating point number N such that _a_ <= N <= _b_ for _a_ <= _b_, and _b_ <= N <= _a_ for _b_ < _a_.\ \ Other Functions[¶](#other-functions "Link to this heading")\ \ ------------------------------------------------------------\ \ random.seed(_n\=None_, _/_)[¶](#random.seed "Link to this definition")\ \ 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_)[¶](#random.choice "Link to this definition")\ \ Chooses and returns one item at random from _sequence_ (tuple, list or any object that supports the subscript operation).\ \ Versions and Downloads latest\ \ Versions\ \ [v1.4.4](http://docs.micropython.org/en/v1.4.4)\ \ [v1.4.5](http://docs.micropython.org/en/v1.4.5)\ \ [v1.4.6](http://docs.micropython.org/en/v1.4.6)\ \ [v1.5](http://docs.micropython.org/en/v1.5)\ \ [v1.5.1](http://docs.micropython.org/en/v1.5.1)\ \ [v1.5.2](http://docs.micropython.org/en/v1.5.2)\ \ [v1.6](http://docs.micropython.org/en/v1.6)\ \ [v1.7](http://docs.micropython.org/en/v1.7)\ \ [v1.8](http://docs.micropython.org/en/v1.8)\ \ [v1.8.1](http://docs.micropython.org/en/v1.8.1)\ \ [v1.8.2](http://docs.micropython.org/en/v1.8.2)\ \ [v1.8.3](http://docs.micropython.org/en/v1.8.3)\ \ [v1.8.4](http://docs.micropython.org/en/v1.8.4)\ \ [v1.8.5](http://docs.micropython.org/en/v1.8.5)\ \ [v1.8.6](http://docs.micropython.org/en/v1.8.6)\ \ [v1.8.7](http://docs.micropython.org/en/v1.8.7)\ \ [v1.9](http://docs.micropython.org/en/v1.9)\ \ [v1.9.1](http://docs.micropython.org/en/v1.9.1)\ \ [v1.9.2](http://docs.micropython.org/en/v1.9.2)\ \ [v1.9.3](http://docs.micropython.org/en/v1.9.3)\ \ [v1.9.4](http://docs.micropython.org/en/v1.9.4)\ \ [v1.10](http://docs.micropython.org/en/v1.10)\ \ [v1.11](http://docs.micropython.org/en/v1.11)\ \ [v1.12](http://docs.micropython.org/en/v1.12)\ \ [v1.13](http://docs.micropython.org/en/v1.13)\ \ [v1.14](http://docs.micropython.org/en/v1.14)\ \ [v1.15](http://docs.micropython.org/en/v1.15)\ \ [v1.16](http://docs.micropython.org/en/v1.16)\ \ [v1.17](http://docs.micropython.org/en/v1.17)\ \ [v1.18](http://docs.micropython.org/en/v1.18)\ \ [v1.19.1](http://docs.micropython.org/en/v1.19.1)\ \ [v1.20.0](http://docs.micropython.org/en/v1.20.0)\ \ [v1.21.0](http://docs.micropython.org/en/v1.21.0)\ \ [v1.22.0](http://docs.micropython.org/en/v1.22.0)\ \ [v1.23.0](http://docs.micropython.org/en/v1.23.0)\ \ [v1.24.0](http://docs.micropython.org/en/v1.24.0)\ \ [latest](http://docs.micropython.org/en/latest)\ \ Downloads\ \ [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf)\ \ * * *\ \ External links\ \ [micropython.org](https://www.micropython.org)\ \ [GitHub](https://github.com/micropython/micropython) --- # socket – socket module — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `socket` – socket module * [View page source](../_sources/library/socket.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`socket`](#module-socket "socket: socket module") – socket module[¶](#module-socket "Link to this heading") ============================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`socket`](https://docs.python.org/3.5/library/socket.html#module-socket "(in Python v3.5)") . This module provides access to the BSD socket interface. Difference to CPython For efficiency and consistency, socket objects in MicroPython implement a [`stream`](../reference/glossary.html#term-stream) (file-like) interface directly. In CPython, you need to convert a socket to a file-like object using [`makefile()`](#socket.socket.makefile "socket.socket.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. Socket address format(s)[¶](#socket-address-format-s "Link to this heading") ----------------------------------------------------------------------------- The native socket address format of the `socket` module is an opaque data type returned by [`getaddrinfo`](#socket.getaddrinfo "socket.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`](#socket.getaddrinfo "socket.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](../reference/glossary.html#term-MicroPython-port) , `socket` module can be builtin or need to be installed from [`micropython-lib`](../reference/glossary.html#term-micropython-lib) (as in the case of [MicroPython Unix port](../reference/glossary.html#term-MicroPython-Unix-port) ), and some ports still accept only numeric addresses in the tuple format, and require to use [`getaddrinfo`](#socket.getaddrinfo "socket.getaddrinfo") function to resolve domain names. Summing up: * Always use [`getaddrinfo`](#socket.getaddrinfo "socket.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()`](#socket.getaddrinfo "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()`](#socket.getaddrinfo "socket.getaddrinfo") . Availability of IPv6 support depends on a [MicroPython port](../reference/glossary.html#term-MicroPython-port) . Functions[¶](#functions "Link to this heading") ------------------------------------------------ socket.getaddrinfo(_host_, _port_, _af\=0_, _type\=0_, _proto\=0_, _flags\=0_, _/_)[¶](#socket.getaddrinfo "Link to this definition") Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. Arguments _af_, _type_, and _proto_ (which have the same meaning as for the [`socket()`](#socket.socket "socket.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\]) 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`](builtins.html#OSError "OSError") subclass) in case of error in this function. MicroPython doesn’t have `socket.gaierror` and raises OSError directly. Note that error numbers of [`getaddrinfo()`](#socket.getaddrinfo "socket.getaddrinfo") form a separate namespace and may not match error numbers from the [`errno`](errno.html#module-errno "errno: system error codes") module. To distinguish [`getaddrinfo()`](#socket.getaddrinfo "socket.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_)[¶](#socket.inet_ntop "Link to this definition") 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_)[¶](#socket.inet_pton "Link to this definition") 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[¶](#constants "Link to this heading") ------------------------------------------------ socket.AF\_INET[¶](#socket.AF_INET "Link to this definition") socket.AF\_INET6[¶](#socket.AF_INET6 "Link to this definition") Address family types. Availability depends on a particular [MicroPython port](../reference/glossary.html#term-MicroPython-port) . socket.SOCK\_STREAM[¶](#socket.SOCK_STREAM "Link to this definition") socket.SOCK\_DGRAM[¶](#socket.SOCK_DGRAM "Link to this definition") Socket types. socket.IPPROTO\_UDP[¶](#socket.IPPROTO_UDP "Link to this definition") socket.IPPROTO\_TCP[¶](#socket.IPPROTO_TCP "Link to this definition") IP protocol numbers. Availability depends on a particular [MicroPython port](../reference/glossary.html#term-MicroPython-port) . Note that you don’t need to specify these in a call to [`socket.socket()`](#socket.socket "socket.socket") , because [`SOCK_STREAM`](#socket.SOCK_STREAM "socket.SOCK_STREAM") socket type automatically selects [`IPPROTO_TCP`](#socket.IPPROTO_TCP "socket.IPPROTO_TCP") , and [`SOCK_DGRAM`](#socket.SOCK_DGRAM "socket.SOCK_DGRAM") - [`IPPROTO_UDP`](#socket.IPPROTO_UDP "socket.IPPROTO_UDP") . Thus, the only real use of these constants is as an argument to [`setsockopt()`](#socket.socket.setsockopt "socket.socket.setsockopt") . socket.SOL\_\* Socket option levels (an argument to [`setsockopt()`](#socket.socket.setsockopt "socket.socket.setsockopt") ). The exact inventory depends on a [MicroPython port](../reference/glossary.html#term-MicroPython-port) . socket.SO\_\* Socket options (an argument to [`setsockopt()`](#socket.socket.setsockopt "socket.socket.setsockopt") ). The exact inventory depends on a [MicroPython port](../reference/glossary.html#term-MicroPython-port) . Constants specific to WiPy: socket.IPPROTO\_SEC[¶](#socket.IPPROTO_SEC "Link to this definition") Special protocol value to create SSL-compatible socket. ### class socket[¶](#class-socket "Link to this heading") _class_ socket.socket(_af\=AF\_INET_, _type\=SOCK\_STREAM_, _proto\=IPPROTO\_TCP_, _/_)[¶](#socket.socket "Link to this definition") 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[¶](#methods "Link to this heading") -------------------------------------------- socket.close()[¶](#socket.socket.close "Link to this definition") 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()`](#socket.socket.close "socket.socket.close") them explicitly as soon you finished working with them. socket.bind(_address_)[¶](#socket.socket.bind "Link to this definition") Bind the socket to _address_. The socket must not already be bound. socket.listen(\[_backlog_\])[¶](#socket.socket.listen "Link to this definition") 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()[¶](#socket.socket.accept "Link to this definition") 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_)[¶](#socket.socket.connect "Link to this definition") Connect to a remote socket at _address_. socket.send(_bytes_)[¶](#socket.socket.send "Link to this definition") 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_)[¶](#socket.socket.sendall "Link to this definition") Send all data to the socket. The socket must be connected to a remote socket. Unlike [`send()`](#socket.socket.send "socket.socket.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()`](#socket.socket.write "socket.socket.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. socket.recv(_bufsize_)[¶](#socket.socket.recv "Link to this definition") 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_)[¶](#socket.socket.sendto "Link to this definition") 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_)[¶](#socket.socket.recvfrom "Link to this definition") 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_)[¶](#socket.socket.setsockopt "Link to this definition") 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_)[¶](#socket.socket.settimeout "Link to this definition") **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`](builtins.html#OSError "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](../reference/glossary.html#term-MicroPython-port) supports this method. A more portable and generic solution is to use [`select.poll`](select.html#select.poll "select.poll") object. This allows to wait on multiple objects at the same time (and not just on sockets, but on generic [`stream`](../reference/glossary.html#term-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`](builtins.html#OSError "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_)[¶](#socket.socket.setblocking "Link to this definition") 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()`](#socket.socket.settimeout "socket.socket.settimeout") calls: * `sock.setblocking(True)` is equivalent to `sock.settimeout(None)` * `sock.setblocking(False)` is equivalent to `sock.settimeout(0)` socket.makefile(_mode\='rb'_, _buffering\=0_, _/_)[¶](#socket.socket.makefile "Link to this definition") Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). 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_\])[¶](#socket.socket.read "Link to this definition") 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_\])[¶](#socket.socket.readinto "Link to this definition") 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()`](#socket.socket.read "socket.socket.read") , this method follows “no short reads” policy. Return value: number of bytes read and stored into _buf_. socket.readline()[¶](#socket.socket.readline "Link to this definition") Read a line, ending in a newline character. Return value: the line read. socket.write(_buf_)[¶](#socket.socket.write "Link to this definition") 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[¶](#socket.socket.error "Link to this definition") 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`](builtins.html#OSError "OSError") . In MicroPython, use [`OSError`](builtins.html#OSError "OSError") directly. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # struct – pack and unpack primitive data types — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `struct` – pack and unpack primitive data types * [View page source](../_sources/library/struct.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`struct`](#module-struct "struct: pack and unpack primitive data types") – pack and unpack primitive data types[¶](#module-struct "Link to this heading") ============================================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`struct`](https://docs.python.org/3.5/library/struct.html#module-struct "(in Python v3.5)") . 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](#fn)
) | 4 | | I | unsigned int | integer ([1](#fn)
) | 4 | | l | long | integer ([1](#fn)
) | 4 | | L | unsigned long | integer ([1](#fn)
) | 4 | | q | long long | integer ([1](#fn)
) | 8 | | Q | unsigned long long | integer ([1](#fn)
) | 8 | | e | n/a (half-float) | float ([2](#fn)
) | 2 | | f | float | float ([2](#fn)
) | 4 | | d | double | float ([2](#fn)
) | 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[¶](#functions "Link to this heading") ------------------------------------------------ struct.calcsize(_fmt_)[¶](#struct.calcsize "Link to this definition") Return the number of bytes needed to store the given _fmt_. struct.pack(_fmt_, _v1_, _v2_, _..._)[¶](#struct.pack "Link to this definition") 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_, _..._)[¶](#struct.pack_into "Link to this definition") 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_. struct.unpack(_fmt_, _data_)[¶](#struct.unpack "Link to this definition") 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_, _/_)[¶](#struct.unpack_from "Link to this definition") 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # heapq – heap queue algorithm — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `heapq` – heap queue algorithm * [View page source](../_sources/library/heapq.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`heapq`](#module-heapq "heapq: heap queue algorithm") – heap queue algorithm[¶](#module-heapq "Link to this heading") ======================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`heapq`](https://docs.python.org/3.5/library/heapq.html#module-heapq "(in Python v3.5)") . This module implements the [min heap queue algorithm](https://en.wikipedia.org/wiki/Heap_%28data_structure%29) . 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[¶](#functions "Link to this heading") ------------------------------------------------ heapq.heappush(_heap_, _item_)[¶](#heapq.heappush "Link to this definition") Push the `item` onto the `heap`. heapq.heappop(_heap_)[¶](#heapq.heappop "Link to this definition") 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_)[¶](#heapq.heapify "Link to this definition") Convert the list `x` into a heap. This is an in-place operation. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # select – wait for events on a set of streams — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `select` – wait for events on a set of streams * [View page source](../_sources/library/select.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`select`](#module-select "select: wait for events on a set of streams") – wait for events on a set of streams[¶](#module-select "Link to this heading") ========================================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`select`](https://docs.python.org/3.5/library/select.html#module-select "(in Python v3.5)") . This module provides functions to efficiently wait for events on multiple [`streams`](../reference/glossary.html#term-stream) (select streams which are ready for operations). Functions[¶](#functions "Link to this heading") ------------------------------------------------ select.poll()[¶](#select.poll "Link to this definition") Create an instance of the Poll class. select.select(_rlist_, _wlist_, _xlist_\[, _timeout_\])[¶](#select.select "Link to this definition") 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`[¶](#class-poll "Link to this heading") ---------------------------------------------------- ### Methods[¶](#methods "Link to this heading") poll.register(_obj_\[, _eventmask_\])[¶](#select.poll.register "Link to this definition") Register [`stream`](../reference/glossary.html#term-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()`](#select.poll.poll "select.poll.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()`](#select.poll.modify "select.poll.modify") ). poll.unregister(_obj_)[¶](#select.poll.unregister "Link to this definition") Unregister _obj_ from polling. poll.modify(_obj_, _eventmask_)[¶](#select.poll.modify "Link to this definition") Modify the _eventmask_ for _obj_. If _obj_ is not registered, [`OSError`](builtins.html#OSError "OSError") is raised with error of ENOENT. poll.poll(_timeout\=\-1_, _/_)[¶](#select.poll.poll "Link to this definition") 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()`](#select.poll.poll "select.poll.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_, _/_)[¶](#select.poll.ipoll "Link to this definition") Like [`poll.poll()`](#select.poll.poll "select.poll.poll") , but instead returns an iterator which yields a [`callee-owned tuple`](../reference/glossary.html#term-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()`](#select.poll.modify "select.poll.modify") . This behaviour is useful for asynchronous I/O schedulers. Difference to CPython This function is a MicroPython extension. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # io – input/output streams — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `io` – input/output streams * [View page source](../_sources/library/io.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`io`](#module-io "io: input/output streams") – input/output streams[¶](#module-io "Link to this heading") ============================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`io`](https://docs.python.org/3.5/library/io.html#module-io "(in Python v3.5)") . This module contains additional types of [`stream`](../reference/glossary.html#term-stream) (file-like) objects and helper functions. Conceptual hierarchy[¶](#conceptual-hierarchy "Link to this heading") ---------------------------------------------------------------------- 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 dichotomies (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 unbuffered. 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, 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[¶](#functions "Link to this heading") ------------------------------------------------ io.open(_name_, _mode\='r'_, _\*\*kwargs_)[¶](#io.open "Link to this definition") 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[¶](#classes "Link to this heading") -------------------------------------------- _class_ io.StringIO(\[_string_\])[¶](#io.StringIO "Link to this definition") _class_ io.BytesIO(\[_string_\])[¶](#io.BytesIO "Link to this definition") In-memory file-like objects for input/output. [`StringIO`](#io.StringIO "io.StringIO") is used for text-mode I/O (similar to a normal file opened with “t” modifier). [`BytesIO`](#io.BytesIO "io.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`](#io.StringIO "io.StringIO") or bytes object for [`BytesIO`](#io.BytesIO "io.BytesIO") ). All the usual file methods like `read()`, `write()`, `seek()`, `flush()`, `close()` are available on these objects, and additionally, a following method: getvalue()[¶](#io.BytesIO.getvalue "Link to this definition") 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`](#io.StringIO "io.StringIO") /[`BytesIO`](#io.BytesIO "io.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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # platform – access to underlying platform’s identifying data — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `platform` – access to underlying platform’s identifying data * [View page source](../_sources/library/platform.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`platform`](#module-platform "platform: access to underlying platform’s identifying data") – access to underlying platform’s identifying data[¶](#module-platform "Link to this heading") ============================================================================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`platform`](https://docs.python.org/3.5/library/platform.html#module-platform "(in Python v3.5)") . This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function APIs. Functions[¶](#functions "Link to this heading") ------------------------------------------------ platform.platform()[¶](#platform.platform "Link to this definition") 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()[¶](#platform.python_compiler "Link to this definition") Returns a string identifying the compiler used for compiling MicroPython. platform.libc\_ver()[¶](#platform.libc_ver "Link to this definition") 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # json – JSON encoding and decoding — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `json` – JSON encoding and decoding * [View page source](../_sources/library/json.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`json`](#module-json "json: JSON encoding and decoding") – JSON encoding and decoding[¶](#module-json "Link to this heading") ================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`json`](https://docs.python.org/3.5/library/json.html#module-json "(in Python v3.5)") . This modules allows to convert between Python objects and the JSON data format. Functions[¶](#functions "Link to this heading") ------------------------------------------------ json.dump(_obj_, _stream_, _separators\=None_)[¶](#json.dump "Link to this definition") 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_)[¶](#json.dumps "Link to this definition") Return _obj_ represented as a JSON string. The arguments have the same meaning as in [`dump`](#json.dump "json.dump") . json.load(_stream_)[¶](#json.load "Link to this definition") 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`](builtins.html#ValueError "ValueError") is raised if the data in _stream_ is not correctly formed. json.loads(_str_)[¶](#json.loads "Link to this definition") Parse the JSON _str_ and return an object. Raises [`ValueError`](builtins.html#ValueError "ValueError") if the string is not correctly formed. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # math – mathematical functions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `math` – mathematical functions * [View page source](../_sources/library/math.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`math`](#module-math "math: mathematical functions") – mathematical functions[¶](#module-math "Link to this heading") ======================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`math`](https://docs.python.org/3.5/library/math.html#module-math "(in Python v3.5)") . 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[¶](#functions "Link to this heading") ------------------------------------------------ math.acos(_x_)[¶](#math.acos "Link to this definition") Return the inverse cosine of `x`. math.acosh(_x_)[¶](#math.acosh "Link to this definition") Return the inverse hyperbolic cosine of `x`. math.asin(_x_)[¶](#math.asin "Link to this definition") Return the inverse sine of `x`. math.asinh(_x_)[¶](#math.asinh "Link to this definition") Return the inverse hyperbolic sine of `x`. math.atan(_x_)[¶](#math.atan "Link to this definition") Return the inverse tangent of `x`. math.atan2(_y_, _x_)[¶](#math.atan2 "Link to this definition") Return the principal value of the inverse tangent of `y/x`. math.atanh(_x_)[¶](#math.atanh "Link to this definition") Return the inverse hyperbolic tangent of `x`. math.ceil(_x_)[¶](#math.ceil "Link to this definition") Return an integer, being `x` rounded towards positive infinity. math.copysign(_x_, _y_)[¶](#math.copysign "Link to this definition") Return `x` with the sign of `y`. math.cos(_x_)[¶](#math.cos "Link to this definition") Return the cosine of `x`. math.cosh(_x_)[¶](#math.cosh "Link to this definition") Return the hyperbolic cosine of `x`. math.degrees(_x_)[¶](#math.degrees "Link to this definition") Return radians `x` converted to degrees. math.erf(_x_)[¶](#math.erf "Link to this definition") Return the error function of `x`. math.erfc(_x_)[¶](#math.erfc "Link to this definition") Return the complementary error function of `x`. math.exp(_x_)[¶](#math.exp "Link to this definition") Return the exponential of `x`. math.expm1(_x_)[¶](#math.expm1 "Link to this definition") Return `exp(x) - 1`. math.fabs(_x_)[¶](#math.fabs "Link to this definition") Return the absolute value of `x`. math.floor(_x_)[¶](#math.floor "Link to this definition") Return an integer, being `x` rounded towards negative infinity. math.fmod(_x_, _y_)[¶](#math.fmod "Link to this definition") Return the remainder of `x/y`. math.frexp(_x_)[¶](#math.frexp "Link to this definition") 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_)[¶](#math.gamma "Link to this definition") Return the gamma function of `x`. math.isfinite(_x_)[¶](#math.isfinite "Link to this definition") Return `True` if `x` is finite. math.isinf(_x_)[¶](#math.isinf "Link to this definition") Return `True` if `x` is infinite. math.isnan(_x_)[¶](#math.isnan "Link to this definition") Return `True` if `x` is not-a-number math.ldexp(_x_, _exp_)[¶](#math.ldexp "Link to this definition") Return `x * (2**exp)`. math.lgamma(_x_)[¶](#math.lgamma "Link to this definition") Return the natural logarithm of the gamma function of `x`. math.log(_x_)[¶](#math.log "Link to this definition") math.log(_x_, _base_) With one argument, return the natural logarithm of _x_. With two arguments, return the logarithm of _x_ to the given _base_. math.log10(_x_)[¶](#math.log10 "Link to this definition") Return the base-10 logarithm of `x`. math.log2(_x_)[¶](#math.log2 "Link to this definition") Return the base-2 logarithm of `x`. math.modf(_x_)[¶](#math.modf "Link to this definition") 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_)[¶](#math.pow "Link to this definition") Returns `x` to the power of `y`. math.radians(_x_)[¶](#math.radians "Link to this definition") Return degrees `x` converted to radians. math.sin(_x_)[¶](#math.sin "Link to this definition") Return the sine of `x`. math.sinh(_x_)[¶](#math.sinh "Link to this definition") Return the hyperbolic sine of `x`. math.sqrt(_x_)[¶](#math.sqrt "Link to this definition") Return the square root of `x`. math.tan(_x_)[¶](#math.tan "Link to this definition") Return the tangent of `x`. math.tanh(_x_)[¶](#math.tanh "Link to this definition") Return the hyperbolic tangent of `x`. math.trunc(_x_)[¶](#math.trunc "Link to this definition") Return an integer, being `x` rounded towards 0. Constants[¶](#constants "Link to this heading") ------------------------------------------------ math.e[¶](#math.e "Link to this definition") base of the natural logarithm math.pi[¶](#math.pi "Link to this definition") the ratio of a circle’s circumference to its diameter Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # time – time related functions — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `time` – time related functions * [View page source](../_sources/library/time.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`time`](#module-time "time: time related functions") – time related functions[¶](#module-time "Link to this heading") ======================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`time`](https://docs.python.org/3.5/library/time.html#module-time "(in Python v3.5)") . 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 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[¶](#functions "Link to this heading") ------------------------------------------------ time.gmtime(\[_secs_\])[¶](#time.gmtime "Link to this definition") time.localtime(\[_secs_\])[¶](#time.localtime "Link to this definition") 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()`](#time.gmtime "time.gmtime") function returns a date-time tuple in UTC, and [`localtime()`](#time.localtime "time.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()[¶](#time.mktime "Link to this definition") 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_)[¶](#time.sleep "Link to this definition") 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()`](#time.sleep_ms "time.sleep_ms") and [`sleep_us()`](#time.sleep_us "time.sleep_us") functions. time.sleep\_ms(_ms_)[¶](#time.sleep_ms "Link to this definition") 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 processing 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()`](#time.sleep_us "time.sleep_us") for more precise delays. time.sleep\_us(_us_)[¶](#time.sleep_us "Link to this definition") 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()[¶](#time.ticks_ms "Link to this definition") 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()`](#time.ticks_ms "time.ticks_ms") , [`ticks_us()`](#time.ticks_us "time.ticks_us") , [`ticks_cpu()`](#time.ticks_cpu "time.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()`](#time.ticks_diff "time.ticks_diff") and [`ticks_add()`](#time.ticks_add "time.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()`](#time.ticks_diff "time.ticks_diff") or [`ticks_add()`](#time.ticks_add "time.ticks_add") will also lead to invalid results from the latter functions. time.ticks\_us()[¶](#time.ticks_us "Link to this definition") Just like [`ticks_ms()`](#time.ticks_ms "time.ticks_ms") above, but in microseconds. time.ticks\_cpu()[¶](#time.ticks_cpu "Link to this definition") Similar to [`ticks_ms()`](#time.ticks_ms "time.ticks_ms") and [`ticks_us()`](#time.ticks_us "time.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_)[¶](#time.ticks_add "Link to this definition") 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()`](#time.ticks_ms "time.ticks_ms") above). _ticks_ parameter must be a direct result of call to [`ticks_ms()`](#time.ticks_ms "time.ticks_ms") , [`ticks_us()`](#time.ticks_us "time.ticks_us") , or [`ticks_cpu()`](#time.ticks_cpu "time.ticks_cpu") functions (or from previous call to [`ticks_add()`](#time.ticks_add "time.ticks_add") ). However, _delta_ can be an arbitrary integer number or numeric expression. [`ticks_add()`](#time.ticks_add "time.ticks_add") is useful for calculating deadlines for events/tasks. (Note: you must use [`ticks_diff()`](#time.ticks_diff "time.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_)[¶](#time.ticks_diff "Link to this definition") Measure ticks difference between values returned from [`ticks_ms()`](#time.ticks_ms "time.ticks_ms") , [`ticks_us()`](#time.ticks_us "time.ticks_us") , or [`ticks_cpu()`](#time.ticks_cpu "time.ticks_cpu") functions, as a signed value which may wrap around. 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()`](#time.ticks_ms "time.ticks_ms") , etc. functions may wrap around, so directly using subtraction on them will produce incorrect result. That is why [`ticks_diff()`](#time.ticks_diff "time.ticks_diff") is needed, it implements modular (or more specifically, ring) arithmetic to produce correct result even for wrap-around values (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()`](#time.ticks_diff "time.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()`](#time.ticks_diff "time.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()`](#time.ticks_diff "time.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()`](#time.time "time.time") values to [`ticks_diff()`](#time.ticks_diff "time.ticks_diff") , you should use normal mathematical operations on them. But note that [`time()`](#time.time "time.time") may (and will) also overflow. This is known as [https://en.wikipedia.org/wiki/Year\_2038\_problem](https://en.wikipedia.org/wiki/Year_2038_problem) . time.time()[¶](#time.time "Link to this definition") 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 precision. If you need higher precision, absolute timestamps, use [`time_ns()`](#time.time_ns "time.time_ns") . If relative times are acceptable then use the [`ticks_ms()`](#time.ticks_ms "time.ticks_ms") and [`ticks_us()`](#time.ticks_us "time.ticks_us") functions. If you need calendar time, [`gmtime()`](#time.gmtime "time.gmtime") or [`localtime()`](#time.localtime "time.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()[¶](#time.time_ns "Link to this definition") Similar to [`time()`](#time.time "time.time") but returns nanoseconds since the Epoch, as an integer (usually a big integer, so will allocate on the heap). Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # zlib – zlib compression & decompression — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `zlib` – zlib compression & decompression * [View page source](../_sources/library/zlib.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`zlib`](#module-zlib "zlib: zlib compression & decompression") – zlib compression & decompression[¶](#module-zlib "Link to this heading") ============================================================================================================================================ _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`zlib`](https://docs.python.org/3.5/library/zlib.html#module-zlib "(in Python v3.5)") . This module allows compression and decompression of binary data with the [DEFLATE algorithm](https://en.wikipedia.org/wiki/DEFLATE) (commonly used in the zlib library and gzip archiver). Note Prefer to use [`deflate.DeflateIO`](deflate.html#deflate.DeflateIO "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`](deflate.html#module-deflate "deflate: deflate compression & decompression") module. * A copy of this module can be installed (or frozen) from [micropython-lib](../reference/glossary.html#term-micropython-lib) ([source](https://github.com/micropython/micropython-lib/blob/master/python-stdlib/zlib/zlib.py) ). See [Package management](../reference/packages.html#packages) for more information. This documentation describes that module. * Requires the built-in [`deflate`](deflate.html#module-deflate "deflate: deflate compression & decompression") module (available since MicroPython v1.21) * Compression support will only be available if compression support is enabled in the built-in [`deflate`](deflate.html#module-deflate "deflate: deflate compression & decompression") module. Functions[¶](#functions "Link to this heading") ------------------------------------------------ zlib.decompress(_data_, _wbits\=15_, _/_)[¶](#zlib.decompress "Link to this definition") Decompresses _data_ into a bytes object. The _wbits_ parameter works the same way as for [`zlib.compress()`](#zlib.compress "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()`](#zlib.compress "zlib.compress") , see the [`CPython documentation for zlib`](https://docs.python.org/3.5/library/zlib.html#module-zlib "(in Python v3.5)") for more information about the _wbits_ parameter. As for [`zlib.compress()`](#zlib.compress "zlib.compress") , MicroPython also supports smaller window sizes than CPython. See more [MicroPython-specific details](deflate.html#deflate-wbits) in the [`deflate`](deflate.html#module-deflate "deflate: deflate compression & decompression") module documentation. If the data to be decompressed requires a larger window size, it will fail during decompression. zlib.compress(_data_, _wbits\=15_, _/_)[¶](#zlib.compress "Link to this definition") 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`](https://docs.python.org/3.5/library/zlib.html#module-zlib "(in Python v3.5)") 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](deflate.html#deflate-wbits) in the [`deflate`](deflate.html#module-deflate "deflate: deflate compression & decompression") module documentation. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # MicroPython language and implementation — MicroPython latest documentation * [](../index.html) * MicroPython language and implementation * [View page source](../_sources/reference/index.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython language and implementation[¶](#micropython-language-and-implementation "Link to this heading") ============================================================================================================ MicroPython aims to implement the Python 3.4 standard (with selected features from later versions) with respect to language syntax, and most of the features of MicroPython are identical to those described by the “Language Reference” documentation at [docs.python.org](https://docs.python.org/3/reference/index.html) . The MicroPython standard library is described in the [corresponding chapter](../library/index.html#micropython-lib) . The [MicroPython differences from CPython](../genrst/index.html#cpython-diffs) chapter describes differences between MicroPython and CPython (which mostly concern standard library and types, but also some language-level features). This chapter describes features and peculiarities of MicroPython implementation and the best practices to use them. * [Glossary](glossary.html) * [The MicroPython Interactive Interpreter Mode (aka REPL)](repl.html) * [Reset and Boot Sequence](reset_boot.html) * [MicroPython remote control: mpremote](mpremote.html) * [MicroPython .mpy files](mpyfiles.html) * [Writing interrupt handlers](isr_rules.html) * [Maximising MicroPython speed](speed_python.html) * [MicroPython on microcontrollers](constrained.html) * [MicroPython manifest files](manifest.html) * [Package management](packages.html) * [Inline assembler for Thumb2 architectures](asm_thumb2_index.html) * [Working with filesystems](filesystem.html) * [The pyboard.py tool](pyboard.py.html) * [MicroPython 2.0 Migration Guide](micropython2_migration.html) Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # _thread – multithreading support — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `_thread` – multithreading support * [View page source](../_sources/library/_thread.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`_thread`](#module-_thread "_thread: multithreading support") – multithreading support[¶](#module-_thread "Link to this heading") ==================================================================================================================================== _This module implements a subset of the corresponding_ [CPython](../reference/glossary.html#term-CPython) _module, as described below. For more information, refer to the original CPython documentation:_ [`_thread`](https://docs.python.org/3.5/library/_thread.html#module-_thread "(in Python v3.5)") . 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. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # MicroPython differences from CPython — MicroPython latest documentation * [](../index.html) * MicroPython differences from CPython * [View page source](../_sources/genrst/index.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython differences from CPython[¶](#micropython-differences-from-cpython "Link to this heading") ====================================================================================================== MicroPython implements Python 3.4 and some select features of Python 3.5 and above. The sections below describe the current status of these features. * [Python 3.5](../differences/python_35.html) * [Python 3.6](../differences/python_36.html) * [Python 3.7](../differences/python_37.html) * [Python 3.8](../differences/python_38.html) * [Python 3.9](../differences/python_39.html) * [Python 3.10](../differences/python_310.html) For the features of Python that are implemented by MicroPython, there are sometimes differences in their behaviour compared to standard Python. The operations listed in the sections below produce conflicting results in MicroPython when compared to standard Python. * [Syntax](syntax.html) * [Argument unpacking does not work if the argument being unpacked is the nth or greater argument where n is the number of bits in an MP\_SMALL\_INT.](syntax.html#argument-unpacking-does-not-work-if-the-argument-being-unpacked-is-the-nth-or-greater-argument-where-n-is-the-number-of-bits-in-an-mp-small-int) * [MicroPython allows := to assign to the iteration variable in nested comprehensions, CPython does not.](syntax.html#micropython-allows-to-assign-to-the-iteration-variable-in-nested-comprehensions-cpython-does-not) * [uPy requires spaces between literal numbers and keywords, CPy doesn’t](syntax.html#upy-requires-spaces-between-literal-numbers-and-keywords-cpy-doesn-t) * [Unicode name escapes are not implemented](syntax.html#unicode-name-escapes-are-not-implemented) * [Core language](core_language.html) * [f-strings don’t support concatenation with adjacent literals if the adjacent literals contain braces](core_language.html#f-strings-don-t-support-concatenation-with-adjacent-literals-if-the-adjacent-literals-contain-braces) * [f-strings cannot support expressions that require parsing to resolve unbalanced nested braces and brackets](core_language.html#f-strings-cannot-support-expressions-that-require-parsing-to-resolve-unbalanced-nested-braces-and-brackets) * [f-strings don’t support !a conversions](core_language.html#f-strings-don-t-support-a-conversions) * [Special method \_\_del\_\_ not implemented for user-defined classes](core_language.html#special-method-del-not-implemented-for-user-defined-classes) * [Method Resolution Order (MRO) is not compliant with CPython](core_language.html#method-resolution-order-mro-is-not-compliant-with-cpython) * [Private Class Members name mangling is not implemented](core_language.html#private-class-members-name-mangling-is-not-implemented) * [When inheriting native types, calling a method in `__init__(self, ...)` before `super().__init__()` raises an `AttributeError` (or segfaults if `MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG` is not enabled).](core_language.html#when-inheriting-native-types-calling-a-method-in-init-self-before-super-init-raises-an-attributeerror-or-segfaults-if-micropy-builtin-method-check-self-arg-is-not-enabled) * [When inheriting from multiple classes super() only calls one class](core_language.html#when-inheriting-from-multiple-classes-super-only-calls-one-class) * [Calling super() getter property in subclass will return a property object, not the value](core_language.html#calling-super-getter-property-in-subclass-will-return-a-property-object-not-the-value) * [Error messages for methods may display unexpected argument counts](core_language.html#error-messages-for-methods-may-display-unexpected-argument-counts) * [Function objects do not have the `__module__` attribute](core_language.html#function-objects-do-not-have-the-module-attribute) * [User-defined attributes for functions are not supported](core_language.html#user-defined-attributes-for-functions-are-not-supported) * [Context manager \_\_exit\_\_() not called in a generator which does not run to completion](core_language.html#context-manager-exit-not-called-in-a-generator-which-does-not-run-to-completion) * [Local variables aren’t included in locals() result](core_language.html#local-variables-aren-t-included-in-locals-result) * [Code running in eval() function doesn’t have access to local variables](core_language.html#code-running-in-eval-function-doesn-t-have-access-to-local-variables) * [\_\_all\_\_ is unsupported in \_\_init\_\_.py in MicroPython.](core_language.html#all-is-unsupported-in-init-py-in-micropython) * [\_\_path\_\_ attribute of a package has a different type (single string instead of list of strings) in MicroPython](core_language.html#path-attribute-of-a-package-has-a-different-type-single-string-instead-of-list-of-strings-in-micropython) * [MicroPython doesn’t support namespace packages split across filesystem.](core_language.html#micropython-doesn-t-support-namespace-packages-split-across-filesystem) * [Builtin types](builtin_types.html) * [Exception](builtin_types.html#exception) * [bytearray](builtin_types.html#bytearray) * [bytes](builtin_types.html#bytes) * [dict](builtin_types.html#dict) * [float](builtin_types.html#float) * [int](builtin_types.html#int) * [list](builtin_types.html#list) * [memoryview](builtin_types.html#memoryview) * [str](builtin_types.html#str) * [tuple](builtin_types.html#tuple) * [Modules](modules.html) * [Positional-only Parameters](modules.html#positional-only-parameters) * [array](modules.html#array) * [json](modules.html#json) * [os](modules.html#os) * [random](modules.html#random) * [struct](modules.html#struct) * [sys](modules.html#sys) Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # MicroPython Internals — MicroPython latest documentation * [](../index.html) * MicroPython Internals * [View page source](../_sources/develop/index.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython Internals[¶](#micropython-internals "Link to this heading") ======================================================================== This chapter covers a tour of MicroPython from the perspective of a developer, contributing to MicroPython. It acts as a comprehensive resource on the implementation details of MicroPython for both novice and expert contributors. Development around MicroPython usually involves modifying the core runtime, porting or maintaining a new library. This guide describes at great depth, the implementation details of MicroPython including a getting started guide, compiler internals, porting MicroPython to a new platform and implementing a core MicroPython library. * [Getting Started](gettingstarted.html) * [Source control with git](gettingstarted.html#source-control-with-git) * [Get the code](gettingstarted.html#get-the-code) * [Compile and build the code](gettingstarted.html#compile-and-build-the-code) * [Required dependencies](gettingstarted.html#required-dependencies) * [Building the MicroPython cross-compiler](gettingstarted.html#building-the-micropython-cross-compiler) * [Building the Unix port of MicroPython](gettingstarted.html#building-the-unix-port-of-micropython) * [Building the Windows port](gettingstarted.html#building-the-windows-port) * [Building the STM32 port](gettingstarted.html#building-the-stm32-port) * [Building the documentation](gettingstarted.html#building-the-documentation) * [Running the tests](gettingstarted.html#running-the-tests) * [Folder structure](gettingstarted.html#folder-structure) * [Writing tests](writingtests.html) * [The Compiler](compiler.html) * [Adding a grammar rule](compiler.html#adding-a-grammar-rule) * [Adding a lexical token](compiler.html#adding-a-lexical-token) * [Parsing](compiler.html#parsing) * [Compiler passes](compiler.html#compiler-passes) * [First pass](compiler.html#first-pass) * [Second and third passes](compiler.html#second-and-third-passes) * [Fourth pass](compiler.html#fourth-pass) * [Emitting bytecode](compiler.html#emitting-bytecode) * [Emitting native code](compiler.html#emitting-native-code) * [Memory Management](memorymgt.html) * [The object model](memorymgt.html#the-object-model) * [Allocation of objects](memorymgt.html#allocation-of-objects) * [Implementing a Module](library.html) * [Implementing a core module](library.html#implementing-a-core-module) * [Optimizations](optimizations.html) * [Frozen bytecode](optimizations.html#frozen-bytecode) * [Variables](optimizations.html#variables) * [Allocation of memory](optimizations.html#allocation-of-memory) * [MicroPython string interning](qstr.html) * [Compile-time QSTR generation](qstr.html#compile-time-qstr-generation) * [Run-time QSTR generation](qstr.html#run-time-qstr-generation) * [Maps and Dictionaries](maps.html) * [Open addressing](maps.html#open-addressing) * [Linear probing](maps.html#linear-probing) * [The public C API](publiccapi.html) * [Extending MicroPython in C](extendingmicropython.html) * [MicroPython external C modules](cmodules.html) * [Structure of an external C module](cmodules.html#structure-of-an-external-c-module) * [Basic example](cmodules.html#basic-example) * [Compiling the cmodule into MicroPython](cmodules.html#compiling-the-cmodule-into-micropython) * [Module usage in MicroPython](cmodules.html#module-usage-in-micropython) * [Native machine code in .mpy files](natmod.html) * [Supported features and limitations](natmod.html#supported-features-and-limitations) * [Defining a native module](natmod.html#defining-a-native-module) * [Minimal example](natmod.html#minimal-example) * [Compiling the module](natmod.html#compiling-the-module) * [Module usage in MicroPython](natmod.html#module-usage-in-micropython) * [Further examples](natmod.html#further-examples) * [Porting MicroPython](porting.html) * [Minimal MicroPython firmware](porting.html#minimal-micropython-firmware) * [MicroPython Configurations](porting.html#micropython-configurations) * [Support for standard input/output](porting.html#support-for-standard-input-output) * [Building and running](porting.html#building-and-running) * [Adding a module to the port](porting.html#adding-a-module-to-the-port) Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # MicroPython license information — MicroPython latest documentation * [](index.html) * MicroPython license information * [View page source](_sources/license.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. MicroPython license information[¶](#micropython-license-information "Link to this heading") ============================================================================================ The MIT License (MIT) Copyright (c) 2013-2017 Damien P. George, and others Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the pyboard — MicroPython latest documentation * [](../index.html) * Quick reference for the pyboard * [View page source](../_sources/pyboard/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the pyboard[¶](#quick-reference-for-the-pyboard "Link to this heading") ============================================================================================ The below pinout is for PYBv1.1. You can also view pinouts for other versions of the pyboard: [PYBv1.0](http://micropython.org/resources/pybv10-pinout.jpg) or [PYBLITEv1.0-AC](http://micropython.org/resources/pyblitev10ac-pinout.jpg) or [PYBLITEv1.0](http://micropython.org/resources/pyblitev10-pinout.jpg) . [![PYBv1.1 pinout](http://micropython.org/resources/pybv11-pinout.jpg)](http://micropython.org/resources/pybv11-pinout.jpg) Below is a quick reference for the pyboard. If it is your first time working with this board please consider reading the following sections first: * [General information about the pyboard](general.html) * [MicroPython tutorial for the pyboard](tutorial/index.html) General board control[¶](#general-board-control "Link to this heading") ------------------------------------------------------------------------ See [`pyb`](../library/pyb.html#module-pyb "pyb: functions related to the board") . import pyb pyb.repl\_uart(pyb.UART(1, 9600)) \# duplicate REPL on UART(1) pyb.wfi() \# pause CPU, waiting for interrupt pyb.freq() \# get CPU and bus frequencies pyb.freq(60000000) \# set CPU freq to 60MHz pyb.stop() \# stop CPU, waiting for external interrupt Delay and timing[¶](#delay-and-timing "Link to this heading") -------------------------------------------------------------- Use the [`time`](../library/time.html#module-time "time: time related functions") module: import time time.sleep(1) \# sleep for 1 second time.sleep\_ms(500) \# sleep for 500 milliseconds time.sleep\_us(10) \# sleep for 10 microseconds start \= time.ticks\_ms() \# get value of millisecond counter delta \= time.ticks\_diff(time.ticks\_ms(), start) \# compute time difference Internal LEDs[¶](#internal-leds "Link to this heading") -------------------------------------------------------- See [pyb.LED](../library/pyb.LED.html#pyb-led) . from pyb import LED led \= LED(1) \# 1=red, 2=green, 3=yellow, 4=blue led.toggle() led.on() led.off() \# LEDs 3 and 4 support PWM intensity (0-255) LED(4).intensity() \# get intensity LED(4).intensity(128) \# set intensity to half Internal switch[¶](#internal-switch "Link to this heading") ------------------------------------------------------------ See [pyb.Switch](../library/pyb.Switch.html#pyb-switch) . from pyb import Switch sw \= Switch() sw.value() \# returns True or False sw.callback(lambda: pyb.LED(1).toggle()) Pins and GPIO[¶](#pins-and-gpio "Link to this heading") -------------------------------------------------------- See [pyb.Pin](../library/pyb.Pin.html#pyb-pin) . from pyb import Pin p\_out \= Pin('X1', Pin.OUT\_PP) p\_out.high() p\_out.low() p\_in \= Pin('X2', Pin.IN, Pin.PULL\_UP) p\_in.value() \# get value, 0 or 1 Servo control[¶](#servo-control "Link to this heading") -------------------------------------------------------- See [pyb.Servo](../library/pyb.Servo.html#pyb-servo) . from pyb import Servo s1 \= Servo(1) \# servo on position 1 (X1, VIN, GND) s1.angle(45) \# move to 45 degrees s1.angle(\-60, 1500) \# move to -60 degrees in 1500ms s1.speed(50) \# for continuous rotation servos External interrupts[¶](#external-interrupts "Link to this heading") -------------------------------------------------------------------- See [pyb.ExtInt](../library/pyb.ExtInt.html#pyb-extint) . from pyb import Pin, ExtInt callback \= lambda e: print("intr") ext \= ExtInt(Pin('Y1'), ExtInt.IRQ\_RISING, Pin.PULL\_NONE, callback) Timers[¶](#timers "Link to this heading") ------------------------------------------ See [pyb.Timer](../library/pyb.Timer.html#pyb-timer) . from pyb import Timer tim \= Timer(1, freq\=1000) tim.counter() \# get counter value tim.freq(0.5) \# 0.5 Hz tim.callback(lambda t: pyb.LED(1).toggle()) RTC (real time clock)[¶](#rtc-real-time-clock "Link to this heading") ---------------------------------------------------------------------- See [pyb.RTC](../library/pyb.RTC.html#pyb-rtc) from pyb import RTC rtc \= RTC() rtc.datetime((2017, 8, 23, 0, 1, 12, 48, 0)) \# set a specific date and \# time, eg. 2017/8/23 1:12:48 \# the day-of-week value is ignored rtc.datetime() \# get date and time PWM (pulse width modulation)[¶](#pwm-pulse-width-modulation "Link to this heading") ------------------------------------------------------------------------------------ See [pyb.Pin](../library/pyb.Pin.html#pyb-pin) and [pyb.Timer](../library/pyb.Timer.html#pyb-timer) . from pyb import Pin, Timer p \= Pin('X1') \# X1 has TIM2, CH1 tim \= Timer(2, freq\=1000) ch \= tim.channel(1, Timer.PWM, pin\=p) ch.pulse\_width\_percent(50) ADC (analog to digital conversion)[¶](#adc-analog-to-digital-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ See [pyb.Pin](../library/pyb.Pin.html#pyb-pin) and [pyb.ADC](../library/pyb.ADC.html#pyb-adc) . from pyb import Pin, ADC adc \= ADC(Pin('X19')) adc.read() \# read value, 0-4095 DAC (digital to analog conversion)[¶](#dac-digital-to-analog-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ See [pyb.Pin](../library/pyb.Pin.html#pyb-pin) and [pyb.DAC](../library/pyb.DAC.html#pyb-dac) . from pyb import Pin, DAC dac \= DAC(Pin('X5')) dac.write(120) \# output between 0 and 255 UART (serial bus)[¶](#uart-serial-bus "Link to this heading") -------------------------------------------------------------- See [pyb.UART](../library/pyb.UART.html#pyb-uart) . from pyb import UART uart \= UART(1, 9600) uart.write('hello') uart.read(5) \# read up to 5 bytes SPI bus[¶](#spi-bus "Link to this heading") -------------------------------------------- See [pyb.SPI](../library/pyb.SPI.html#pyb-spi) . from pyb import SPI spi \= SPI(1, SPI.CONTROLLER, baudrate\=200000, polarity\=1, phase\=0) spi.send('hello') spi.recv(5) \# receive 5 bytes on the bus spi.send\_recv('hello') \# send and receive 5 bytes I2C bus[¶](#i2c-bus "Link to this heading") -------------------------------------------- Hardware I2C is available on the X and Y halves of the pyboard via `I2C('X')` and `I2C('Y')`. Alternatively pass in the integer identifier of the peripheral, eg `I2C(1)`. Software I2C is also available by explicitly specifying the `scl` and `sda` pins instead of the bus name. For more details see [machine.I2C](../library/machine.I2C.html#machine-i2c) . from machine import I2C i2c \= I2C('X', freq\=400000) \# create hardware I2c object i2c \= I2C(scl\='X1', sda\='X2', freq\=100000) \# create software I2C object i2c.scan() \# returns list of peripheral addresses i2c.writeto(0x42, 'hello') \# write 5 bytes to peripheral with address 0x42 i2c.readfrom(0x42, 5) \# read 5 bytes from peripheral i2c.readfrom\_mem(0x42, 0x10, 2) \# read 2 bytes from peripheral 0x42, peripheral memory 0x10 i2c.writeto\_mem(0x42, 0x10, 'xy') \# write 2 bytes to peripheral 0x42, peripheral memory 0x10 Note: for legacy I2C support see [pyb.I2C](../library/pyb.I2C.html#pyb-i2c) . I2S bus[¶](#i2s-bus "Link to this heading") -------------------------------------------- See [machine.I2S](../library/machine.I2S.html#machine-i2s) . from machine import I2S, Pin i2s \= I2S(2, sck\=Pin('Y6'), ws\=Pin('Y5'), sd\=Pin('Y8'), mode\=I2S.TX, bits\=16, format\=I2S.STEREO, rate\=44100, ibuf\=40000) \# create I2S object i2s.write(buf) \# write buffer of audio samples to I2S device i2s \= I2S(1, sck\=Pin('X5'), ws\=Pin('X6'), sd\=Pin('Y4'), mode\=I2S.RX, bits\=16, format\=I2S.MONO, rate\=22050, ibuf\=40000) \# create I2S object i2s.readinto(buf) \# fill buffer with audio samples from I2S device 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. PYBv1.0/v1.1 has one I2S bus with id=2. PYBD-SFxW has two I2S buses with id=1 and id=2. I2S is shared with SPI. CAN bus (controller area network)[¶](#can-bus-controller-area-network "Link to this heading") ---------------------------------------------------------------------------------------------- See [pyb.CAN](../library/pyb.CAN.html#pyb-can) . from pyb import CAN can \= CAN(1, CAN.LOOPBACK) can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) can.send('message!', 123) \# send a message with id 123 can.recv(0) \# receive message on FIFO 0 Internal accelerometer[¶](#internal-accelerometer "Link to this heading") -------------------------------------------------------------------------- See [pyb.Accel](../library/pyb.Accel.html#pyb-accel) . from pyb import Accel accel \= Accel() print(accel.x(), accel.y(), accel.z(), accel.tilt()) Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # btree – simple BTree database — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `btree` – simple BTree database * [View page source](../_sources/library/btree.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`btree`](#module-btree "btree: simple BTree database") – simple BTree database[¶](#module-btree "Link to this heading") ========================================================================================================================== The `btree` module implements a simple key-value database using external storage (disk files, or in general case, a random-access [`stream`](../reference/glossary.html#term-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`](builtins.html#dict "dict") type works, one notable difference is that both keys and values must be [`bytes`](builtins.html#bytes "bytes") \-like objects (so, if you want to store objects of other types, you need to first serialize them to [`str`](builtins.html#str "str") or [`bytes`](builtins.html#bytes "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. \# 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[¶](#functions "Link to this heading") ------------------------------------------------ btree.open(_stream_, _\*_, _flags\=0_, _pagesize\=0_, _cachesize\=0_, _minkeypage\=0_)[¶](#btree.open "Link to this definition") Open a database from a random-access [`stream`](../reference/glossary.html#term-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[¶](#methods "Link to this heading") -------------------------------------------- btree.close()[¶](#btree.btree.close "Link to this definition") 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()[¶](#btree.btree.flush "Link to this definition") Flush any data in cache to the underlying stream. btree.\_\_getitem\_\_(_key_)[¶](#btree.btree.__getitem__ "Link to this definition") btree.get(_key_, _default\=None_, _/_)[¶](#btree.btree.get "Link to this definition") btree.\_\_setitem\_\_(_key_, _val_)[¶](#btree.btree.__setitem__ "Link to this definition") btree.\_\_delitem\_\_(_key_)[¶](#btree.btree.__delitem__ "Link to this definition") btree.\_\_contains\_\_(_key_)[¶](#btree.btree.__contains__ "Link to this definition") Standard dictionary methods. btree.\_\_iter\_\_()[¶](#btree.btree.__iter__ "Link to this definition") 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.btree.keys "Link to this definition") btree.values(\[_start\_key_\[, _end\_key_\[, _flags_\]\]\])[¶](#btree.btree.values "Link to this definition") btree.items(\[_start\_key_\[, _end\_key_\[, _flags_\]\]\])[¶](#btree.btree.items "Link to this definition") 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()`](#btree.btree.values "btree.btree.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`](#btree.INCL "btree.INCL") . You can iterate in descending key direction by passing _flags_ of [`btree.DESC`](#btree.DESC "btree.DESC") . The flags values can be ORed together. Constants[¶](#constants "Link to this heading") ------------------------------------------------ btree.INCL[¶](#btree.INCL "Link to this definition") A flag for [`keys()`](#btree.btree.keys "btree.btree.keys") , [`values()`](#btree.btree.values "btree.btree.values") , [`items()`](#btree.btree.items "btree.btree.items") methods to specify that scanning should be inclusive of the end key. btree.DESC[¶](#btree.DESC "Link to this definition") A flag for [`keys()`](#btree.btree.keys "btree.btree.keys") , [`values()`](#btree.btree.values "btree.btree.values") , [`items()`](#btree.btree.items "btree.btree.items") methods to specify that scanning should be in descending direction of keys. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the ESP8266 — MicroPython latest documentation * [](../index.html) * Quick reference for the ESP8266 * [View page source](../_sources/esp8266/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the ESP8266[¶](#quick-reference-for-the-esp8266 "Link to this heading") ============================================================================================ [![Adafruit Feather HUZZAH board](../_images/adafruit_products_pinoutstop.jpg)](../_images/adafruit_products_pinoutstop.jpg) The Adafruit Feather HUZZAH board (image attribution: Adafruit). Below is a quick reference for ESP8266-based boards. If it is your first time working with this board please consider reading the following sections first: * [General information about the ESP8266 port](general.html) * [MicroPython tutorial for ESP8266](tutorial/index.html) Installing MicroPython[¶](#installing-micropython "Link to this heading") -------------------------------------------------------------------------- See the corresponding section of tutorial: [Getting started with MicroPython on the ESP8266](tutorial/intro.html#intro) . It also includes a troubleshooting subsection. General board control[¶](#general-board-control "Link to this heading") ------------------------------------------------------------------------ The MicroPython REPL is on UART0 (GPIO1=TX, GPIO3=RX) at baudrate 115200. Tab-completion is useful to find out what methods an object has. Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL. The [`machine`](../library/machine.html#module-machine "machine: functions related to the hardware") module: import machine machine.freq() \# get the current frequency of the CPU machine.freq(160000000) \# set the CPU frequency to 160 MHz The [`esp`](../library/esp.html#module-esp "esp: functions related to the ESP8266 and ESP32") module: import esp esp.osdebug(None) \# turn off vendor O/S debugging messages esp.osdebug(0) \# redirect vendor O/S debugging messages to UART(0) Networking[¶](#networking "Link to this heading") -------------------------------------------------- The [`network.WLAN`](../library/network.WLAN.html#network.WLAN "network.WLAN") class in the [`network`](../library/network.html#module-network "network: network configuration") module: import network wlan \= network.WLAN(network.WLAN.IF\_STA) \# create station interface wlan.active(True) \# activate the interface wlan.scan() \# scan for access points wlan.isconnected() \# check if the station is connected to an AP wlan.connect('ssid', 'key') \# connect to an AP wlan.config('mac') \# get the interface's MAC address wlan.ipconfig('addr4') \# get the interface's IPv4 addresses ap \= network.WLAN(network.WLAN.IF\_AP) \# create access-point interface ap.active(True) \# activate the interface ap.config(ssid\='ESP-AP') \# set the SSID of the access point A useful function for connecting to your local WiFi network is: def do\_connect(): import network wlan \= network.WLAN(network.WLAN.IF\_STA) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect('ssid', 'key') while not wlan.isconnected(): pass print('network config:', wlan.ipconfig('addr4')) Once the network is established the [`socket`](../library/socket.html#module-socket "socket: socket module") module can be used to create and use TCP/UDP sockets as usual. Delay and timing[¶](#delay-and-timing "Link to this heading") -------------------------------------------------------------- Use the [`time`](../library/time.html#module-time "time: time related functions") module: import time time.sleep(1) \# sleep for 1 second time.sleep\_ms(500) \# sleep for 500 milliseconds time.sleep\_us(10) \# sleep for 10 microseconds start \= time.ticks\_ms() \# get millisecond counter delta \= time.ticks\_diff(time.ticks\_ms(), start) \# compute time difference Timers[¶](#timers "Link to this heading") ------------------------------------------ Virtual (RTOS-based) timers are supported. Use the [machine.Timer](../library/machine.Timer.html#machine-timer) class with timer ID of -1: from machine import Timer tim \= Timer(\-1) tim.init(period\=5000, mode\=Timer.ONE\_SHOT, callback\=lambda t:print(1)) tim.init(period\=2000, mode\=Timer.PERIODIC, callback\=lambda t:print(2)) The period is in milliseconds. Pins and GPIO[¶](#pins-and-gpio "Link to this heading") -------------------------------------------------------- Use the [machine.Pin](../library/machine.Pin.html#machine-pin) class: from machine import Pin p0 \= Pin(0, Pin.OUT) \# create output pin on GPIO0 p0.on() \# set pin to "on" (high) level p0.off() \# set pin to "off" (low) level p0.value(1) \# set pin to on/high p2 \= Pin(2, Pin.IN) \# create input pin on GPIO2 print(p2.value()) \# get value, 0 or 1 p4 \= Pin(4, Pin.IN, Pin.PULL\_UP) \# enable internal pull-up resistor p5 \= Pin(5, Pin.OUT, value\=1) \# set pin high on creation Available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspond to the actual GPIO pin numbers of ESP8266 chip. Note that many end-user boards use their own adhoc pin numbering (marked e.g. D0, D1, …). As MicroPython supports different boards and modules, physical pin numbering was chosen as the lowest common denominator. For mapping between board logical pins and physical chip pins, consult your board documentation. Note that Pin(1) and Pin(3) are REPL UART TX and RX respectively. Also note that Pin(16) is a special pin (used for wakeup from deepsleep mode) and may be not available for use with higher-level classes like `Neopixel`. There’s a higher-level abstraction [machine.Signal](../library/machine.Signal.html#machine-signal) which can be used to invert a pin. Useful for illuminating active-low LEDs using `on()` or `value(1)`. UART (serial bus)[¶](#uart-serial-bus "Link to this heading") -------------------------------------------------------------- See [machine.UART](../library/machine.UART.html#machine-uart) . from machine import UART uart \= UART(0, baudrate\=9600) uart.write('hello') uart.read(5) \# read up to 5 bytes Two UARTs are available. UART0 is on Pins 1 (TX) and 3 (RX). UART0 is bidirectional, and by default is used for the REPL. UART1 is on Pins 2 (TX) and 8 (RX) however Pin 8 is used to connect the flash chip, so UART1 is TX only. When UART0 is attached to the REPL, all incoming chars on UART(0) go straight to stdin so uart.read() will always return None. Use sys.stdin.read() if it’s needed to read characters from the UART(0) while it’s also used for the REPL (or detach, read, then reattach). When detached the UART(0) can be used for other purposes. If there are no objects in any of the dupterm slots when the REPL is started (on [hard or soft reset](../reference/reset_boot.html) ) then UART(0) is automatically attached. Without this, the only way to recover a board without a REPL would be to completely erase and reflash (which would install the default boot.py which attaches the REPL). To detach the REPL from UART0, use: import os os.dupterm(None, 1) The REPL is attached by default. If you have detached it, to reattach it use: import os, machine uart \= machine.UART(0, 115200) os.dupterm(uart, 1) PWM (pulse width modulation)[¶](#pwm-pulse-width-modulation "Link to this heading") ------------------------------------------------------------------------------------ PWM can be enabled on all pins except Pin(16). There is a single frequency for all channels, with range between 1 and 1000 (measured in Hz). The duty cycle is between 0 and 1023 inclusive. Use the `machine.PWM` class: from machine import Pin, PWM pwm0 \= PWM(Pin(0)) \# create PWM object from a pin pwm0.freq() \# get current frequency pwm0.freq(1000) \# set frequency pwm0.duty() \# get current duty cycle pwm0.duty(200) \# set duty cycle pwm0.deinit() \# turn off PWM on the pin pwm2 \= PWM(Pin(2), freq\=500, duty\=512) \# create and configure in one go ADC (analog to digital conversion)[¶](#adc-analog-to-digital-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ ADC is available on a dedicated pin. Note that input voltages on the ADC pin must be between 0v and 1.0v. Use the [machine.ADC](../library/machine.ADC.html#machine-adc) class: from machine import ADC adc \= ADC(0) \# create ADC object on ADC pin adc.read() \# read value, 0-1024 Software SPI bus[¶](#software-spi-bus "Link to this heading") -------------------------------------------------------------- There are two SPI drivers. One is implemented in software (bit-banging) and works on all pins, and is accessed via the [machine.SoftSPI](../library/machine.SPI.html#machine-softspi) class: from machine import Pin, SoftSPI \# construct an SPI bus on the given pins \# polarity is the idle state of SCK \# phase=0 means sample on the first edge of SCK, phase=1 means the second spi \= SoftSPI(baudrate\=100000, polarity\=1, phase\=0, sck\=Pin(0), mosi\=Pin(2), miso\=Pin(4)) spi.init(baudrate\=200000) \# set the baudrate spi.read(10) \# read 10 bytes on MISO spi.read(10, 0xff) \# read 10 bytes while outputting 0xff on MOSI buf \= bytearray(50) \# create a buffer spi.readinto(buf) \# read into the given buffer (reads 50 bytes in this case) spi.readinto(buf, 0xff) \# read into the given buffer and output 0xff on MOSI spi.write(b'12345') \# write 5 bytes on MOSI buf \= bytearray(4) \# create a buffer spi.write\_readinto(b'1234', buf) \# write to MOSI and read from MISO into the buffer spi.write\_readinto(buf, buf) \# write buf to MOSI and read MISO back into buf Hardware SPI bus[¶](#hardware-spi-bus "Link to this heading") -------------------------------------------------------------- The hardware SPI is faster (up to 80Mhz), but only works on following pins: `MISO` is GPIO12, `MOSI` is GPIO13, and `SCK` is GPIO14. It has the same methods as the bitbanging SPI class above, except for the pin parameters for the constructor and init (as those are fixed): from machine import Pin, SPI hspi \= SPI(1, baudrate\=80000000, polarity\=0, phase\=0) (`SPI(0)` is used for FlashROM and not available to users.) I2C bus[¶](#i2c-bus "Link to this heading") -------------------------------------------- The I2C driver is implemented in software and works on all pins, and is accessed via the [machine.I2C](../library/machine.I2C.html#machine-i2c) class (which is an alias of [machine.SoftI2C](../library/machine.I2C.html#machine-softi2c) ): from machine import Pin, I2C \# construct an I2C bus i2c \= I2C(scl\=Pin(5), sda\=Pin(4), freq\=100000) i2c.readfrom(0x3a, 4) \# read 4 bytes from peripheral device with address 0x3a i2c.writeto(0x3a, '12') \# write '12' to peripheral device with address 0x3a buf \= bytearray(10) \# create a buffer with 10 bytes i2c.writeto(0x3a, buf) \# write the given buffer to the peripheral Real time clock (RTC)[¶](#real-time-clock-rtc "Link to this heading") ---------------------------------------------------------------------- See [machine.RTC](../library/machine.RTC.html#machine-rtc) from machine import RTC rtc \= RTC() rtc.datetime((2017, 8, 23, 0, 1, 12, 48, 0)) \# set a specific date and \# time, eg. 2017/8/23 1:12:48 \# the day-of-week value is ignored rtc.datetime() \# get date and time \# synchronize with ntp \# need to be connected to wifi import ntptime ntptime.settime() \# set the rtc datetime from the remote server rtc.datetime() \# get the date and time in UTC Note Not all methods are implemented: [`RTC.now()`](../library/machine.RTC.html#machine.RTC.now "machine.RTC.now") , [`RTC.irq(handler=*)`](../library/machine.RTC.html#machine.RTC.irq "machine.RTC.irq") (using a custom handler), [`RTC.init()`](../library/machine.RTC.html#machine.RTC.init "machine.RTC.init") and [`RTC.deinit()`](../library/machine.RTC.html#machine.RTC.deinit "machine.RTC.deinit") are currently not supported. WDT (Watchdog timer)[¶](#wdt-watchdog-timer "Link to this heading") -------------------------------------------------------------------- See [machine.WDT](../library/machine.WDT.html#machine-wdt) . from machine import WDT \# enable the WDT wdt \= WDT() wdt.feed() Deep-sleep mode[¶](#deep-sleep-mode "Link to this heading") ------------------------------------------------------------ Connect GPIO16 to the reset pin (RST on HUZZAH). Then the following code can be used to sleep, wake and check the reset cause: import machine \# configure RTC.ALARM0 to be able to wake the device rtc \= machine.RTC() rtc.irq(trigger\=rtc.ALARM0, wake\=machine.DEEPSLEEP) \# check if the device woke from a deep sleep if machine.reset\_cause() \== machine.DEEPSLEEP\_RESET: print('woke from a deep sleep') \# set RTC.ALARM0 to fire after 10 seconds (waking the device) rtc.alarm(rtc.ALARM0, 10000) \# put the device to sleep machine.deepsleep() OneWire driver[¶](#onewire-driver "Link to this heading") ---------------------------------------------------------- The OneWire driver is implemented in software and works on all pins: from machine import Pin import onewire ow \= onewire.OneWire(Pin(12)) \# create a OneWire bus on GPIO12 ow.scan() \# return a list of devices on the bus ow.reset() \# reset the bus ow.readbyte() \# read a byte ow.writebyte(0x12) \# write a byte on the bus ow.write('123') \# write bytes on the bus ow.select\_rom(b'12345678') \# select a specific device by its ROM code There is a specific driver for DS18S20 and DS18B20 devices: import time, ds18x20 ds \= ds18x20.DS18X20(ow) roms \= ds.scan() ds.convert\_temp() time.sleep\_ms(750) for rom in roms: print(ds.read\_temp(rom)) Be sure to put a 4.7k pull-up resistor on the data line. Note that the `convert_temp()` method must be called each time you want to sample the temperature. NeoPixel driver[¶](#neopixel-driver "Link to this heading") ------------------------------------------------------------ Use the `neopixel` module: from machine import Pin from neopixel import NeoPixel pin \= Pin(0, Pin.OUT) \# set GPIO0 to output to drive NeoPixels np \= NeoPixel(pin, 8) \# create NeoPixel driver on GPIO0 for 8 pixels np\[0\] \= (255, 255, 255) \# set the first pixel to white np.write() \# write data to all pixels r, g, b \= np\[0\] \# get first pixel colour Warning By default `NeoPixel` is configured to control the more popular _800kHz_ units. It is possible to use alternative timing to control other (typically 400kHz) devices by passing `timing=0` when constructing the `NeoPixel` object. For low-level driving of a NeoPixel see [`machine.bitstream`](../library/machine.html#machine.bitstream "machine.bitstream") . APA102 driver[¶](#apa102-driver "Link to this heading") -------------------------------------------------------- Use the `apa102` module: from machine import Pin from apa102 import APA102 clock \= Pin(14, Pin.OUT) \# set GPIO14 to output to drive the clock data \= Pin(13, Pin.OUT) \# set GPIO13 to output to drive the data apa \= APA102(clock, data, 8) \# create APA102 driver on the clock and the data pin for 8 pixels apa\[0\] \= (255, 255, 255, 31) \# set the first pixel to white with a maximum brightness of 31 apa.write() \# write data to all pixels r, g, b, brightness \= apa\[0\] \# get first pixel colour For low-level driving of an APA102: import esp esp.apa102\_write(clock\_pin, data\_pin, rgbi\_buf) DHT driver[¶](#dht-driver "Link to this heading") -------------------------------------------------- The DHT driver is implemented in software and works on all pins: import dht import machine d \= dht.DHT11(machine.Pin(4)) d.measure() d.temperature() \# eg. 23 (°C) d.humidity() \# eg. 41 (% RH) d \= dht.DHT22(machine.Pin(4)) d.measure() d.temperature() \# eg. 23.6 (°C) d.humidity() \# eg. 41.3 (% RH) SSD1306 driver[¶](#ssd1306-driver "Link to this heading") ---------------------------------------------------------- Driver for SSD1306 monochrome OLED displays. See tutorial [Using a SSD1306 OLED display](tutorial/ssd1306.html#ssd1306) . from machine import Pin, I2C import ssd1306 i2c \= I2C(scl\=Pin(5), sda\=Pin(4), freq\=100000) display \= ssd1306.SSD1306\_I2C(128, 64, i2c) display.text('Hello World', 0, 0, 1) display.show() WebREPL (web browser interactive prompt)[¶](#webrepl-web-browser-interactive-prompt "Link to this heading") ------------------------------------------------------------------------------------------------------------ WebREPL (REPL over WebSockets, accessible via a web browser) is an experimental feature available in ESP8266 port. Download web client from [https://github.com/micropython/webrepl](https://github.com/micropython/webrepl) (hosted version available at [http://micropython.org/webrepl](http://micropython.org/webrepl) ), and configure it by executing: import webrepl\_setup and following on-screen instructions. After reboot, it will be available for connection. If you disabled automatic start-up on boot, you may run configured daemon on demand using: import webrepl webrepl.start() The supported way to use WebREPL is by connecting to ESP8266 access point, but the daemon is also started on STA interface if it is active, so if your router is set up and works correctly, you may also use WebREPL while connected to your normal Internet access point (use the ESP8266 AP connection method if you face any issues). Besides terminal/command prompt access, WebREPL also has provision for file transfer (both upload and download). Web client has buttons for the corresponding functions, or you can use command-line client `webrepl_cli.py` from the repository above. See the MicroPython forum for other community-supported alternatives to transfer files to ESP8266. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # bluetooth — low-level Bluetooth — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `bluetooth` — low-level Bluetooth * [View page source](../_sources/library/bluetooth.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`bluetooth`](#module-bluetooth "bluetooth: Low-level Bluetooth radio functionality") — low-level Bluetooth[¶](#module-bluetooth "Link to this heading") ========================================================================================================================================================== 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](https://github.com/micropython/micropython-lib/tree/master/micropython/bluetooth/aioble) . Note This module is still under development and its classes, functions, methods and constants are subject to change. class BLE[¶](#class-ble "Link to this heading") ------------------------------------------------ Constructor[¶](#constructor "Link to this heading") ---------------------------------------------------- _class_ bluetooth.BLE[¶](#bluetooth.BLE "Link to this definition") Returns the singleton BLE object. Configuration[¶](#configuration "Link to this heading") -------------------------------------------------------- BLE.active(\[_active_, \]_/_)[¶](#bluetooth.BLE.active "Link to this definition") 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'_, _/_)[¶](#bluetooth.BLE.config "Link to this definition") 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`](#bluetooth.BLE.gatts_write "bluetooth.BLE.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`](#bluetooth.BLE.gattc_exchange_mtu "bluetooth.BLE.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. * `'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[¶](#event-handling "Link to this heading") ---------------------------------------------------------- BLE.irq(_handler_, _/_)[¶](#bluetooth.BLE.irq "Link to this definition") 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`, `notify_data`, and `uuid` entries in the tuples are read-only memoryview instances pointing to [`bluetooth`](#module-bluetooth "bluetooth: Low-level Bluetooth radio functionality") ’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(). 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. \# 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) \_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-bluetooth "bluetooth: Low-level Bluetooth radio functionality") module. Add the ones that you need from the list above to your program. Broadcaster Role (Advertiser)[¶](#broadcaster-role-advertiser "Link to this heading") -------------------------------------------------------------------------------------- BLE.gap\_advertise(_interval\_us_, _adv\_data\=None_, _\*_, _resp\_data\=None_, _connectable\=True_)[¶](#bluetooth.BLE.gap_advertise "Link to this definition") Starts advertising at the specified interval (in **micro**seconds). 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 reused. 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''`. Observer Role (Scanner)[¶](#observer-role-scanner "Link to this heading") -------------------------------------------------------------------------- BLE.gap\_scan(_duration\_ms_, _interval\_us\=1280000_, _window\_us\=11250_, _active\=False_, _/_)[¶](#bluetooth.BLE.gap_scan "Link to this definition") Run a scan operation lasting for the specified duration (in **milli**seconds). 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_ **micro**seconds every _interval\_us_ **micro**seconds for a total of _duration\_ms_ **milli**seconds. The default interval and window 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[¶](#central-role "Link to this heading") ------------------------------------------------------ A central device can connect to peripherals that it has discovered using the observer role (see [`gap_scan`](#bluetooth.BLE.gap_scan "bluetooth.BLE.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_, _/_)[¶](#bluetooth.BLE.gap_connect "Link to this definition") Connect to a peripheral. See [`gap_scan`](#bluetooth.BLE.gap_scan "bluetooth.BLE.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 **micro**seconds 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 microseconds. A shorter interval will increase throughput, at the expense of power usage. Peripheral Role[¶](#peripheral-role "Link to this heading") ------------------------------------------------------------ A peripheral device is expected to send connectable advertisements (see [`gap_advertise`](#bluetooth.BLE.gap_advertise "bluetooth.BLE.gap_advertise") ). It will usually be acting as a GATT server, having first registered services and characteristics using [`gatts_register_services`](#bluetooth.BLE.gatts_register_services "bluetooth.BLE.gatts_register_services") . When a central connects, the `_IRQ_CENTRAL_CONNECT` event will be raised. Central & Peripheral Roles[¶](#central-peripheral-roles "Link to this heading") -------------------------------------------------------------------------------- BLE.gap\_disconnect(_conn\_handle_, _/_)[¶](#bluetooth.BLE.gap_disconnect "Link to this definition") 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[¶](#gatt-server "Link to this heading") ---------------------------------------------------- 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`](#bluetooth.BLE.gatts_write "bluetooth.BLE.gatts_write") after registration. e.g. `gatts_write(char_handle, bytes(100))`. BLE.gatts\_register\_services(_services\_definition_, _/_)[¶](#bluetooth.BLE.gatts_register_services "Link to this 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\_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`](#bluetooth.BLE.gatts_read "bluetooth.BLE.gatts_read") , [`gatts_write`](#bluetooth.BLE.gatts_write "bluetooth.BLE.gatts_write") , [`gatts_notify`](#bluetooth.BLE.gatts_notify "bluetooth.BLE.gatts_notify") , and [`gatts_indicate`](#bluetooth.BLE.gatts_indicate "bluetooth.BLE.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_, _/_)[¶](#bluetooth.BLE.gatts_read "Link to this definition") Reads the local value for this handle (which has either been written by [`gatts_write`](#bluetooth.BLE.gatts_write "bluetooth.BLE.gatts_write") or by a remote client). BLE.gatts\_write(_value\_handle_, _data_, _send\_update\=False_, _/_)[¶](#bluetooth.BLE.gatts_write "Link to this definition") 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_, _/_)[¶](#bluetooth.BLE.gatts_notify "Link to this definition") Sends a notification request to a connected client. If _data_ is `None` (the default), then the current local value (as set with [`gatts_write`](#bluetooth.BLE.gatts_write "bluetooth.BLE.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_, _/_)[¶](#bluetooth.BLE.gatts_indicate "Link to this definition") Sends a indication request to a connected client. If _data_ is `None` (the default), then the current local value (as set with [`gatts_write`](#bluetooth.BLE.gatts_write "bluetooth.BLE.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. 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_, _/_)[¶](#bluetooth.BLE.gatts_set_buffer "Link to this definition") 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`](#bluetooth.BLE.gatts_read "bluetooth.BLE.gatts_read") , the value will be cleared after reading. This feature is useful when implementing something like the Nordic UART Service. GATT Client[¶](#gatt-client "Link to this heading") ---------------------------------------------------- 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_, _/_)[¶](#bluetooth.BLE.gattc_discover_services "Link to this definition") 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_, _/_)[¶](#bluetooth.BLE.gattc_discover_characteristics "Link to this definition") 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, followed by `_IRQ_GATTC_CHARACTERISTIC_DONE` on completion. BLE.gattc\_discover\_descriptors(_conn\_handle_, _start\_handle_, _end\_handle_, _/_)[¶](#bluetooth.BLE.gattc_discover_descriptors "Link to this definition") 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_, _/_)[¶](#bluetooth.BLE.gattc_read "Link to this definition") 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_, _/_)[¶](#bluetooth.BLE.gattc_write "Link to this definition") 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. BLE.gattc\_exchange\_mtu(_conn\_handle_, _/_)[¶](#bluetooth.BLE.gattc_exchange_mtu "Link to this definition") 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[¶](#l2cap-connection-oriented-channels "Link to this heading") -------------------------------------------------------------------------------------------------- > 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 negotiate 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`](#bluetooth.BLE.l2cap_recvinto "bluetooth.BLE.l2cap_recvinto") > . BLE.l2cap\_listen(_psm_, _mtu_, _/_)[¶](#bluetooth.BLE.l2cap_listen "Link to this definition") 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_, _/_)[¶](#bluetooth.BLE.l2cap_connect "Link to this definition") Connect to a listening peer on the specified _psm_ with local MTU set to _mtu_. On successful connection, 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_, _/_)[¶](#bluetooth.BLE.l2cap_disconnect "Link to this definition") Disconnect an active L2CAP channel with the specified _conn\_handle_ and _cid_. BLE.l2cap\_send(_conn\_handle_, _cid_, _buf_, _/_)[¶](#bluetooth.BLE.l2cap_send "Link to this definition") 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`](#bluetooth.BLE.l2cap_send "bluetooth.BLE.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). BLE.l2cap\_recvinto(_conn\_handle_, _cid_, _buf_, _/_)[¶](#bluetooth.BLE.l2cap_recvinto "Link to this definition") 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`](#bluetooth.BLE.l2cap_recvinto "bluetooth.BLE.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-and-bonding "Link to this heading") -------------------------------------------------------------------- > 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 resolve 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 ESP32, STM32 and Unix. BLE.gap\_pair(_conn\_handle_, _/_)[¶](#bluetooth.BLE.gap_pair "Link to this definition") Initiate pairing with the remote device. Before calling this, ensure that the `io`, `mitm`, `le_secure`, and `bond` configuration options are set (via [`config`](#bluetooth.BLE.config "bluetooth.BLE.config") ). On successful pairing, the `_IRQ_ENCRYPTION_UPDATE` event will be raised. BLE.gap\_passkey(_conn\_handle_, _action_, _passkey_, _/_)[¶](#bluetooth.BLE.gap_passkey "Link to this definition") 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). > class UUID[¶](#class-uuid "Link to this heading") -------------------------------------------------- Constructor[¶](#id1 "Link to this heading") -------------------------------------------- _class_ bluetooth.UUID(_value_, _/_)[¶](#bluetooth.UUID "Link to this definition") 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'`. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the ESP32 — MicroPython latest documentation * [](../index.html) * Quick reference for the ESP32 * [View page source](../_sources/esp32/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the ESP32[¶](#quick-reference-for-the-esp32 "Link to this heading") ======================================================================================== [![ESP32 board](../_images/esp32.jpg)](../_images/esp32.jpg) The Espressif ESP32 Development Board (image attribution: Adafruit). Below is a quick reference for ESP32-based boards. If it is your first time working with this board it may be useful to get an overview of the microcontroller: * [General information about the ESP32 port](general.html) * [MicroPython tutorial for ESP32](tutorial/index.html) Note that there are several varieties of ESP32 – ESP32, ESP32C3, ESP32C6, ESP32S2, ESP32S3 – supported by MicroPython, with some differences in functionality between them. Installing MicroPython[¶](#installing-micropython "Link to this heading") -------------------------------------------------------------------------- See the corresponding section of tutorial: [Getting started with MicroPython on the ESP32](tutorial/intro.html#esp32-intro) . It also includes a troubleshooting subsection. General board control[¶](#general-board-control "Link to this heading") ------------------------------------------------------------------------ The MicroPython REPL is on UART0 (GPIO1=TX, GPIO3=RX) at baudrate 115200. Tab-completion is useful to find out what methods an object has. Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL. The [`machine`](../library/machine.html#module-machine "machine: functions related to the hardware") module: import machine machine.freq() \# get the current frequency of the CPU machine.freq(240000000) \# set the CPU frequency to 240 MHz The [`esp`](../library/esp.html#module-esp "esp: functions related to the ESP8266 and ESP32") module: import esp esp.osdebug(None) \# turn off vendor O/S debugging messages esp.osdebug(0) \# redirect vendor O/S debugging messages to UART(0) \# low level methods to interact with flash storage esp.flash\_size() esp.flash\_user\_start() esp.flash\_erase(sector\_no) esp.flash\_write(byte\_offset, buffer) esp.flash\_read(byte\_offset, buffer) The [`esp32`](../library/esp32.html#module-esp32 "esp32: functionality specific to the ESP32") module: import esp32 esp32.raw\_temperature() \# read the internal temperature of the MCU, in Fahrenheit esp32.ULP() \# access to the Ultra-Low-Power Co-processor, not on ESP32C3/C6 Note that the temperature sensor in the ESP32 will typically read higher than ambient due to the IC getting warm while it runs. This effect can be minimised by reading the temperature sensor immediately after waking up from sleep. ESP32C3, ESP32C6, ESP32S2, and ESP32S3 also have an internal temperature sensor available. It is implemented a bit differently to the ESP32 and returns the temperature in Celsius: esp32.mcu\_temperature() \# read the internal temperature of the MCU, in Celsius Networking[¶](#networking "Link to this heading") -------------------------------------------------- ### WLAN[¶](#wlan "Link to this heading") The [`network.WLAN`](../library/network.WLAN.html#network.WLAN "network.WLAN") class in the [`network`](../library/network.html#module-network "network: network configuration") module: import network wlan \= network.WLAN() \# create station interface (the default, see below for an access point interface) wlan.active(True) \# activate the interface wlan.scan() \# scan for access points wlan.isconnected() \# check if the station is connected to an AP wlan.connect('ssid', 'key') \# connect to an AP wlan.config('mac') \# get the interface's MAC address wlan.ipconfig('addr4') \# get the interface's IPv4 addresses ap \= network.WLAN(network.WLAN.IF\_AP) \# create access-point interface ap.config(ssid\='ESP-AP') \# set the SSID of the access point ap.config(max\_clients\=10) \# set how many clients can connect to the network ap.active(True) \# activate the interface A useful function for connecting to your local WiFi network is: def do\_connect(): import machine, network wlan \= network.WLAN() wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect('ssid', 'key') while not wlan.isconnected(): machine.idle() print('network config:', wlan.ipconfig('addr4')) Once the network is established the [`socket`](../library/socket.html#module-socket "socket: socket module") module can be used to create and use TCP/UDP sockets as usual, and the `requests` module for convenient HTTP requests. After a call to `wlan.connect()`, the device will by default retry to connect **forever**, even when the authentication failed or no AP is in range. `wlan.status()` will return `network.STAT_CONNECTING` in this state until a connection succeeds or the interface gets disabled. This can be changed by calling `wlan.config(reconnects=n)`, where n are the number of desired reconnect attempts (0 means it won’t retry, -1 will restore the default behaviour of trying to reconnect forever). ### LAN[¶](#lan "Link to this heading") #### Built-in MAC (original ESP32)[¶](#built-in-mac-original-esp32 "Link to this heading") The original ESP32 SoC has a built-in Ethernet MAC. Using this MAC requires an external Ethernet PHY to be wired to the chip’s EMAC pins. Most of the EMAC pin assignments are fixed, consult the ESP32 datasheet for details. If the PHY is connected, the internal Ethernet MAC can be configured via the [`network.LAN`](../library/network.LAN.html#network.LAN "network.LAN") constructor: import network lan \= network.LAN(mdc\=PIN\_MDC, ...) \# Set the pin and mode configuration lan.active(True) \# activate the interface lan.ipconfig('addr4') \# get the interface's IPv4 addresses Required keyword arguments for the constructor: * `mdc` and `mdio` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") objects (or integers) specifying the MDC and MDIO pins. * `phy_type` - Select the PHY device type. Supported devices are `PHY_LAN8710`, `PHY_LAN8720`, `PHY_IP101`, `PHY_RTL8201`, `PHY_DP83848`, `PHY_KSZ8041` and `PHY_KSZ8081`. These values are all constants defined in the `network` module. * `phy_addr` - The address number of the PHY device. Must be an integer in the range 0x00 to 0x1f, inclusive. Common values are `0` and `1`. All of the above keyword arguments must be present to configure the interface. Optional keyword arguments: * `reset` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying the PHY reset pin. * `power` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying a pin which switches the power of the PHY device. * `ref_clk` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying the pin used for the EMAC `ref_clk` signal. If not specified, the board default is used (typically GPIO 0, but may be different if a particular board has Ethernet.) * `ref_clk_mode` - Defines whether the EMAC `ref_clk` pin of the ESP32 should be an input or an output. Suitable values are `machine.Pin.IN` and `machine.Pin.OUT`. If not specified, the board default is used (typically input, but may be different if a particular board has Ethernet.) These are working configurations for LAN interfaces of some popular ESP32 boards: \# Olimex ESP32-GATEWAY: power controlled by Pin(5) \# Olimex ESP32 PoE and ESP32-PoE ISO: power controlled by Pin(12) lan \= network.LAN(mdc\=machine.Pin(23), mdio\=machine.Pin(18), power\=machine.Pin(5), phy\_type\=network.PHY\_LAN8720, phy\_addr\=0, ref\_clk\=machine.Pin(17), ref\_clk\_mode\=machine.Pin.OUT) \# Wireless-Tag's WT32-ETH01 lan \= network.LAN(mdc\=machine.Pin(23), mdio\=machine.Pin(18), phy\_type\=network.PHY\_LAN8720, phy\_addr\=1, power\=None) \# Wireless-Tag's WT32-ETH01 v1.4 lan \= network.LAN(mdc\=machine.Pin(23), mdio\=machine.Pin(18), phy\_type\=network.PHY\_LAN8720, phy\_addr\=1, power\=machine.Pin(16)) \# Espressif ESP32-Ethernet-Kit\_A\_V1.2 lan \= network.LAN(id\=0, mdc\=Pin(23), mdio\=Pin(18), power\=Pin(5), phy\_type\=network.PHY\_IP101, phy\_addr\=1) #### SPI Ethernet Interface[¶](#spi-ethernet-interface "Link to this heading") All ESP32 SoCs support external SPI Ethernet interface chips. These are Ethernet interfaces that connect via a SPI bus, rather than an Ethernet RMII interface. Note The only exception is the ESP32 `d2wd` variant, where this feature is disabled to save code size. SPI Ethernet uses the same [`network.LAN`](../library/network.LAN.html#network.LAN "network.LAN") constructor, with a different set of keyword arguments: import machine, network spi \= machine.SPI(1, sck\=SCK\_PIN, mosi\=MOSI\_PIN, miso\=MISO\_PIN) lan \= network.LAN(spi\=spi, cs\=CS\_PIN, ...) \# Set the pin and mode configuration lan.active(True) \# activate the interface lan.ipconfig('addr4') \# get the interface's IPv4 addresses Required keyword arguments for the constructor: * `spi` - Should be a [`machine.SPI`](../library/machine.SPI.html#machine.SPI "machine.SPI") object configured for this connection. Note that any clock speed configured on the SPI object is ignored, the SPI Ethernet clock speed is configured at compile time. * `cs` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying the CS pin connected to the interface. * `int` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying the INT pin connected to the interface. * `phy_type` - Select the SPI Ethernet interface type. Supported devices are `PHY_KSZ8851SNL`, `PHY_DM9051`, `PHY_W5500`. These values are all constants defined in the `network` module. * `phy_addr` - The address number of the PHY device. Must be an integer in the range 0x00 to 0x1f, inclusive. This is usually `0` for SPI Ethernet devices. All of the above keyword arguments must be present to configure the interface. Optional keyword arguments for the constructor: * `reset` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying the SPI Ethernet interface reset pin. * `power` - [`machine.Pin`](../library/machine.Pin.html#machine.Pin "machine.Pin") object (or integer) specifying a pin which switches the power of the SPI Ethernet interface. Here is a sample configuration for a WIZNet W5500 chip connected to pins on an ESP32-S3 development board: import machine, network from machine import Pin, SPI spi \= SPI(1, sck\=Pin(12), mosi\=Pin(13), miso\=Pin(14)) lan \= network.LAN(spi\=spi, phy\_type\=network.PHY\_W5500, phy\_addr\=0, cs\=Pin(10), int\=Pin(11)) Note WIZnet W5500 Ethernet is also supported on some other MicroPython ports, but using a [different software interface](../library/network.WIZNET5K.html#network-wiznet5k) . Delay and timing[¶](#delay-and-timing "Link to this heading") -------------------------------------------------------------- Use the [`time`](../library/time.html#module-time "time: time related functions") module: import time time.sleep(1) \# sleep for 1 second time.sleep\_ms(500) \# sleep for 500 milliseconds time.sleep\_us(10) \# sleep for 10 microseconds start \= time.ticks\_ms() \# get millisecond counter delta \= time.ticks\_diff(time.ticks\_ms(), start) \# compute time difference Timers[¶](#timers "Link to this heading") ------------------------------------------ The ESP32 port has four hardware timers. Use the [machine.Timer](../library/machine.Timer.html#machine-timer) class with a timer ID from 0 to 3 (inclusive): from machine import Timer tim0 \= Timer(0) tim0.init(period\=5000, mode\=Timer.ONE\_SHOT, callback\=lambda t:print(0)) tim1 \= Timer(1) tim1.init(period\=2000, mode\=Timer.PERIODIC, callback\=lambda t:print(1)) The period is in milliseconds. Virtual timers are not currently supported on this port. Pins and GPIO[¶](#pins-and-gpio "Link to this heading") -------------------------------------------------------- Use the [machine.Pin](../library/machine.Pin.html#machine-pin) class: from machine import Pin p0 \= Pin(0, Pin.OUT) \# create output pin on GPIO0 p0.on() \# set pin to "on" (high) level p0.off() \# set pin to "off" (low) level p0.value(1) \# set pin to on/high p2 \= Pin(2, Pin.IN) \# create input pin on GPIO2 print(p2.value()) \# get value, 0 or 1 p4 \= Pin(4, Pin.IN, Pin.PULL\_UP) \# enable internal pull-up resistor p5 \= Pin(5, Pin.OUT, value\=1) \# set pin high on creation p6 \= Pin(6, Pin.OUT, drive\=Pin.DRIVE\_3) \# set maximum drive strength Available Pins are from the following ranges (inclusive): 0-19, 21-23, 25-27, 32-39. These correspond to the actual GPIO pin numbers of ESP32 chip. Note that many end-user boards use their own adhoc pin numbering (marked e.g. D0, D1, …). For mapping between board logical pins and physical chip pins consult your board documentation. Four drive strengths are supported, using the `drive` keyword argument to the `Pin()` constructor or `Pin.init()` method, with different corresponding safe maximum source/sink currents and approximate internal driver resistances: > * `Pin.DRIVE_0`: 5mA / 130 ohm > > * `Pin.DRIVE_1`: 10mA / 60 ohm > > * `Pin.DRIVE_2`: 20mA / 30 ohm (default strength if not configured) > > * `Pin.DRIVE_3`: 40mA / 15 ohm > The `hold=` keyword argument to `Pin()` and `Pin.init()` will enable the ESP32 “pad hold” feature. When set to `True`, the pin configuration (direction, pull resistors and output value) will be held and any further changes (including changing the output level) will not be applied. Setting `hold=False` will immediately apply any outstanding pin configuration changes and release the pin. Using `hold=True` while a pin is already held will apply any configuration changes and then immediately reapply the hold. Notes: * Pins 1 and 3 are REPL UART TX and RX respectively * Pins 6, 7, 8, 11, 16, and 17 are used for connecting the embedded flash, and are not recommended for other uses * Pins 34-39 are input only, and also do not have internal pull-up resistors * See [Deep-sleep mode](#deep-sleep-mode) for a discussion of pin behaviour during sleep There’s a higher-level abstraction [machine.Signal](../library/machine.Signal.html#machine-signal) which can be used to invert a pin. Useful for illuminating active-low LEDs using `on()` or `value(1)`. UART (serial bus)[¶](#uart-serial-bus "Link to this heading") -------------------------------------------------------------- See [machine.UART](../library/machine.UART.html#machine-uart) . from machine import UART uart1 \= UART(1, baudrate\=9600, tx\=33, rx\=32) uart1.write('hello') \# write 5 bytes uart1.read(5) \# read up to 5 bytes The ESP32 has three hardware UARTs: UART0, UART1 and UART2. They each have default GPIO assigned to them, however depending on your ESP32 variant and board, these pins may conflict with embedded flash, onboard PSRAM or peripherals. Any GPIO can be used for hardware UARTs using the GPIO matrix, except for input-only pins 34-39 that can be used as `rx`. To avoid conflicts simply provide `tx` and `rx` pins when constructing. The default pins listed below. | | UART0 | UART1 | UART2 | | --- | --- | --- | --- | | tx | 1 | 10 | 17 | | rx | 3 | 9 | 16 | PWM (pulse width modulation)[¶](#pwm-pulse-width-modulation "Link to this heading") ------------------------------------------------------------------------------------ PWM can be enabled on all output-enabled pins. The base frequency can range from 1Hz to 40MHz but there is a tradeoff; as the base frequency _increases_ the duty resolution _decreases_. See [LED Control](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/ledc.html) for more details. Use the [machine.PWM](../library/machine.PWM.html#machine-pwm) class: from machine import Pin, PWM pwm0 \= PWM(Pin(0), freq\=5000, duty\_u16\=32768) \# create PWM object from a pin freq \= pwm0.freq() \# get current frequency pwm0.freq(1000) \# set PWM frequency from 1Hz to 40MHz duty \= pwm0.duty() \# get current duty cycle, range 0-1023 (default 512, 50%) pwm0.duty(256) \# set duty cycle from 0 to 1023 as a ratio duty/1023, (now 25%) duty\_u16 \= pwm0.duty\_u16() \# get current duty cycle, range 0-65535 pwm0.duty\_u16(2\*\*16\*3//4) \# set duty cycle from 0 to 65535 as a ratio duty\_u16/65535, (now 75%) duty\_ns \= pwm0.duty\_ns() \# get current pulse width in ns pwm0.duty\_ns(250\_000) \# set pulse width in nanoseconds from 0 to 1\_000\_000\_000/freq, (now 25%) pwm0.deinit() \# turn off PWM on the pin pwm2 \= PWM(Pin(2), freq\=20000, duty\=512) \# create and configure in one go print(pwm2) \# view PWM settings ESP chips have different hardware peripherals: | | | | | | --- | --- | --- | --- | | Hardware specification | ESP32 | ESP32-S2 | ESP32-C3 | | Number of groups (speed modes) | 2 | 1 | 1 | | Number of timers per group | 4 | 4 | 4 | | Number of channels per group | 8 | 8 | 6 | | Different PWM frequencies (groups \* timers) | 8 | 4 | 4 | | Total PWM channels (Pins, duties) (groups \* channels) | 16 | 8 | 6 | A maximum number of PWM channels (Pins) are available on the ESP32 - 16 channels, but only 8 different PWM frequencies are available, the remaining 8 channels must have the same frequency. On the other hand, 16 independent PWM duty cycles are possible at the same frequency. See more examples in the [Pulse Width Modulation](tutorial/pwm.html#esp32-pwm) tutorial. DAC (digital to analog conversion)[¶](#dac-digital-to-analog-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ On the ESP32, DAC functionality is available on pins 25, 26. On the ESP32S2, DAC functionality is available on pins 17, 18. Use the DAC: from machine import DAC, Pin dac \= DAC(Pin(25)) \# create an DAC object acting on a pin dac.write(128) \# set a raw analog value in the range 0-255, 50% now ADC (analog to digital conversion)[¶](#adc-analog-to-digital-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ On the ESP32, ADC functionality is available on pins 32-39 (ADC block 1) and pins 0, 2, 4, 12-15 and 25-27 (ADC block 2). Use the [machine.ADC](../library/machine.ADC.html#machine-adc) class: 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 ADC block 2 is also used by WiFi and so attempting to read analog values from block 2 pins when WiFi is active will raise an exception. The internal ADC reference voltage is typically 1.1V, but varies slightly from package to package. The ADC is less linear close to the reference voltage (particularly at higher attenuations) and has a minimum measurement voltage around 100mV, voltages at or below this will read as 0. To read voltages accurately, it is recommended to use the `read_uv()` method (see below). ESP32-specific ADC class method reference: _class_ ADC(_pin_, _\*_, _atten_)[¶](#ADC "Link to this definition") Return the ADC object for the specified pin. ESP32 does not support different timings for ADC sampling and so the `sample_ns` keyword argument is not supported. To read voltages above the reference voltage, apply input attenuation with the `atten` keyword argument. Valid values (and approximate linear measurement ranges) are: > * `ADC.ATTN_0DB`: No attenuation (100mV - 950mV) > > * `ADC.ATTN_2_5DB`: 2.5dB attenuation (100mV - 1250mV) > > * `ADC.ATTN_6DB`: 6dB attenuation (150mV - 1750mV) > > * `ADC.ATTN_11DB`: 11dB attenuation (150mV - 2450mV) > Warning Note that the absolute maximum voltage rating for input pins is 3.6V. Going near to this boundary risks damage to the IC! ADC.read\_uv()[¶](#ADC.read_uv "Link to this definition") This method uses the known characteristics of the ADC and per-package eFuse values - set during manufacture - to return a calibrated input voltage (before attenuation) in microvolts. The returned value has only millivolt resolution (i.e., will always be a multiple of 1000 microvolts). The calibration is only valid across the linear range of the ADC. In particular, an input tied to ground will read as a value above 0 microvolts. Within the linear range, however, more accurate and consistent results will be obtained than using [`read_u16()`](../samd/quickref.html#read_u16 "read_u16") and scaling the result with a constant. The ESP32 port also supports the [machine.ADC](../library/machine.ADCBlock.html#machine-adcblock) API: _class_ ADCBlock(_id_, _\*_, _bits_)[¶](#ADCBlock "Link to this definition") Return the ADC block object with the given `id` (1 or 2) and initialize it to the specified resolution (9 to 12-bits depending on the ESP32 series) or the highest supported resolution if not specified. ADCBlock.connect(_pin_)[¶](#ADCBlock.connect "Link to this definition") ADCBlock.connect(_channel_) ADCBlock.connect(_channel_, _pin_) Return the `ADC` object for the specified ADC pin or channel number. Arbitrary connection of ADC channels to GPIO is not supported and so specifying a pin that is not connected to this block, or specifying a mismatched channel and pin, will raise an exception. Legacy methods: ADC.read()[¶](#ADC.read "Link to this definition") This method returns the raw ADC value ranged according to the resolution of the block, e.g., 0-4095 for 12-bit resolution. ADC.atten(_atten_)[¶](#ADC.atten "Link to this definition") Equivalent to `ADC.init(atten=atten)`. ADC.width(_bits_)[¶](#ADC.width "Link to this definition") Equivalent to `ADC.block().init(bits=bits)`. For compatibility, the `ADC` object also provides constants matching the supported ADC resolutions: > * `ADC.WIDTH_9BIT` = 9 > > * `ADC.WIDTH_10BIT` = 10 > > * `ADC.WIDTH_11BIT` = 11 > > * `ADC.WIDTH_12BIT` = 12 > Software SPI bus[¶](#software-spi-bus "Link to this heading") -------------------------------------------------------------- Software SPI (using bit-banging) works on all pins, and is accessed via the [machine.SoftSPI](../library/machine.SPI.html#machine-softspi) class: from machine import Pin, SoftSPI \# construct a SoftSPI bus on the given pins \# polarity is the idle state of SCK \# phase=0 means sample on the first edge of SCK, phase=1 means the second spi \= SoftSPI(baudrate\=100000, polarity\=1, phase\=0, sck\=Pin(0), mosi\=Pin(2), miso\=Pin(4)) spi.init(baudrate\=200000) \# set the baudrate spi.read(10) \# read 10 bytes on MISO spi.read(10, 0xff) \# read 10 bytes while outputting 0xff on MOSI buf \= bytearray(50) \# create a buffer spi.readinto(buf) \# read into the given buffer (reads 50 bytes in this case) spi.readinto(buf, 0xff) \# read into the given buffer and output 0xff on MOSI spi.write(b'12345') \# write 5 bytes on MOSI buf \= bytearray(4) \# create a buffer spi.write\_readinto(b'1234', buf) \# write to MOSI and read from MISO into the buffer spi.write\_readinto(buf, buf) \# write buf to MOSI and read MISO back into buf Warning Currently _all_ of `sck`, `mosi` and `miso` _must_ be specified when initialising Software SPI. Hardware SPI bus[¶](#hardware-spi-bus "Link to this heading") -------------------------------------------------------------- There are two hardware SPI channels that allow faster transmission rates (up to 80Mhz). These may be used on any IO pins that support the required direction and are otherwise unused (see [Pins and GPIO](#pins-and-gpio) ) but if they are not configured to their default pins then they need to pass through an extra layer of GPIO multiplexing, which can impact their reliability at high speeds. Hardware SPI channels are limited to 40MHz when used on pins other than the default ones listed below. | | HSPI (id=1) | VSPI (id=2) | | --- | --- | --- | | sck | 14 | 18 | | mosi | 13 | 23 | | miso | 12 | 19 | Hardware SPI is accessed via the [machine.SPI](../library/machine.SPI.html#machine-spi) class and has the same methods as software SPI above: from machine import Pin, SPI hspi \= SPI(1, 10000000) hspi \= SPI(1, 10000000, sck\=Pin(14), mosi\=Pin(13), miso\=Pin(12)) vspi \= SPI(2, baudrate\=80000000, polarity\=0, phase\=0, bits\=8, firstbit\=0, sck\=Pin(18), mosi\=Pin(23), miso\=Pin(19)) Software I2C bus[¶](#software-i2c-bus "Link to this heading") -------------------------------------------------------------- Software I2C (using bit-banging) works on all output-capable pins, and is accessed via the [machine.SoftI2C](../library/machine.I2C.html#machine-softi2c) class: from machine import Pin, SoftI2C i2c \= SoftI2C(scl\=Pin(5), sda\=Pin(4), freq\=100000) i2c.scan() \# scan for devices i2c.readfrom(0x3a, 4) \# read 4 bytes from device with address 0x3a i2c.writeto(0x3a, '12') \# write '12' to device with address 0x3a buf \= bytearray(10) \# create a buffer with 10 bytes i2c.writeto(0x3a, buf) \# write the given buffer to the peripheral Hardware I2C bus[¶](#hardware-i2c-bus "Link to this heading") -------------------------------------------------------------- There are two hardware I2C peripherals with identifiers 0 and 1. Any available output-capable pins can be used for SCL and SDA but the defaults are given below. | | I2C(0) | I2C(1) | | --- | --- | --- | | scl | 18 | 25 | | sda | 19 | 26 | The driver is accessed via the [machine.I2C](../library/machine.I2C.html#machine-i2c) class and has the same methods as software I2C above: from machine import Pin, I2C i2c \= I2C(0) i2c \= I2C(1, scl\=Pin(5), sda\=Pin(4), freq\=400000) I2S bus[¶](#i2s-bus "Link to this heading") -------------------------------------------- See [machine.I2S](../library/machine.I2S.html#machine-i2s) . from machine import I2S, Pin i2s \= I2S(0, sck\=Pin(13), ws\=Pin(14), sd\=Pin(34), mode\=I2S.TX, bits\=16, format\=I2S.STEREO, rate\=44100, ibuf\=40000) \# create I2S object i2s.write(buf) \# write buffer of audio samples to I2S device i2s \= I2S(1, sck\=Pin(33), ws\=Pin(25), sd\=Pin(32), mode\=I2S.RX, bits\=16, format\=I2S.MONO, rate\=22050, ibuf\=40000) \# create I2S object i2s.readinto(buf) \# fill buffer with audio samples from I2S device 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. ESP32 has two I2S buses with id=0 and id=1 Real time clock (RTC)[¶](#real-time-clock-rtc "Link to this heading") ---------------------------------------------------------------------- See [machine.RTC](../library/machine.RTC.html#machine-rtc) from machine import RTC rtc \= RTC() rtc.datetime((2017, 8, 23, 0, 1, 12, 48, 0)) \# set a specific date and \# time, eg. 2017/8/23 1:12:48 \# the day-of-week value is ignored rtc.datetime() \# get date and time WDT (Watchdog timer)[¶](#wdt-watchdog-timer "Link to this heading") -------------------------------------------------------------------- See [machine.WDT](../library/machine.WDT.html#machine-wdt) . from machine import WDT \# enable the WDT with a timeout of 5s (1s is the minimum) wdt \= WDT(timeout\=5000) wdt.feed() Deep-sleep mode[¶](#deep-sleep-mode "Link to this heading") ------------------------------------------------------------ The following code can be used to sleep, wake and check the reset cause: import machine \# check if the device woke from a deep sleep if machine.reset\_cause() \== machine.DEEPSLEEP\_RESET: print('woke from a deep sleep') \# put the device to sleep for 10 seconds machine.deepsleep(10000) Notes: * Calling `deepsleep()` without an argument will put the device to sleep indefinitely * A software reset does not change the reset cause Some ESP32 pins (0, 2, 4, 12-15, 25-27, 32-39) are connected to the RTC during deep-sleep and can be used to wake the device with the `wake_on_` functions in the [`esp32`](../library/esp32.html#module-esp32 "esp32: functionality specific to the ESP32") module. The output-capable RTC pins (all except 34-39) will also retain their pull-up or pull-down resistor configuration when entering deep-sleep. If the pull resistors are not actively required during deep-sleep and are likely to cause current leakage (for example a pull-up resistor is connected to ground through a switch), then they should be disabled to save power before entering deep-sleep mode: from machine import Pin, deepsleep \# configure input RTC pin with pull-up on boot pin \= Pin(2, Pin.IN, Pin.PULL\_UP) \# disable pull-up and put the device to sleep for 10 seconds pin.init(pull\=None) machine.deepsleep(10000) Output-configured RTC pins will also retain their output direction and level in deep-sleep if pad hold is enabled with the `hold=True` argument to `Pin.init()`. Non-RTC GPIO pins will be disconnected by default on entering deep-sleep. Configuration of non-RTC pins - including output level - can be retained by enabling pad hold on the pin and enabling GPIO pad hold during deep-sleep: from machine import Pin, deepsleep import esp32 opin \= Pin(19, Pin.OUT, value\=1, hold\=True) # hold output level ipin \= Pin(21, Pin.IN, Pin.PULL\_UP, hold\=True) \# hold pull-up \# enable pad hold in deep-sleep for non-RTC GPIO esp32.gpio\_deep\_sleep\_hold(True) \# put the device to sleep for 10 seconds deepsleep(10000) The pin configuration - including the pad hold - will be retained on wake from sleep. See [Pins and GPIO](#pins-and-gpio) above for a further discussion of pad holding. SD card[¶](#sd-card "Link to this heading") -------------------------------------------- See [machine.SDCard](../library/machine.SDCard.html#machine-sdcard) . import machine, os, vfs \# On original ESP32, slot 2 uses pins sck=18, cs=5, miso=19, mosi=23 sd \= machine.SDCard(slot\=2) vfs.mount(sd, '/sd') \# mount os.listdir('/sd') \# list directory contents vfs.umount('/sd') \# eject RMT[¶](#rmt "Link to this heading") ------------------------------------ The RMT is ESP32-specific and allows generation of accurate digital pulses with 12.5ns resolution. See [esp32.RMT](../library/esp32.html#esp32-rmt) for details. Usage is: 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) \# 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 OneWire driver[¶](#onewire-driver "Link to this heading") ---------------------------------------------------------- The OneWire driver is implemented in software and works on all pins: from machine import Pin import onewire ow \= onewire.OneWire(Pin(12)) \# create a OneWire bus on GPIO12 ow.scan() \# return a list of devices on the bus ow.reset() \# reset the bus ow.readbyte() \# read a byte ow.writebyte(0x12) \# write a byte on the bus ow.write('123') \# write bytes on the bus ow.select\_rom(b'12345678') \# select a specific device by its ROM code There is a specific driver for DS18S20 and DS18B20 devices: import time, ds18x20 ds \= ds18x20.DS18X20(ow) roms \= ds.scan() ds.convert\_temp() time.sleep\_ms(750) for rom in roms: print(ds.read\_temp(rom)) Be sure to put a 4.7k pull-up resistor on the data line. Note that the `convert_temp()` method must be called each time you want to sample the temperature. NeoPixel and APA106 driver[¶](#neopixel-and-apa106-driver "Link to this heading") ---------------------------------------------------------------------------------- Use the `neopixel` and `apa106` modules: from machine import Pin from neopixel import NeoPixel pin \= Pin(0, Pin.OUT) \# set GPIO0 to output to drive NeoPixels np \= NeoPixel(pin, 8) \# create NeoPixel driver on GPIO0 for 8 pixels np\[0\] \= (255, 255, 255) \# set the first pixel to white np.write() \# write data to all pixels r, g, b \= np\[0\] \# get first pixel colour The APA106 driver extends NeoPixel, but internally uses a different colour order: from apa106 import APA106 ap \= APA106(pin, 8) r, g, b \= ap\[0\] Warning By default `NeoPixel` is configured to control the more popular _800kHz_ units. It is possible to use alternative timing to control other (typically 400kHz) devices by passing `timing=0` when constructing the `NeoPixel` object. For low-level driving of a NeoPixel see [`machine.bitstream`](../library/machine.html#machine.bitstream "machine.bitstream") . This low-level driver uses an RMT channel by default. To configure this see [`RMT.bitstream_channel`](../library/esp32.html#esp32.RMT.bitstream_channel "esp32.RMT.bitstream_channel") . APA102 (DotStar) uses a different driver as it has an additional clock pin. Capacitive touch[¶](#capacitive-touch "Link to this heading") -------------------------------------------------------------- ESP32, ESP32-S2 and ESP32-S3 support capacitive touch via the `TouchPad` class in the `machine` module: from machine import TouchPad, Pin t \= TouchPad(Pin(14)) t.read() \# Returns a smaller number when touched `TouchPad.read` returns a value proportional to the capacitance between the pin and the board’s Ground connection. On ESP32 the number becomes smaller when the pin (or connected touch pad) is touched, on ESP32-S2 and ESP32-S3 the number becomes larger when the pin is touched. In all cases, a touch causes a significant change in the return value. Note the returned values are _relative_ and can vary depending on the board and surrounding environment so some calibration (i.e. comparison to a baseline or rolling average) may be required. | | | | --- | --- | | Chip | Touch-enabled pins | | ESP32 | 0, 2, 4, 12, 13, 14, 15, 27, 32, 33 | | ESP32-S2 | 1 to 14 inclusive | | ESP32-S3 | 1 to 14 inclusive | Trying to assign to any other pins will result in a `ValueError`. Note that TouchPads can be used to wake an ESP32 from sleep: import machine from machine import TouchPad, Pin import esp32 t \= TouchPad(Pin(14)) t.config(500) \# configure the threshold at which the pin is considered touched esp32.wake\_on\_touch(True) machine.lightsleep() \# put the MCU to sleep until a touchpad is touched For more details on touchpads refer to [Espressif Touch Sensor](https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/touch_pad.html) . DHT driver[¶](#dht-driver "Link to this heading") -------------------------------------------------- The DHT driver is implemented in software and works on all pins: import dht import machine d \= dht.DHT11(machine.Pin(4)) d.measure() d.temperature() \# eg. 23 (°C) d.humidity() \# eg. 41 (% RH) d \= dht.DHT22(machine.Pin(4)) d.measure() d.temperature() \# eg. 23.6 (°C) d.humidity() \# eg. 41.3 (% RH) WebREPL (web browser interactive prompt)[¶](#webrepl-web-browser-interactive-prompt "Link to this heading") ------------------------------------------------------------------------------------------------------------ WebREPL (REPL over WebSockets, accessible via a web browser) is an experimental feature available in ESP32 port. Download web client from [https://github.com/micropython/webrepl](https://github.com/micropython/webrepl) (hosted version available at [http://micropython.org/webrepl](http://micropython.org/webrepl) ), and configure it by executing: import webrepl\_setup and following on-screen instructions. After reboot, it will be available for connection. If you disabled automatic start-up on boot, you may run configured daemon on demand using: import webrepl webrepl.start() \# or, start with a specific password webrepl.start(password\='mypass') The WebREPL daemon listens on all active interfaces, which can be STA or AP. This allows you to connect to the ESP32 via a router (the STA interface) or directly when connected to its access point. In addition to terminal/command prompt access, WebREPL also has provision for file transfer (both upload and download). The web client has buttons for the corresponding functions, or you can use the command-line client `webrepl_cli.py` from the repository above. See the MicroPython forum for other community-supported alternatives to transfer files to an ESP32 board. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # cryptolib – cryptographic ciphers — MicroPython latest documentation * [](../index.html) * [MicroPython libraries](index.html) * `cryptolib` – cryptographic ciphers * [View page source](../_sources/library/cryptolib.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. [`cryptolib`](#module-cryptolib "cryptolib: cryptographic ciphers") – cryptographic ciphers[¶](#module-cryptolib "Link to this heading") ========================================================================================================================================== Classes[¶](#classes "Link to this heading") -------------------------------------------- _class_ cryptolib.aes[¶](#cryptolib.aes "Link to this definition") _classmethod_ \_\_init\_\_(_key_, _mode_\[, _IV_\])[¶](#cryptolib.aes.__init__ "Link to this definition") 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. > > * For Counter mode, _IV_ is the initial value for the counter. > encrypt(_in\_buf_\[, _out\_buf_\])[¶](#cryptolib.aes.encrypt "Link to this definition") Encrypt _in\_buf_. If no _out\_buf_ is given result is returned as a newly allocated [`bytes`](builtins.html#bytes "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_\])[¶](#cryptolib.aes.decrypt "Link to this definition") Like [`encrypt()`](#cryptolib.aes.encrypt "cryptolib.aes.encrypt") , but for decryption. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the RP2 — MicroPython latest documentation * [](../index.html) * Quick reference for the RP2 * [View page source](../_sources/rp2/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the RP2[¶](#quick-reference-for-the-rp2 "Link to this heading") ==================================================================================== [![Raspberry Pi Pico](../_images/pico_pinout.png)](../_images/pico_pinout.png) The Raspberry Pi Pico Development Board (image attribution: Raspberry Pi Foundation). Below is a quick reference for Raspberry Pi RP2xxx boards. If it is your first time working with this board it may be useful to get an overview of the microcontroller: * [General information about the RP2xxx port](general.html) * [Getting started with MicroPython on the RP2xxx](tutorial/intro.html) Installing MicroPython[¶](#installing-micropython "Link to this heading") -------------------------------------------------------------------------- See the corresponding section of tutorial: [Getting started with MicroPython on the RP2xxx](tutorial/intro.html#rp2-intro) . It also includes a troubleshooting subsection. General board control[¶](#general-board-control "Link to this heading") ------------------------------------------------------------------------ The MicroPython REPL is accessed via the USB serial port. Tab-completion is useful to find out what methods an object has. Paste mode (ctrl-E) is useful to paste a large slab of Python code into the REPL. The [`machine`](../library/machine.html#module-machine "machine: functions related to the hardware") module: machine.freq() allows to change the MCU frequency and control the peripheral frequency for UART and SPI. Usage: machine.freq(MCU\_frequency\[, peripheral\_frequency\=48\_000\_000\]) The MCU frequency can be set in a range from less than 48 MHz to about 250MHz. The default at boot time is 125 MHz. The peripheral frequency must be either 48 MHz or identical to the MCU frequency, with 48 MHz as the default. If the peripheral frequency is changed, any already existing instance of UART and SPI will change it’s baud rate and may have to be re-configured: import machine machine.freq() \# get the current frequency of the CPU machine.freq(240000000) \# set the CPU frequency to 240 MHz and keep \# the UART frequency at 48MHz machine.freq(125000000, 125000000) \# set the CPU and UART frequency to 125 MHz The [`rp2`](../library/rp2.html#module-rp2 "rp2: functionality specific to the RP2") module: import rp2 Networking[¶](#networking "Link to this heading") -------------------------------------------------- ### WLAN[¶](#wlan "Link to this heading") Note This section applies only to devices that include WiFi support, such as the [Pico W](https://www.raspberrypi.com/documentation/microcontrollers/pico-series.html#picow-technical-specification) and [Pico 2 W](https://www.raspberrypi.com/documentation/microcontrollers/pico-series.html#pico2w-technical-specification) . The [`network.WLAN`](../library/network.WLAN.html#network.WLAN "network.WLAN") class in the [`network`](../library/network.html#module-network "network: network configuration") module: import network wlan \= network.WLAN() \# create station interface (the default, see below for an access point interface) wlan.active(True) \# activate the interface wlan.scan() \# scan for access points wlan.isconnected() \# check if the station is connected to an AP wlan.connect('ssid', 'key') \# connect to an AP wlan.config('mac') \# get the interface's MAC address wlan.ipconfig('addr4') \# get the interface's IPv4 addresses ap \= network.WLAN(network.WLAN.IF\_AP) \# create access-point interface ap.config(ssid\='RP2-AP') \# set the SSID of the access point ap.config(max\_clients\=10) \# set how many clients can connect to the network ap.active(True) \# activate the interface A useful function for connecting to your local WiFi network is: def do\_connect(): import machine, network wlan \= network.WLAN() wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect('ssid', 'key') while not wlan.isconnected(): machine.idle() print('network config:', wlan.ipconfig('addr4')) Once the network is established the [`socket`](../library/socket.html#module-socket "socket: socket module") module can be used to create and use TCP/UDP sockets as usual, and the `requests` module for convenient HTTP requests. After a call to `wlan.connect()`, the device will by default retry to connect **forever**, even when the authentication failed or no AP is in range. `wlan.status()` will return `network.STAT_CONNECTING` in this state until a connection succeeds or the interface gets disabled. Delay and timing[¶](#delay-and-timing "Link to this heading") -------------------------------------------------------------- Use the [`time`](../library/time.html#module-time "time: time related functions") module: import time time.sleep(1) \# sleep for 1 second time.sleep\_ms(500) \# sleep for 500 milliseconds time.sleep\_us(10) \# sleep for 10 microseconds start \= time.ticks\_ms() \# get millisecond counter delta \= time.ticks\_diff(time.ticks\_ms(), start) \# compute time difference Timers[¶](#timers "Link to this heading") ------------------------------------------ RP2040’s system timer peripheral provides a global microsecond timebase and generates interrupts for it. The software timer is available currently, and there are unlimited number of them (memory permitting). There is no need to specify the timer id (id=-1 is supported at the moment) as it will default to this. Use the [`machine.Timer`](../library/machine.Timer.html#machine.Timer "machine.Timer") class: from machine import Timer tim \= Timer(period\=5000, mode\=Timer.ONE\_SHOT, callback\=lambda t:print(1)) tim.init(period\=2000, mode\=Timer.PERIODIC, callback\=lambda t:print(2)) Pins and GPIO[¶](#pins-and-gpio "Link to this heading") -------------------------------------------------------- Use the [machine.Pin](../library/machine.Pin.html#machine-pin) class: from machine import Pin p0 \= Pin(0, Pin.OUT) \# create output pin on GPIO0 p0.on() \# set pin to "on" (high) level p0.off() \# set pin to "off" (low) level p0.value(1) \# set pin to on/high p2 \= Pin(2, Pin.IN) \# create input pin on GPIO2 print(p2.value()) \# get value, 0 or 1 p4 \= Pin(4, Pin.IN, Pin.PULL\_UP) \# enable internal pull-up resistor p5 \= Pin(5, Pin.OUT, value\=1) \# set pin high on creation Programmable IO (PIO)[¶](#programmable-io-pio "Link to this heading") ---------------------------------------------------------------------- PIO is useful to build low-level IO interfaces from scratch. See the [`rp2`](../library/rp2.html#module-rp2 "rp2: functionality specific to the RP2") module for detailed explanation of the assembly instructions. Example using PIO to blink an LED at 1Hz: from machine import Pin import rp2 @rp2.asm\_pio(set\_init\=rp2.PIO.OUT\_LOW) def blink\_1hz(): \# Cycles: 1 + 7 + 32 \* (30 + 1) = 1000 set(pins, 1) set(x, 31) \[6\] label("delay\_high") nop() \[29\] jmp(x\_dec, "delay\_high") \# Cycles: 1 + 7 + 32 \* (30 + 1) = 1000 set(pins, 0) set(x, 31) \[6\] label("delay\_low") nop() \[29\] jmp(x\_dec, "delay\_low") \# Create and start a StateMachine with blink\_1hz, outputting on Pin(25) sm \= rp2.StateMachine(0, blink\_1hz, freq\=2000, set\_base\=Pin(25)) sm.active(1) UART (serial bus)[¶](#uart-serial-bus "Link to this heading") -------------------------------------------------------------- There are two UARTs, UART0 and UART1. UART0 can be mapped to GPIO 0/1, 12/13 and 16/17, and UART1 to GPIO 4/5 and 8/9. See [machine.UART](../library/machine.UART.html#machine-uart) . from machine import UART, Pin uart1 \= UART(1, baudrate\=9600, tx\=Pin(4), rx\=Pin(5)) uart1.write('hello') \# write 5 bytes uart1.read(5) \# read up to 5 bytes Note REPL over UART is disabled by default. You can see the [Getting started with MicroPython on the RP2xxx](tutorial/intro.html#rp2-intro) for details on how to enable REPL over UART. PWM (pulse width modulation)[¶](#pwm-pulse-width-modulation "Link to this heading") ------------------------------------------------------------------------------------ There are 8 independent PWM generators called slices, which each have two channels making it 16 PWM channels in total which can be clocked from 8Hz to 62.5Mhz at a machine.freq() of 125Mhz. The two channels of a slice run at the same frequency, but can have a different duty rate. The two channels are usually assigned to adjacent GPIO pin pairs with even/odd numbers. So GPIO0 and GPIO1 are at slice 0, GPIO2 and GPIO3 are at slice 1, and so on. A certain channel can be assigned to different GPIO pins (see Pinout). For instance slice 0, channel A can be assigned to both GPIO0 and GPIO16. Use the `machine.PWM` class: from machine import Pin, PWM \# create PWM object from a pin and set the frequency of slice 0 \# and duty cycle for channel A pwm0 \= PWM(Pin(0), freq\=2000, duty\_u16\=32768) pwm0.freq() \# get the current frequency of slice 0 pwm0.freq(1000) \# set/change the frequency of slice 0 pwm0.duty\_u16() \# get the current duty cycle of channel A, range 0-65535 pwm0.duty\_u16(200) \# set the duty cycle of channel A, range 0-65535 pwm0.duty\_u16(0) \# stop the output at channel A print(pwm0) \# show the properties of the PWM object. pwm0.deinit() \# turn off PWM of slice 0, stopping channels A and B ADC (analog to digital conversion)[¶](#adc-analog-to-digital-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ RP2040 has five ADC channels in total, four of which are 12-bit SAR based ADCs: GP26, GP27, GP28 and GP29. The input signal for ADC0, ADC1, ADC2 and ADC3 can be connected with GP26, GP27, GP28, GP29 respectively (On Pico board, GP29 is connected to VSYS). The standard ADC range is 0-3.3V. The fifth channel is connected to the in-built temperature sensor and can be used for measuring the temperature. Use the [machine.ADC](../library/machine.ADC.html#machine-adc) class: from machine import ADC, Pin adc \= ADC(Pin(26)) \# create ADC object on ADC pin adc.read\_u16() \# read value, 0-65535 across voltage range 0.0v - 3.3v The argument of the constructor ADC specifies either a Pin by number, name of as Pin object, or a channel number in the range 0 - 3 or ADC.CORE\_TEMP for the internal temperature sensor. If a pin is specified, the pin is initialized in high-Z mode. If a channel number is used, the pin is not initialized and configuring is left to the user code. After hard reset, RP2040 pins operate in current sink mode at about 60µA. If the pin is not otherwise configured, that may lead to wrong ADC readings. Software SPI bus[¶](#software-spi-bus "Link to this heading") -------------------------------------------------------------- Software SPI (using bit-banging) works on all pins, and is accessed via the [machine.SoftSPI](../library/machine.SPI.html#machine-softspi) class: from machine import Pin, SoftSPI \# construct a SoftSPI bus on the given pins \# polarity is the idle state of SCK \# phase=0 means sample on the first edge of SCK, phase=1 means the second spi \= SoftSPI(baudrate\=100\_000, polarity\=1, phase\=0, sck\=Pin(0), mosi\=Pin(2), miso\=Pin(4)) spi.init(baudrate\=200000) \# set the baudrate spi.read(10) \# read 10 bytes on MISO spi.read(10, 0xff) \# read 10 bytes while outputting 0xff on MOSI buf \= bytearray(50) \# create a buffer spi.readinto(buf) \# read into the given buffer (reads 50 bytes in this case) spi.readinto(buf, 0xff) \# read into the given buffer and output 0xff on MOSI spi.write(b'12345') \# write 5 bytes on MOSI buf \= bytearray(4) \# create a buffer spi.write\_readinto(b'1234', buf) \# write to MOSI and read from MISO into the buffer spi.write\_readinto(buf, buf) \# write buf to MOSI and read MISO back into buf Warning Currently _all_ of `sck`, `mosi` and `miso` _must_ be specified when initialising Software SPI. Hardware SPI bus[¶](#hardware-spi-bus "Link to this heading") -------------------------------------------------------------- The RP2040 has 2 hardware SPI buses which is accessed via the [machine.SPI](../library/machine.SPI.html#machine-spi) class and has the same methods as software SPI above: from machine import Pin, SPI spi \= SPI(1, 10\_000\_000) \# Default assignment: sck=Pin(10), mosi=Pin(11), miso=Pin(8) spi \= SPI(1, 10\_000\_000, sck\=Pin(14), mosi\=Pin(15), miso\=Pin(12)) spi \= SPI(0, baudrate\=80\_000\_000, polarity\=0, phase\=0, bits\=8, sck\=Pin(6), mosi\=Pin(7), miso\=Pin(4)) Software I2C bus[¶](#software-i2c-bus "Link to this heading") -------------------------------------------------------------- Software I2C (using bit-banging) works on all output-capable pins, and is accessed via the [machine.SoftI2C](../library/machine.I2C.html#machine-softi2c) class: from machine import Pin, SoftI2C i2c \= SoftI2C(scl\=Pin(5), sda\=Pin(4), freq\=100\_000) i2c.scan() \# scan for devices i2c.readfrom(0x3a, 4) \# read 4 bytes from device with address 0x3a i2c.writeto(0x3a, '12') \# write '12' to device with address 0x3a buf \= bytearray(10) \# create a buffer with 10 bytes i2c.writeto(0x3a, buf) \# write the given buffer to the peripheral Hardware I2C bus[¶](#hardware-i2c-bus "Link to this heading") -------------------------------------------------------------- The driver is accessed via the [machine.I2C](../library/machine.I2C.html#machine-i2c) class and has the same methods as software I2C above: from machine import Pin, I2C i2c \= I2C(0) \# default assignment: scl=Pin(9), sda=Pin(8) i2c \= I2C(1, scl\=Pin(3), sda\=Pin(2), freq\=400\_000) I2S bus[¶](#i2s-bus "Link to this heading") -------------------------------------------- See [machine.I2S](../library/machine.I2S.html#machine-i2s) . from machine import I2S, Pin i2s \= I2S(0, sck\=Pin(16), ws\=Pin(17), sd\=Pin(18), mode\=I2S.TX, bits\=16, format\=I2S.STEREO, rate\=44100, ibuf\=40000) \# create I2S object i2s.write(buf) \# write buffer of audio samples to I2S device i2s \= I2S(1, sck\=Pin(0), ws\=Pin(1), sd\=Pin(2), mode\=I2S.RX, bits\=16, format\=I2S.MONO, rate\=22050, ibuf\=40000) \# create I2S object i2s.readinto(buf) \# fill buffer with audio samples from I2S device The `ws` pin number must be one greater than the `sck` pin number. 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. Two I2S buses are supported with id=0 and id=1. Real time clock (RTC)[¶](#real-time-clock-rtc "Link to this heading") ---------------------------------------------------------------------- See [machine.RTC](../library/machine.RTC.html#machine-rtc) from machine import RTC rtc \= RTC() rtc.datetime((2017, 8, 23, 0, 1, 12, 48, 0)) \# set a specific date and \# time, eg. 2017/8/23 1:12:48 \# the day-of-week value is ignored rtc.datetime() \# get date and time WDT (Watchdog timer)[¶](#wdt-watchdog-timer "Link to this heading") -------------------------------------------------------------------- The RP2040 has a watchdog which is a countdown timer that can restart parts of the chip if it reaches zero. See [machine.WDT](../library/machine.WDT.html#machine-wdt) . from machine import WDT \# enable the WDT with a timeout of 5s (1s is the minimum) wdt \= WDT(timeout\=5000) wdt.feed() The maximum value for timeout is 8388 ms. OneWire driver[¶](#onewire-driver "Link to this heading") ---------------------------------------------------------- The OneWire driver is implemented in software and works on all pins: from machine import Pin import onewire ow \= onewire.OneWire(Pin(12)) \# create a OneWire bus on GPIO12 ow.scan() \# return a list of devices on the bus ow.reset() \# reset the bus ow.readbyte() \# read a byte ow.writebyte(0x12) \# write a byte on the bus ow.write('123') \# write bytes on the bus ow.select\_rom(b'12345678') \# select a specific device by its ROM code There is a specific driver for DS18S20 and DS18B20 devices: import time, ds18x20 ds \= ds18x20.DS18X20(ow) roms \= ds.scan() ds.convert\_temp() time.sleep\_ms(750) for rom in roms: print(ds.read\_temp(rom)) Be sure to put a 4.7k pull-up resistor on the data line. Note that the `convert_temp()` method must be called each time you want to sample the temperature. NeoPixel and APA106 driver[¶](#neopixel-and-apa106-driver "Link to this heading") ---------------------------------------------------------------------------------- Use the `neopixel` and `apa106` modules: from machine import Pin from neopixel import NeoPixel pin \= Pin(0, Pin.OUT) \# set GPIO0 to output to drive NeoPixels np \= NeoPixel(pin, 8) \# create NeoPixel driver on GPIO0 for 8 pixels np\[0\] \= (255, 255, 255) \# set the first pixel to white np.write() \# write data to all pixels r, g, b \= np\[0\] \# get first pixel colour The APA106 driver extends NeoPixel, but internally uses a different colour order: from apa106 import APA106 ap \= APA106(pin, 8) r, g, b \= ap\[0\] APA102 (DotStar) uses a different driver as it has an additional clock pin. Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the WiPy — MicroPython latest documentation * [](../index.html) * Quick reference for the WiPy * [View page source](../_sources/wipy/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the WiPy[¶](#quick-reference-for-the-wipy "Link to this heading") ====================================================================================== [![WiPy pinout and alternate functions table](https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png)](https://raw.githubusercontent.com/wipy/wipy/master/docs/PinOUT.png) Below is a quick reference for CC3200/WiPy. If it is your first time working with this board please consider reading the following sections first: * [General information about the WiPy](general.html) * [WiPy tutorials and examples](tutorial/index.html) General board control (including sleep modes)[¶](#general-board-control-including-sleep-modes "Link to this heading") ---------------------------------------------------------------------------------------------------------------------- See the [`machine`](../library/machine.html#module-machine "machine: functions related to the hardware") module: import machine help(machine) \# display all members from the machine module machine.freq() \# get the CPU frequency machine.unique\_id() \# return the 6-byte unique id of the board (the WiPy's MAC address) machine.idle() \# average current decreases to (~12mA), any interrupts wake it up machine.lightsleep() \# everything except for WLAN is powered down (~950uA avg. current) \# wakes from Pin, RTC or WLAN machine.deepsleep() \# deepest sleep mode, MCU starts from reset. Wakes from Pin and RTC. Pins and GPIO[¶](#pins-and-gpio "Link to this heading") -------------------------------------------------------- See [machine.Pin](../library/machine.Pin.html#machine-pin) . from machine import Pin \# initialize GP2 in gpio mode (alt=0) and make it an output p\_out \= Pin('GP2', mode\=Pin.OUT) p\_out.value(1) p\_out.value(0) p\_out.toggle() p\_out(True) \# make GP1 an input with the pull-up enabled p\_in \= Pin('GP1', mode\=Pin.IN, pull\=Pin.PULL\_UP) p\_in() \# get value, 0 or 1 Timers[¶](#timers "Link to this heading") ------------------------------------------ See [machine.TimerWiPy](../library/machine.TimerWiPy.html#machine-timerwipy) and [machine.Pin](../library/machine.Pin.html#machine-pin) . Timer `id`’s take values from 0 to 3.: from machine import Timer from machine import Pin tim \= Timer(0, mode\=Timer.PERIODIC) tim\_a \= tim.channel(Timer.A, freq\=1000) tim\_a.freq(5) \# 5 Hz p\_out \= Pin('GP2', mode\=Pin.OUT) tim\_a.irq(trigger\=Timer.TIMEOUT, handler\=lambda t: p\_out.toggle()) PWM (pulse width modulation)[¶](#pwm-pulse-width-modulation "Link to this heading") ------------------------------------------------------------------------------------ See [machine.Pin](../library/machine.Pin.html#machine-pin) and [machine.Timer](../library/machine.Timer.html#machine-timer) . from machine import Timer \# timer 1 in PWM mode and width must be 16 buts tim \= Timer(1, mode\=Timer.PWM, width\=16) \# enable channel A @1KHz with a 50.55% duty cycle tim\_a \= tim.channel(Timer.A, freq\=1000, duty\_cycle\=5055) ADC (analog to digital conversion)[¶](#adc-analog-to-digital-conversion "Link to this heading") ------------------------------------------------------------------------------------------------ See [machine.ADCWiPy](../library/machine.ADCWiPy.html#machine-adcwipy) . from machine import ADC adc \= ADC() apin \= adc.channel(pin\='GP3') apin() \# read value, 0-4095 UART (serial bus)[¶](#uart-serial-bus "Link to this heading") -------------------------------------------------------------- See [machine.UART](../library/machine.UART.html#machine-uart) . from machine import UART uart \= UART(0, baudrate\=9600) uart.write('hello') uart.read(5) \# read up to 5 bytes SPI bus[¶](#spi-bus "Link to this heading") -------------------------------------------- See [machine.SPI](../library/machine.SPI.html#machine-spi) . from machine import SPI \# configure the SPI controller @ 2MHz spi \= SPI(0, SPI.CONTROLLER, baudrate\=2\_000\_000, polarity\=0, phase\=0) spi.write('hello') spi.read(5) \# receive 5 bytes on the bus rbuf \= bytearray(5) spi.write\_readinto('hello', rbuf) \# send and receive 5 bytes I2C bus[¶](#i2c-bus "Link to this heading") -------------------------------------------- See [machine.I2C](../library/machine.I2C.html#machine-i2c) . from machine import I2C \# configure the I2C bus i2c \= I2C(baudrate\=100000) i2c.scan() \# returns list of peripheral addresses i2c.writeto(0x42, 'hello') \# send 5 bytes to peripheral with address 0x42 i2c.readfrom(0x42, 5) \# receive 5 bytes from peripheral i2c.readfrom\_mem(0x42, 0x10, 2) \# read 2 bytes from peripheral 0x42, peripheral memory 0x10 i2c.writeto\_mem(0x42, 0x10, 'xy') \# write 2 bytes to peripheral 0x42, peripheral memory 0x10 Watchdog timer (WDT)[¶](#watchdog-timer-wdt "Link to this heading") -------------------------------------------------------------------- See [machine.WDT](../library/machine.WDT.html#machine-wdt) . from machine import WDT \# enable the WDT with a timeout of 5s (1s is the minimum) wdt \= WDT(timeout\=5000) wdt.feed() Real time clock (RTC)[¶](#real-time-clock-rtc "Link to this heading") ---------------------------------------------------------------------- See [machine.RTC](../library/machine.RTC.html#machine-rtc) from machine import RTC rtc \= RTC() \# init with default time and date rtc \= RTC(datetime\=(2015, 8, 29, 9, 0, 0, 0, None)) \# init with a specific time and date print(rtc.now()) def alarm\_handler (rtc\_o): pass \# do some non blocking operations \# warning printing on an irq via telnet is not \# possible, only via UART \# create a RTC alarm that expires after 5 seconds rtc.alarm(time\=5000, repeat\=False) \# enable RTC interrupts rtc\_i \= rtc.irq(trigger\=RTC.ALARM0, handler\=alarm\_handler, wake\=machine.SLEEP) \# go into suspended mode waiting for the RTC alarm to expire and wake us up machine.lightsleep() SD card[¶](#sd-card "Link to this heading") -------------------------------------------- See [machine.SD](../library/machine.SD.html#machine-sd) . from machine import SD import vfs \# clock pin, cmd pin, data0 pin sd \= SD(pins\=('GP10', 'GP11', 'GP15')) \# or use default ones for the expansion board sd \= SD() vfs.mount(sd, '/sd') WLAN (WiFi)[¶](#wlan-wifi "Link to this heading") -------------------------------------------------- See [network.WLAN](../library/network.WLAN.html#network-wlan) and [`machine`](../library/machine.html#module-machine "machine: functions related to the hardware") . import machine, network from network import WLAN \# configure the WLAN subsystem in station mode (the default is AP) wlan \= WLAN(mode\=WLAN.STA) \# go for fixed IP settings network.ipconfig(dns\='8.8.8.8') wlan.ipconfig(addr4\='192.168.0.107/24', gw4\='192.168.0.1') wlan.scan() \# scan for available networks wlan.connect(ssid\='mynetwork', auth\=(WLAN.WPA2, 'mynetworkkey')) while not wlan.isconnected(): pass \# enable wake on WLAN wlan.irq(trigger\=WLAN.ANY\_EVENT, wake\=machine.SLEEP) \# go to sleep machine.lightsleep() \# now, connect to the FTP or the Telnet server and the WiPy will wake-up Telnet and FTP server[¶](#telnet-and-ftp-server "Link to this heading") ------------------------------------------------------------------------ See [`network.Server`](general.html#network.Server "network.Server") from network import Server \# init with new user, password and seconds timeout server \= Server(login\=('user', 'password'), timeout\=60) server.timeout(300) \# change the timeout server.timeout() \# get the timeout server.isrunning() \# check whether the server is running or not Heart beat LED[¶](#heart-beat-led "Link to this heading") ---------------------------------------------------------- See [`wipy`](../library/wipy.html#module-wipy "wipy: WiPy specific features") . import wipy wipy.heartbeat(False) \# disable the heartbeat LED wipy.heartbeat(True) \# enable the heartbeat LED wipy.heartbeat() \# get the heartbeat state Versions and Downloads latest Versions [v1.4.4](http://docs.micropython.org/en/v1.4.4) [v1.4.5](http://docs.micropython.org/en/v1.4.5) [v1.4.6](http://docs.micropython.org/en/v1.4.6) [v1.5](http://docs.micropython.org/en/v1.5) [v1.5.1](http://docs.micropython.org/en/v1.5.1) [v1.5.2](http://docs.micropython.org/en/v1.5.2) [v1.6](http://docs.micropython.org/en/v1.6) [v1.7](http://docs.micropython.org/en/v1.7) [v1.8](http://docs.micropython.org/en/v1.8) [v1.8.1](http://docs.micropython.org/en/v1.8.1) [v1.8.2](http://docs.micropython.org/en/v1.8.2) [v1.8.3](http://docs.micropython.org/en/v1.8.3) [v1.8.4](http://docs.micropython.org/en/v1.8.4) [v1.8.5](http://docs.micropython.org/en/v1.8.5) [v1.8.6](http://docs.micropython.org/en/v1.8.6) [v1.8.7](http://docs.micropython.org/en/v1.8.7) [v1.9](http://docs.micropython.org/en/v1.9) [v1.9.1](http://docs.micropython.org/en/v1.9.1) [v1.9.2](http://docs.micropython.org/en/v1.9.2) [v1.9.3](http://docs.micropython.org/en/v1.9.3) [v1.9.4](http://docs.micropython.org/en/v1.9.4) [v1.10](http://docs.micropython.org/en/v1.10) [v1.11](http://docs.micropython.org/en/v1.11) [v1.12](http://docs.micropython.org/en/v1.12) [v1.13](http://docs.micropython.org/en/v1.13) [v1.14](http://docs.micropython.org/en/v1.14) [v1.15](http://docs.micropython.org/en/v1.15) [v1.16](http://docs.micropython.org/en/v1.16) [v1.17](http://docs.micropython.org/en/v1.17) [v1.18](http://docs.micropython.org/en/v1.18) [v1.19.1](http://docs.micropython.org/en/v1.19.1) [v1.20.0](http://docs.micropython.org/en/v1.20.0) [v1.21.0](http://docs.micropython.org/en/v1.21.0) [v1.22.0](http://docs.micropython.org/en/v1.22.0) [v1.23.0](http://docs.micropython.org/en/v1.23.0) [v1.24.0](http://docs.micropython.org/en/v1.24.0) [latest](http://docs.micropython.org/en/latest) Downloads [PDF](http://docs.micropython.org/en/latest/micropython-docs.pdf) * * * External links [micropython.org](https://www.micropython.org) [GitHub](https://github.com/micropython/micropython) --- # Quick reference for the UNIX and Windows ports — MicroPython latest documentation * [](../index.html) * Quick reference for the UNIX and Windows ports * [View page source](../_sources/unix/quickref.rst.txt) * * * This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions. If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version. Quick reference for the UNIX and Windows ports[¶](#quick-reference-for-the-unix-and-windows-ports "Link to this heading") ========================================================================================================================== Command line options[¶](#command-line-options "Link to this heading") ---------------------------------------------------------------------- Usage: micropython \[ \-h \] \[ \-i \] \[ \-O \] \[ \-v \] \[ \-X \] \[ \-c | \-m | \] \[ \] Invocation options: \-c [¶](#cmdoption-c "Link to this definition") Runs the code in ``. The code can be one or more Python statements. \-m [¶](#cmdoption-m "Link to this definition") Runs the module ``. The module must be in `sys.path`.