MicroPython Libraries For PyBoard
MicroPython Libraries For PyBoard
MicroPython Libraries For PyBoard
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.
MicroPython-specific libraries
Functionality specific to the MicroPython implementation is available in the following libraries.
• btree – simple BTree database
• framebuf — frame buffer manipulation
• machine — functions related to the hardware
• micropython – access and control MicroPython internals
• network — network configuration
• ubluetooth — low-level Bluetooth
• ucryptolib – cryptographic ciphers
• uctypes – access binary data in a structured way
Port-specific libraries
In some cases the following port/board-specific libraries have functions or classes similar to those in the
machine library. Where this occurs, the entry in the port specific library exposes hardware functionality
unique to that platform.
To write portable code use functions and classes from the machine module. To access platform-specific
hardware use the appropriate library, e.g. pyb in the case of the Pyboard.
all()
any()
bin()
class bool
class bytearray
class bytes
callable()
chr()
classmethod()
compile()
class complex
delattr(obj, name)
The argument name should be a string, and this function deletes the named attribute from the object given
by obj.
class dict
dir()
divmod()
enumerate()
eval()
exec()
filter()
class float
class frozenset
getattr()
globals()
hasattr()
hash()
hex()
id()
input()
class int
classmethod from_bytes(bytes, byteorder)
to_bytes(size, byteorder)
isinstance()
issubclass()
iter()
len()
class list
locals()
map()
max()
class memoryview
min()
next()
class object
oct()
open()
ord()
pow()
print()
property()
range()
repr()
reversed()
round()
class set
setattr()
class slice
sorted()
staticmethod()
class str
sum()
super()
class tuple
type()
zip()
Exceptions
exception AssertionError
exception AttributeError
exception Exception
exception ImportError
exception IndexError
exception KeyboardInterrupt
exception KeyError
exception MemoryError
exception NameError
exception NotImplementedError
exception OSError
See CPython documentation: OSError. MicroPython doesn’t implement errno attribute, instead use
the standard way to access exception arguments: exc.args[0].
exception RuntimeError
exception StopIteration
exception SyntaxError
exception SystemExit
exception TypeError
exception ValueError
exception ZeroDivisionError
cmath – mathematical functions for complex
numbers
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: cmath.
The cmath module provides some basic mathematical functions for working with complex numbers.
Availability: not available on WiPy and ESP8266. Floating point support required for this module.
Functions
cmath.cos(z)
cmath.exp(z)
cmath.log(z)
Return the natural logarithm of z. The branch cut is along the negative real axis.
cmath.log10(z)
Return the base-10 logarithm of z. The branch cut is along the negative real axis.
cmath.phase(z)
cmath.polar(z)
cmath.rect(r, phi)
cmath.sin(z)
cmath.sqrt(z)
Constants
cmath.e
base of the natural logarithm
cmath.pi
Functions
gc.enable()
gc.disable()
Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still
be initiated manually using gc.collect().
gc.collect()
gc.mem_alloc()
Difference to CPython
This function is MicroPython extension.
gc.mem_free()
Return the number of bytes of available heap RAM, or -1 if this amount is not known.
Difference to CPython
This function is MicroPython extension.
gc.threshold([amount])
Set or query the additional GC allocation threshold. Normally, a collection is triggered only when a new
allocation cannot be satisfied, i.e. on an out-of-memory (OOM) condition. If this function is called, in
addition to OOM, a collection will be triggered each time after amount bytes have been allocated (in total,
since the previous time such an amount of bytes have been allocated). amount is usually specified as less
than the full heap size, with the intention to trigger a collection earlier than when the heap becomes
exhausted, and in the hope that an early collection will prevent excessive memory fragmentation. This is a
heuristic measure, the effect of which will vary from application to application, as well as the optimal
value of the amount parameter.
Calling the function without argument will return the current value of the threshold. A value of -1 means a
disabled allocation threshold.
Difference to CPython
This function is a MicroPython extension. CPython has a similar function - set_threshold(), but
due to different GC implementations, its signature and semantics are different.
The math module provides some basic mathematical functions for working with floating-point numbers.
Functions
math.acos(x)
math.acosh(x)
math.asin(x)
math.asinh(x)
math.atan(x)
math.atan2(y, x)
math.atanh(x)
math.copysign(x, y)
math.cos(x)
math.cosh(x)
math.degrees(x)
math.erf(x)
math.erfc(x)
math.exp(x)
math.expm1(x)
Return exp(x) - 1.
math.fabs(x)
math.floor(x)
math.fmod(x, y)
math.frexp(x)
Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m,
e) such that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the
relation 0.5 <= abs(m) < 1 holds.
math.gamma(x)
math.isfinite(x)
math.isinf(x)
math.isnan(x)
math.ldexp(x, exp)
Return x * (2**exp).
math.lgamma(x)
math.log(x)
math.log10(x)
math.log2(x)
math.modf(x)
Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same
sign as x.
math.pow(x, y)
math.radians(x)
math.sin(x)
math.sinh(x)
Return the hyperbolic sine of x.
math.sqrt(x)
math.tan(x)
math.tanh(x)
math.trunc(x)
Constants
math.e
math.pi
Classes
class uarray.array(typecode[, iterable])
Create array with elements of given type. Initial contents of the array are given by iterable. If it is not
provided, an empty array is created.
append(val)
extend(iterable)
Append new elements as contained in iterable to the end of array, growing it.
uasyncio — asynchronous I/O scheduler
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: asyncio
Example:
import uasyncio
# Running on a pyboard
from pyb import LED
uasyncio.run(main(LED(1), LED(2)))
Core functions
uasyncio.create_task(coro)
Create a new task from the given coroutine and schedule it to run.
uasyncio.current_task()
Return the Task object associated with the currently running task.
uasyncio.run(coro)
Create a new task from the given coroutine and run it until it completes.
uasyncio.sleep(t)
This is a coroutine.
uasyncio.sleep_ms(t)
Wait for the awaitable to complete, but cancel it if it takes longer that 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.
This is a coroutine.
uasyncio.wait_for_ms(awaitable, timeout)
uasyncio.gather(*awaitables, return_exceptions=False)
Run all awaitables concurrently. Any awaitables that are not tasks are promoted to tasks.
This is a coroutine.
class Task
class uasyncio.Task
This object wraps a coroutine into a running task. Tasks can be waited on using await task, which
will wait for the task to complete and return the return value of the task.
Tasks should not be created directly, rather use create_task to create them.
Task.cancel()
Cancel the task by injecting a CancelledError into it. The task may or may not ignore this exception.
class Event
class uasyncio.Event
Create a new event which can be used to synchronise tasks. Events start in the cleared state.
Event.is_set()
Event.set()
Set the event. Any tasks waiting on the event will be scheduled to run.
Note: This must be called from within a task. It is not safe to call this from an IRQ, scheduler callback, or
other thread. See ThreadSafeFlag.
Event.clear()
Event.wait()
Wait for the event to be set. If the event is already set then it returns immediately.
This is a coroutine.
class ThreadSafeFlag
class uasyncio.ThreadSafeFlag
Create a new flag which can be used to synchronise a task with code running outside the asyncio loop,
such as other threads, IRQs, or scheduler callbacks. Flags start in the cleared state.
ThreadSafeFlag.set()
Set the flag. If there is a task waiting on the event, it will be scheduled to run.
ThreadSafeFlag.wait()
Wait for the flag to be set. If the flag is already set then it returns immediately.
This is a coroutine.
class Lock
class uasyncio.Lock
Create a new lock which can be used to coordinate tasks. Locks start in the unlocked state.
In addition to the methods below, locks can be used in an async with statement.
Lock.locked()
Lock.acquire()
Wait for the lock to be in the unlocked state and then lock it in an atomic way. Only one task can acquire
the lock at any one time.
This is a coroutine.
Lock.release()
Release the lock. If any tasks are waiting on the lock then the next one in the queue is scheduled to run
and the lock remains locked. Otherwise, no tasks are waiting an the lock becomes unlocked.
Open a TCP connection to the given host and port. The host address will be resolved using
socket.getaddrinfo, which is currently a blocking call.
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.
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.
This is a coroutine.
class uasyncio.Stream
This represents a TCP stream connection. To minimise code this class implements both a reader and a
writer, and both StreamReader and StreamWriter alias to this class.
Stream.get_extra_info(v)
Get extra information about the stream, given by v. The valid values for v are: peername.
Stream.close()
Stream.wait_closed()
This is a coroutine.
Stream.read(n)
This is a coroutine.
Stream.readline()
This is a coroutine.
Stream.write(buf)
Accumulated buf to the output buffer. The data is only flushed when Stream.drain is called. It is
recommended to call Stream.drain immediately after calling this function.
Stream.drain()
This is a coroutine.
class uasyncio.Server
This represents the server class returned from start_server. It can be used in an async with
statement to close the server upon exit.
Server.close()
Server.wait_closed()
This is a coroutine.
Event Loop
uasyncio.get_event_loop()
Return the event loop used to schedule and run tasks. See Loop.
uasyncio.new_event_loop()
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 uasyncio.Loop
This represents the object which schedules and runs tasks. It cannot be created, use get_event_loop
instead.
Loop.create_task(coro)
Create a task from the given coro and return the new Task object.
Loop.run_forever()
Loop.run_until_complete(awaitable)
Run the given awaitable until it completes. If awaitable is not a task then it will be promoted to one.
Loop.stop()
Loop.close()
Loop.set_exception_handler(handler)
Set the exception handler to call when a Task raises an exception that is not caught. The handler should
accept two arguments: (loop, context).
Loop.get_exception_handler()
Get the current exception handler. Returns the handler, or None if no custom handler is set.
Loop.default_exception_handler(context)
Loop.call_exception_handler(context)
Call the current exception handler. The argument context is passed through and is a dictionary containing
keys: 'message', 'exception', 'future'.
This module implements conversions between binary data and various encodings of it in ASCII form (in both
directions).
Functions
ubinascii.hexlify(data[, sep])
Convert the bytes in the data object to a hexadecimal representation. Returns a bytes object.
If the additional argument sep is supplied it is used as a separator between hexadecimal values.
ubinascii.unhexlify(data)
Convert hexadecimal data to binary representation. Returns bytes string. (i.e. inverse of hexlify)
ubinascii.a2b_base64(data)
Decode base64-encoded data, ignoring invalid characters in the input. Conforms to RFC 2045 s.6.8.
Returns a bytes object.
ubinascii.b2a_base64(data)
Encode binary data in base64 format, as in RFC 3548. Returns the encoded data followed by a newline
character, as a bytes object.
This module implements advanced collection and container types to hold/accumulate various objects.
Classes
ucollections.deque(iterable, maxlen[, flags])
Deques (double-ended queues) are a list-like container that support O(1) appends and pops from either
side of the deque. New deques are created using the following arguments:
• iterable must be the empty tuple, and the new deque is created empty.
• maxlen must be specified and the deque will be bounded to this maximum length.
Once the deque is full, any new items added will discard items from the opposite end.
• The optional flags can be 1 to check for overflow when adding items.
As well as supporting bool and len, deque objects have the following methods:
deque.append(x)
Add x to the right side of the deque. Raises IndexError if overflow checking is enabled and there is
no more room left.
deque.popleft()
Remove and return an item from the left side of the deque. Raises IndexError if no items are
present.
ucollections.namedtuple(name, fields)
This is factory function to create a new namedtuple type with a specific name and set of fields. A
namedtuple is a subclass of tuple which allows to access its fields not just by numeric index, but also with
an attribute access syntax using symbolic field names. Fields is a sequence of strings specifying field
names. For compatibility with CPython it can also be a a string with space-separated field named (but this
is less efficient). Example of use:
ucollections.OrderedDict(...)
dict type subclass which remembers and preserves the order of keys added. When ordered dict is
iterated over, keys/items are returned in the order they were added:
Output:
z 1
a 2
w 5
b 3
This module provides access to symbolic error codes for OSError exception. A particular inventory of codes
depends on MicroPython port.
Constants
EEXIST, EAGAIN, etc.
Error codes, based on ANSI C/POSIX standard. All error codes start with “E”. As mentioned above,
inventory of the codes depends on MicroPython port. Errors are usually accessible as exc.args[0]
where exc is an instance of OSError. Usage example:
try:
uos.mkdir("my_dir")
except OSError as exc:
if exc.args[0] == uerrno.EEXIST:
print("Directory already exists")
uerrno.errorcode
Dictionary mapping numeric error codes to strings with symbolic error code (see above):
>>> print(uerrno.errorcode[uerrno.EEXIST])
EEXIST
uhashlib – hashing algorithms
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: hashlib.
This module implements binary data hashing algorithms. The exact inventory of available algorithms depends
on a board. Among the algorithms which may be implemented:
• SHA256 - The current generation, modern hashing algorithm (of SHA2 series). It is suitable for
cryptographically-secure purposes. Included in the MicroPython core and any board is recommended to
provide this, unless it has particular code size constraints.
• SHA1 - A previous generation algorithm. Not recommended for new usages, but SHA1 is a part of
number of Internet standards and existing applications, so boards targeting network connectivity and
interoperability will try to provide this.
• MD5 - A legacy algorithm, not considered cryptographically secure. Only selected boards, targeting
interoperability with legacy applications, will offer this.
Constructors
class uhashlib.sha256([data])
Create an SHA256 hasher object and optionally feed data into it.
class uhashlib.sha1([data])
Create an SHA1 hasher object and optionally feed data into it.
class uhashlib.md5([data])
Create an MD5 hasher object and optionally feed data into it.
Methods
hash.update(data)
hash.digest()
Return hash for all data passed through hash, as a bytes object. After this method is called, more data
cannot be fed into the hash any longer.
hash.hexdigest()
Functions
uheapq.heappush(heap, item)
uheapq.heappop(heap)
Pop the first item from the heap, and return it. Raises IndexError if heap is empty.
uheapq.heapify(x)
This module contains additional types of stream (file-like) objects and helper functions.
Conceptual hierarchy
Difference to CPython
Conceptual hierarchy of stream base classes is simplified in MicroPython, as described in this section.
(Abstract) base stream classes, which serve as a foundation for behavior 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 favor no-short-
operations behavior 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 behavior gets tricky in case of non-blocking streams, blocking vs non-blocking
behavior 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
uio.open(name, mode='r', **kwargs)
Open a file. Builtin open() function is aliased to this function. All ports (which provide access to file
system) are required to support mode parameter, but support for other arguments vary by port.
Classes
class uio.FileIO(...)
This is type of a file open in binary mode, e.g. using open(name, "rb"). You should not instantiate
this class directly.
class uio.TextIOWrapper(...)
This is type of a file open in text mode, e.g. using open(name, "rt"). You should not instantiate this
class directly.
class uio.StringIO([string])
class uio.BytesIO([string])
In-memory file-like objects for input/output. StringIO is used for text-mode I/O (similar to a normal
file opened with “t” modifier). BytesIO is used for binary-mode I/O (similar to a normal file opened
with “b” modifier). Initial contents of file-like objects can be specified with string parameter (should be
normal string for StringIO or bytes object for BytesIO). All the usual file methods like read(),
write(), seek(), flush(), close() are available on these objects, and additionally, a following
method:
getvalue()
Get the current contents of the underlying buffer which holds data.
class uio.StringIO(alloc_size)
class uio.BytesIO(alloc_size)
Difference to CPython
These constructors are a MicroPython extension.
ujson – JSON encoding and decoding
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: json.
This modules allows to convert between Python objects and the JSON data format.
Functions
ujson.dump(obj, stream)
ujson.dumps(obj)
ujson.load(stream)
Parse the given stream, interpreting it as a JSON string and deserialising the data to a Python object. The
resulting object is returned.
Parsing continues until end-of-file is encountered. A ValueError is raised if the data in stream is not
correctly formed.
ujson.loads(str)
Parse the JSON str and return an object. Raises ValueError if the string is not correctly formed.
uos – basic “operating system” services
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: os.
The uos module contains functions for filesystem access and mounting, terminal redirection and duplication,
and the uname and urandom functions.
General functions
uos.uname()
Return a tuple (possibly a named tuple) containing information about the underlying machine and/or its
operating system. The tuple has five fields in the following order, each of them being a string:
uos.urandom(n)
Return a bytes object with n random bytes. Whenever possible, it is generated by the hardware random
number generator.
Filesystem access
uos.chdir(path)
uos.getcwd()
uos.ilistdir([dir])
This function returns an iterator which then yields tuples corresponding to the entries in the directory that
it is listing. With no argument it lists the current directory, otherwise it lists the directory given by dir.
• 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.
uos.listdir([dir])
With no argument, list the current directory. Otherwise list the given directory.
uos.mkdir(path)
uos.remove(path)
Remove a file.
uos.rmdir(path)
Remove a directory.
uos.rename(old_path, new_path)
Rename a file.
uos.stat(path)
uos.statvfs(path)
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.
uos.sync()
Duplicate or switch the MicroPython terminal (the REPL) on the given stream-like object. The
stream_object argument must be a native stream object, or derive from uio.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
Some ports provide a Virtual Filesystem (VFS) and the ability to mount multiple “real” filesystems within this
VFS. Filesystem objects can be mounted at either the root of the VFS, or at a subdirectory that lives in the root.
This allows dynamic and flexible configuration of the filesystem that is seen by Python programs. Ports that
have this functionality provide the mount() and umount() functions, and possibly various filesystem
implementations represented by VFS classes.
uos.mount(fsobj, mount_point, *, readonly)
Mount the filesystem object fsobj at the location in the VFS given by the mount_point string. fsobj can be
a a VFS object that has a mount() method, or a block device. If it’s a block device then the filesystem
type is automatically detected (an exception is raised if no filesystem was recognised). mount_point may
be '/' to mount fsobj at the root, or '/<name>' to mount it at a subdirectory under the root.
During the mount process the method mount() is called on the filesystem object.
uos.umount(mount_point)
Unmount a filesystem. mount_point can be a string naming the mount location, or a previously-mounted
filesystem object. During the unmount process the method umount() is called on the filesystem object.
class uos.VfsFat(block_dev)
Create a filesystem object that uses the FAT filesystem format. Storage of the FAT filesystem is provided
by block_dev. Objects created by this constructor can be mounted using mount().
static mkfs(block_dev)
Create a filesystem object that uses the littlefs v1 filesystem format. Storage of the littlefs filesystem is
provided by block_dev, which must support the extended interface. Objects created by this constructor
can be mounted using mount().
Note
There are reports of littlefs v1 failing in certain situations, for details see littlefs issue 347.
Create a filesystem object that uses the littlefs v2 filesystem format. Storage of the littlefs filesystem is
provided by block_dev, which must support the extended interface. Objects created by this constructor
can be mounted using mount().
The mtime argument enables modification timestamps for files, stored using littlefs attributes. This option
can be disabled or enabled differently each mount time and timestamps will only be added or updated if
mtime is enabled, otherwise the timestamps will remain untouched. Littlefs v2 filesystems without
timestamps will work without reformatting and timestamps will be added transparently to existing files
once they are opened for writing. When mtime is enabled uos.stat on files without timestamps will
return 0 for the timestamp.
Note
There are reports of littlefs v2 failing in certain situations, for details see littlefs issue 295.
Block devices
A block device is an object which implements the block protocol. This enables a device to support MicroPython
filesystems. The physical hardware is represented by a user defined class. The AbstractBlockDev class is a
template for the design of such a class: MicroPython does not actually provide that class, but an actual block
device class must implement the methods described below.
A concrete implementation of this class will usually allow access to the memory-like functionality of a piece of
hardware (like flash memory). A block device can be formatted to any supported filesystem and mounted using
uos methods.
See Working with filesystems for example implementations of block devices using the two variants of the block
protocol described below.
Construct a block device object. The parameters to the constructor are dependent on the specific block
device.
readblocks(block_num, buf)
readblocks(block_num, buf, offset)
The first form reads aligned, multiples of blocks. Starting at the block given by the index
block_num, read blocks from the device into buf (an array of bytes). The number of blocks to read is
given by the length of buf, which will be a multiple of the block size.
The second form allows reading at arbitrary locations within a block, and arbitrary lengths. Starting
at block index block_num, and byte offset within that block of offset, read bytes from the device
into buf (an array of bytes). The number of bytes to read is given by the length of buf.
writeblocks(block_num, buf)
writeblocks(block_num, buf, offset)
The first form writes aligned, multiples of blocks, and requires that the blocks that are written to be
first erased (if necessary) by this method. Starting at the block given by the index block_num, write
blocks from buf (an array of bytes) to the device. The number of blocks to write is given by the
length of buf, which will be a multiple of the block size.
The second form allows writing at arbitrary locations within a block, and arbitrary lengths. Only the
bytes being written should be changed, and the caller of this method must ensure that the relevant
blocks are erased via a prior ioctl call. Starting at block index block_num, and byte offset within
that block of offset, write bytes from buf (an array of bytes) to the device. The number of bytes to
write is given by the length of buf.
Note that implementations must never implicitly erase blocks if the offset argument is specified,
even if it is zero.
ioctl(op, arg)
Control the block device and query its parameters. The operation to perform is given by
op which is one of the following integers:
As a minimum ioctl(4, ...) must be intercepted; for littlefs ioctl(6, ...) must also be
intercepted. The need for others is hardware dependent.
Unless otherwise stated ioctl(op, arg) can return None. Consequently an implementation
can ignore unused values of op. Where op is intercepted, the return value for operations 4 and 5 are
as detailed above. Other operations should return 0 on success and non-zero for failure, with the
value returned being an OSError errno code.
ure – simple regular expressions
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: re.
This module implements regular expression operations. Regular expression syntax supported is a subset of
CPython re module (and actually is a subset of POSIX extended regular expressions).
[...]
Match set of characters. Individual characters and ranges are supported, including negated sets (e.g. [^a-
c]).
??
Non-greedy version of ?, match zero or one, with the preference for zero.
*?
Non-greedy version of *, match zero or more, with the preference for the shortest match.
+?
Non-greedy version of +, match one or more, with the preference for the shortest match.
Match either the left-hand side or the right-hand side sub-patterns of this operator.
(...)
Grouping. Each group is capturing (a substring it captures can be accessed with match.group()
method).
\d
\D
\s
\S
\w
\W
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})
• special character escapes like \r, \n - use Python’s own escaping instead
• etc.
Example:
import ure
regex.split("line1\rline2\nline3\r\n")
# Result:
# ['line1', 'line2', 'line3', '', '']
Functions
ure.compile(regex_str[, flags])
ure.match(regex_str, string)
Compile regex_str and match against string. Match always happens from starting position in a string.
ure.search(regex_str, string)
Compile regex_str and search it in a string. Unlike match, this will search string for first position which
matches regex (which still may be 0 if regex is anchored).
Compile regex_str and search for it in string, replacing all matches with replace, and returning the new
string.
replace can be a string or a function. If it is a string then escape sequences of the form \<number> and
\g<number> can be used to expand to the corresponding group (or an empty string for unmatched
groups). If replace is a function then it must take a single argument (the match) and should return a
replacement string.
If count is specified and non-zero then substitution will stop after this many substitutions are made. The
flags argument is ignored.
ure.DEBUG
Flag value, display debug information about compiled expression. (Availability depends on MicroPython
port.)
Regex objects
Compiled regular expression. Instances of this class are created using ure.compile().
regex.match(string)
regex.search(string)
regex.sub(replace, string, count=0, flags=0, /)
Similar to the module-level functions match(), search() and sub(). Using methods is (much)
more efficient if the same regex is applied to multiple strings.
regex.split(string, max_split=-1, /)
Split a string using regex. If max_split is given, it specifies maximum number of splits to perform.
Returns list of strings (there may be up to max_split+1 elements if it’s specified).
Match objects
Match objects as returned by match() and search() methods, and passed to the replacement function in
sub().
match.group(index)
Return matching (sub)string. index is 0 for entire match, 1 and above for each capturing group. Only
numeric groups are supported.
match.groups()
Return a tuple containing all the substrings of the groups of the match.
match.start([index])
match.end([index])
Return the index in the original string of the start or end of the substring group that was matched. index
defaults to the entire group, otherwise it will select a group.
match.span([index])
This module provides functions to efficiently wait for events on multiple streams (select streams which are
ready for operations).
Functions
uselect.poll()
This function is provided by some MicroPython ports for compatibility and is not efficient. Usage of
Poll is recommended instead.
class Poll
Methods
poll.register(obj[, eventmask])
Note that flags like uselect.POLLHUP and uselect.POLLERR are not valid as input eventmask
(these are unsolicited events which will be returned from poll() regardless of whether they are asked
for). This semantics is per POSIX.
It is OK to call this function multiple times for the same obj. Successive calls will update obj’s eventmask
to the value of eventmask (i.e. will behave as modify()).
poll.unregister(obj)
poll.modify(obj, eventmask)
Modify the eventmask for obj. If obj is not registered, OSError is raised with error of ENOENT.
poll.poll(timeout=-1, /)
Wait for at least one of the registered objects to become ready or have an exceptional condition, with
optional timeout in milliseconds (if timeout arg is not specified or -1, there is no timeout).
Returns list of (obj, event, …) tuples. There may be other elements in tuple, depending on a platform
and version, so don’t assume that its size is 2. The event element specifies which events happened with
a stream and is a combination of uselect.POLL* constants described above. Note that flags
uselect.POLLHUP and uselect.POLLERR can be returned at any time (even if were not asked
for), and must be acted on accordingly (the corresponding stream unregistered from poll and likely
closed), because otherwise all further invocations of poll() may return immediately with these flags set
for this stream again.
Difference to CPython
Tuples returned may contain more than 2 elements as described above.
poll.ipoll(timeout=-1, flags=0, /)
Like poll.poll(), but instead returns an iterator which yields a callee-owned tuple. This
function provides an efficient, allocation-free way to poll on streams.
If flags is 1, one-shot behavior for events is employed: streams for which events happened will have their
event masks automatically reset (equivalent to poll.modify(obj, 0)), so new events for such a
stream won’t be processed until new mask is set with poll.modify(). This behavior is useful for
asynchronous I/O schedulers.
Difference to CPython
This function is a MicroPython extension.
usocket – socket module
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: socket.
Using getaddrinfo is the most efficient (both in terms of memory and processing power) and portable way
to work with addresses.
However, socket module (note the difference with native MicroPython usocket module described here)
provides CPython-compatible way to specify addresses using tuples, as described below. Note that depending
on a MicroPython port, socket module can be builtin or need to be installed from micropython-lib (as
in the case of MicroPython Unix port), and some ports still accept only numeric addresses in the tuple format,
and require to use getaddrinfo function to resolve domain names.
Summing up:
• Always use getaddrinfo when writing portable applications.
• Tuple addresses described below can be used as a shortcut for quick hacks and interactive use, if your
port supports them.
Tuple address format for socket module:
• IPv4: (ipv4_address, port), where ipv4_address is a string with dot-notation numeric IPv4 address, e.g.
"8.8.8.8", and port is and integer port number in the range 1-65535. Note the domain names are not
accepted as ipv4_address, they should be resolved first using usocket.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
usocket.getaddrinfo(). Availability of IPv6 support depends on a MicroPython port.
Functions
usocket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, /)
Create a new socket using the given address family, socket type and protocol number. Note that
specifying proto in most cases is not required (and not recommended, as some MicroPython ports may
omit IPPROTO_* constants). Instead, type argument will select needed protocol automatically:
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() 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).
s = usocket.socket()
# This assumes that if "type" is not specified, an address for
# SOCK_STREAM will be returned, which may be not true
s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1])
s = usocket.socket()
# Guaranteed to return an address which can be connect'ed to for
# stream operation.
s.connect(usocket.getaddrinfo('www.micropython.org', 80, 0, SOCK_STREAM)[0][-1])
Difference to CPython
CPython raises a socket.gaierror exception (OSError subclass) in case of error in this function.
MicroPython doesn’t have socket.gaierror and raises OSError directly. Note that error numbers of
getaddrinfo() form a separate namespace and may not match error numbers from the uerrno
module. To distinguish getaddrinfo() errors, they are represented by negative numbers, whereas
standard system errors are positive numbers (error numbers are accessible using e.args[0] property
from an exception object). The use of negative values is a provisional detail which may change in the
future.
usocket.inet_ntop(af, bin_addr)
Convert a binary network address bin_addr of the given address family af to a textual representation:
usocket.inet_pton(af, txt_addr)
Convert a textual network address txt_addr of the given address family af to a binary representation:
Constants
usocket.AF_INET
usocket.AF_INET6
usocket.SOCK_STREAM
usocket.SOCK_DGRAM
Socket types.
usocket.IPPROTO_UDP
usocket.IPPROTO_TCP
IP protocol numbers. Availability depends on a particular MicroPython port. Note that you don’t need to
specify these in a call to usocket.socket(), because SOCK_STREAM socket type automatically
selects IPPROTO_TCP, and SOCK_DGRAM - IPPROTO_UDP. Thus, the only real use of these constants
is as an argument to setsockopt().
usocket.SOL_*
Socket option levels (an argument to setsockopt()). The exact inventory depends on a MicroPython
port.
usocket.SO_*
Socket options (an argument to setsockopt()). The exact inventory depends on a MicroPython port.
class socket
Methods
socket.close()
Mark the socket closed and release all resources. Once that happens, all future operations on the socket
object will fail. The remote end will receive EOF indication if supported by protocol.
Sockets are automatically closed when they are garbage-collected, but it is recommended to close()
them explicitly as soon you finished working with them.
socket.bind(address)
Bind the socket to address. The socket must not already be bound.
socket.listen([backlog])
Enable a server to accept connections. If backlog is specified, it must be at least 0 (if it’s lower, it will be
set to 0); and specifies the number of unaccepted connections that the system will allow before refusing
new connections. If not specified, a default reasonable value is chosen.
socket.accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return
value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the
connection, and address is the address bound to the socket on the other end of the connection.
socket.connect(address)
socket.send(bytes)
Send data to the socket. The socket must be connected to a remote socket. Returns number of bytes sent,
which may be smaller than the length of data (“short write”).
socket.sendall(bytes)
Send all data to the socket. The socket must be connected to a remote socket. Unlike send(), this
method will try to send all of data, by sending data chunk by chunk consecutively.
The behavior of this method on non-blocking sockets is undefined. Due to this, on MicroPython, it’s
recommended to use write() method instead, which has the same “no short writes” policy for blocking
sockets, and will return number of bytes sent on non-blocking sockets.
socket.recv(bufsize)
Receive data from the socket. The return value is a bytes object representing the data received. The
maximum amount of data to be received at once is specified by bufsize.
socket.sendto(bytes, address)
Send data to the socket. The socket should not be connected to a remote socket, since the destination
socket is specified by address.
socket.recvfrom(bufsize)
Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object
representing the data received and address is the address of the socket sending the data.
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)
Not every MicroPython port supports this method. A more portable and generic solution is to use
uselect.poll object. This allows to wait on multiple objects at the same time (and not just on
sockets, but on generic stream objects which support polling). Example:
# Instead of:
s.settimeout(1.0) # time in seconds
s.read(10) # may timeout
# Use:
poller = uselect.poll()
poller.register(s, uselect.POLLIN)
res = poller.poll(1000) # time in milliseconds
if not res:
# s is still not ready for input, i.e. operation timed out
Difference to CPython
CPython raises a socket.timeout exception in case of timeout, which is an OSError subclass.
MicroPython raises an OSError directly instead. If you use except OSError: to catch the exception,
your code will work both in MicroPython and CPython.
socket.setblocking(flag)
Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to
blocking mode.
socket.makefile(mode='rb', buffering=0, /)
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])
Read up to size bytes from the socket. Return a bytes object. If size is not given, it reads all data available
from the socket until EOF; as such the method will not return until the socket is closed. This function tries
to read as much data as requested (no “short reads”). This may be not possible with non-blocking socket
though, and then less data will be returned.
socket.readinto(buf[, nbytes])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most
len(buf) bytes. Just as read(), this method follows “no short reads” policy.
socket.readline()
socket.write(buf)
Write the buffer of bytes to the socket. This function will try to write all data to a socket (no “short
writes”). This may be not possible with a non-blocking socket though, and returned value will be less than
the length of buf.
exception usocket.error
Difference to CPython
CPython used to have a socket.error exception which is now deprecated, and is an alias of
OSError. In MicroPython, use OSError directly.
ussl – SSL/TLS module
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: ssl.
This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets
Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side.
Functions
ussl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE,
ca_certs=None, do_handshake=True)
Takes a `stream` *sock* (usually usocket.socket instance of
``SOCK_STREAM`` type),
and returns an instance of ssl.SSLSocket, which wraps the underlying
stream in
an SSL context. Returned object has the usual `stream` interface methods
like
``read()``, ``write()``, etc.
A server-side SSL socket should be created from a normal socket returned
from
:meth:`~usocket.socket.accept()` on a non-SSL listening server socket.
• do_handshake 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 (there is no do_handshake
method as in CPython). 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.
Depending on the underlying module implementation in a particular MicroPython port, some or all
keyword arguments above may be not supported.
Warning
Some implementations of ussl 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.
Exceptions
ssl.SSLError
This exception does NOT exist. Instead its base class, OSError, is used.
Constants
ussl.CERT_NONE
ussl.CERT_OPTIONAL
ussl.CERT_REQUIRED
Functions
ustruct.calcsize(fmt)
Pack the values v1, v2, … according to the format string fmt. The return value is a bytes object encoding
the values.
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.
ustruct.unpack(fmt, data)
Unpack from the data according to the format string fmt. The return value is a tuple of the unpacked
values.
Unpack from the data starting at offset according to the format string fmt. offset may be negative to count
from the end of buffer. The return value is a tuple of the unpacked valu
usys – system specific functions
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: sys.
Functions
usys.exit(retval=0, /)
Terminate current program with a given exit code. Underlyingly, this function raise as SystemExit
exception. If an argument is given, its value given as an argument to SystemExit.
usys.atexit(func)
Register func to be called upon termination. func must be a callable that takes no arguments, or None to
disable the call. The atexit function will return the previous value set by this function, which is
initially None.
Difference to CPython
This function is a MicroPython extension intended to provide similar functionality to the atexit
module in CPython.
usys.print_exception(exc, file=usys.stdout, /)
Print exception with a traceback to a file-like object file (or usys.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.
Constants
usys.argv
usys.byteorder
usys.implementation
Object with information about the current Python implementation. For MicroPython, it has following
attributes:
This object is the recommended way to distinguish MicroPython from other Python implementations
(note that it still may not exist in the very minimal ports).
Difference to CPython
CPython mandates more attributes for this object, but the actual useful bare minimum is implemented in
MicroPython.
usys.maxsize
Maximum value which a native integer type can hold on the current platform, or maximum value
representable by MicroPython integer type, if it’s smaller than platform max value (that is the case for
MicroPython ports without long int support).
This attribute is useful for detecting “bitness” of a platform (32-bit vs 64-bit, etc.). It’s recommended to
not compare this attribute to some value directly, but instead count number of bits in it:
bits = 0
v = usys.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.
usys.modules
Dictionary of loaded modules. On some ports, it may not include builtin modules.
usys.path
usys.platform
The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS,
e.g. "linux". For baremetal ports it is an identifier of a board, e.g. "pyboard" for the original
MicroPython reference board. It thus can be used to distinguish one board from another. If you need to
check whether your program runs on MicroPython (vs other Python implementation), use
usys.implementation instead.
usys.stderr
usys.stdin
usys.stdout
Standard output stream.
usys.version
usys.version_info
Python language version that this implementation conforms to, as a tuple of ints.
Difference to CPython
Only the first three version numbers (major, minor, micro) are supported and they can be
referenced only by index, not by name.
utime – time related functions
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: time.
The utime 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,
embedded ports use epoch of 2000-01-01 00:00:00 UTC.
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
utime.gmtime([secs])
utime.localtime([secs])
Convert the time secs expressed in seconds since the Epoch (see above) into an 8-tuple which contains:
(year, month, mday, hour, minute, second, weekday, yearday) If secs is not
provided or None, then the current time from the RTC is used.
The gmtime() function returns a date-time tuple in UTC, and localtime() returns a date-time tuple
in local time.
• month is 1-12
• mday is 1-31
• hour is 0-23
• minute is 0-59
• second is 0-59
utime.mktime()
This is inverse function of localtime. It’s argument is a full 8-tuple which expresses a time as per
localtime. It returns an integer which is the number of seconds since Jan 1, 2000.
utime.sleep(seconds)
Sleep for the given number of seconds. Some boards may accept seconds as a floating-point number to
sleep for a fractional number of seconds. Note that other boards may not accept a floating-point argument,
for compatibility with them use sleep_ms() and sleep_us() functions.
utime.sleep_ms(ms)
utime.sleep_us(us)
utime.ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, that wraps around after some
value.
The wrap-around value is not explicitly exposed, but we will refer to it as TICKS_MAX to simplify
discussion. Period of the values is TICKS_PERIOD = TICKS_MAX + 1. TICKS_PERIOD is guaranteed
to be a power of two, but otherwise may differ from port to port. The same period value is used for all of
ticks_ms(), ticks_us(), ticks_cpu() functions (for simplicity). Thus, these functions will
return a value in range [0 .. TICKS_MAX], inclusive, total TICKS_PERIOD values. Note that only non-
negative values are used. For the most part, you should treat values returned by these functions as opaque.
The only operations available for them are ticks_diff() and ticks_add() functions described
below.
Note: Performing standard mathematical operations (+, -) or relational operators (<, <=, >, >=) directly on
these value will lead to invalid result. Performing mathematical operations and then passing their results
as arguments to ticks_diff() or ticks_add() will also lead to invalid results from the latter
functions.
utime.ticks_us()
utime.ticks_cpu()
Similar to ticks_ms() and ticks_us(), but with the highest possible resolution in the system. This
is usually CPU clocks, and that’s why the function is named that way. But it doesn’t have to be a CPU
clock, some other timing source available in a system (e.g. high-resolution timer) can be used instead.
The exact timing unit (resolution) of this function is not specified on utime 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.
Offset ticks value by a given number, which can be either positive or negative. Given a ticks value, this
function allows to calculate ticks value delta ticks before or after it, following modular-arithmetic
definition of tick values (see ticks_ms() above). ticks parameter must be a direct result of call to
ticks_ms(), ticks_us(), or ticks_cpu() functions (or from previous call to ticks_add()).
However, delta can be an arbitrary integer number or numeric expression. ticks_add() is useful for
calculating deadlines for events/tasks. (Note: you must use ticks_diff() function to work with
deadlines.)
Examples:
utime.ticks_diff(ticks1, ticks2)
The argument order is the same as for subtraction operator, ticks_diff(ticks1, ticks2) has the
same meaning as ticks1 - ticks2. However, values returned by ticks_ms(), etc. functions may
wrap around, so directly using subtraction on them will produce incorrect result. That is why
ticks_diff() is needed, it implements modular (or more specifically, ring) arithmetics to produce
correct result even for wrap-around values (as long as they not too distant inbetween, 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 behavior: don’t let your
application run any single task for too long. Run tasks in steps, and do time-keeping inbetween.
• Polling with timeout. In this case, the order of events is known, and you will deal only with
positive results of ticks_diff():
• Scheduling events. In this case, ticks_diff() result may be negative if an event is overdue:
Note: Do not pass time() values to ticks_diff(), you should use normal mathematical operations
on them. But note that time() may (and will) also overflow. This is known as https://en.wikipedia.org/
wiki/Year_2038_problem .
utime.time()
Returns the number of seconds, as an integer, since the Epoch, assuming that underlying RTC is set and
maintained as described above. If an RTC is not set, this function returns number of seconds since a port-
specific reference point in time (for embedded boards without a battery-backed RTC, usually since power
up or reset). If you want to develop portable MicroPython application, you should not rely on this
function to provide higher than second precision. If you need higher precision, absolute timestamps, use
time_ns(). If relative times are acceptable then use the ticks_ms() and ticks_us() functions.
If you need calendar time, gmtime() or localtime() without an argument is a better choice.
Difference to CPython
In CPython, this function returns number of seconds since Unix epoch, 1970-01-01 00:00 UTC, as a
floating-point, usually having microsecond precision. With MicroPython, only Unix port uses the same
Epoch, and if floating-point precision allows, returns sub-second precision. Embedded hardware usually
doesn’t have floating-point precision to represent both long time ranges and subsecond precision, so they
use integer value with second precision. Some embedded hardware also lacks battery-powered RTC, so
returns number of seconds since last power-up or from other relative, hardware-specific point (e.g. reset).
utime.time_ns()
Similar to time() but returns nanoseconds since the Epoch, as an integer (usually a big integer, so will
allocate on the heap).
uzlib – zlib decompression
This module implements a subset of the corresponding CPython module, as described below. For more
information, refer to the original CPython documentation: zlib.
This module allows to decompress binary data compressed with DEFLATE algorithm (commonly used in zlib
library and gzip archiver). Compression is not yet implemented.
Functions
uzlib.decompress(data, wbits=0, bufsize=0, /)
Return decompressed data as bytes. wbits is DEFLATE dictionary window size used during compression
(8-15, the dictionary size is power of 2 of that value). Additionally, if value is positive, data is assumed to
be zlib stream (with zlib header). Otherwise, if it’s negative, it’s assumed to be raw DEFLATE stream.
bufsize parameter is for compatibility with CPython and is ignored.
Create a stream wrapper which allows transparent decompression of compressed data in another
stream. This allows to process compressed streams with data larger than available heap size. In addition to
values described in decompress(), wbits may take values 24..31 (16 + 8..15), meaning that input
stream has gzip header.
Difference to CPython
This class is MicroPython extension. It’s included on provisional basis and may be changed considerably
or removed in later versions.
# Prints b'two'
print(db[b"2"])
del db[b"2"]
# Prints:
# b"1"
# b"3"
for key in db:
print(key)
db.close()
# Don't forget to close the underlying stream!
f.close()
Functions
btree.open(stream, *, flags=0, pagesize=0, cachesize=0, minkeypage=0)
Open a database from a random-access stream (like an open file). All other parameters are optional and
keyword-only, and allow to tweak advanced parameters of the database operation (most users will not
need them):
• pagesize - Page size used for the nodes in BTree. Acceptable range is 512-65536. If 0, a port-
specific default will be used, optimized for port’s memory usage and/or performance.
• cachesize - Suggested memory cache size in bytes. For a board with enough memory using larger
values may improve performance. Cache policy is as follows: entire cache is not allocated at once;
instead, accessing a new page in database will allocate a memory buffer for it, until value specified
by cachesize is reached. Then, these buffers will be managed using LRU (least recently used)
policy. More buffers may still be allocated if needed (e.g., if a database contains big keys and/or
values). Allocated cache buffers aren’t reclaimed.
• minkeypage - Minimum number of keys to store per page. Default value of 0 equivalent to 2.
Returns a BTree object, which implements a dictionary protocol (set of methods), and some additional
methods described below.
Methods
btree.close()
Close the database. It’s mandatory to close the database at the end of processing, as some unwritten data
may be still in the cache. Note that this does not close underlying stream with which the database was
opened, it should be closed separately (which is also mandatory to make sure that data flushed from
buffer to the underlying storage).
btree.flush()
btree.__getitem__(key)
btree.get(key, default=None, /)
btree.__setitem__(key, val)
btree.__delitem__(key)
btree.__contains__(key)
btree.__iter__()
A BTree object can be iterated over directly (similar to a dictionary) to get access to all keys in order.
These methods are similar to standard dictionary methods, but also can take optional parameters to iterate
over a key sub-range, instead of the entire database. Note that for all 3 methods, start_key and end_key
arguments represent key values. For example, values() method will iterate over values corresponding
to they key range given. None values for start_key means “from the first key”, no end_key or its value of
None means “until the end of database”. By default, range is inclusive of start_key and exclusive of
end_key, you can include end_key in iteration by passing flags of btree.INCL. You can iterate in
descending key direction by passing flags of btree.DESC. The flags values can be ORed together.
Constants
btree.INCL
A flag for keys(), values(), items() methods to specify that scanning should be inclusive of the
end key.
btree.DESC
A flag for keys(), values(), items() methods to specify that scanning should be in descending
direction of keys.
framebuf — frame buffer manipulation
This module provides a general frame buffer which can be used to create bitmap images, which can then be sent
to a display.
class FrameBuffer
The FrameBuffer class provides a pixel buffer which can be drawn upon with pixels, lines, rectangles, text and
even other FrameBuffer’s. It is useful when generating output for displays.
For example:
import framebuf
fbuf.fill(0)
fbuf.text('MicroPython!', 0, 0, 0xffff)
fbuf.hline(0, 10, 96, 0xffff)
Constructors
class framebuf.FrameBuffer(buffer, width, height, format, stride=width, /)
• buffer is an object with a buffer protocol which must be large enough to contain every
pixel defined by the width, height and format of the FrameBuffer.
• format specifies the type of pixel used in the FrameBuffer; permissible values are
listed under Constants below. These set the number of bits used to encode a color
value and the layout of these bits in buffer. Where a color value c is passed to a
method, c is a small integer with an encoding that is dependent on the format of the
FrameBuffer.
• stride is the number of pixels between each horizontal line of pixels in the
FrameBuffer. This defaults to width but may need adjustments when implementing a
FrameBuffer within another larger FrameBuffer or screen. The buffer size must
accommodate an increased step size.
One must specify valid buffer, width, height, format and optionally stride. Invalid buffer size
or dimensions may lead to unexpected errors.
If c is not given, get the color value of the specified pixel. If c is given, set the specified pixel to the given
color.
FrameBuffer.hline(x, y, w, c)
FrameBuffer.vline(x, y, h, c)
Draw a line from a set of coordinates using the given color and a thickness of 1 pixel. The line method
draws the line up to a second set of coordinates whereas the hline and vline methods draw horizontal
and vertical lines respectively up to a given length.
FrameBuffer.rect(x, y, w, h, c)
FrameBuffer.fill_rect(x, y, w, h, c)
Draw a rectangle at the given location, size and color. The rect method draws only a 1 pixel outline
whereas the fill_rect method draws both the outline and interior.
Drawing text
FrameBuffer.text(s, x, y[, c])
Write text to the FrameBuffer using the the coordinates as the upper-left corner of the text. The color of
the text can be defined by the optional argument but is otherwise a default value of 1. All characters have
dimensions of 8x8 pixels and there is currently no way to change the font.
Other methods
FrameBuffer.scroll(xstep, ystep)
Shift the contents of the FrameBuffer by the given vector. This may leave a footprint of the previous
colors in the FrameBuffer.
Draw another FrameBuffer on top of the current one at the given coordinates. If key is specified then it
should be a color integer and the corresponding color will be considered transparent: all pixels with that
color value will not be drawn.
This method works between FrameBuffer instances utilising different formats, but the resulting colors
may be unexpected due to the mismatch in color formats.
Constants
framebuf.MONO_VLSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are vertically mapped
with bit 0 being nearest the top of the screen. Consequently each byte occupies 8 vertical pixels.
Subsequent bytes appear at successive horizontal locations until the rightmost edge is reached. Further
bytes are rendered at locations starting at the leftmost edge, 8 pixels lower.
framebuf.MONO_HLSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are horizontally
mapped. Each byte occupies 8 horizontal pixels with bit 7 being the leftmost. Subsequent bytes appear at
successive horizontal locations until the rightmost edge is reached. Further bytes are rendered on the next
row, one pixel lower.
framebuf.MONO_HMSB
Monochrome (1-bit) color format This defines a mapping where the bits in a byte are horizontally
mapped. Each byte occupies 8 horizontal pixels with bit 0 being the leftmost. Subsequent bytes appear at
successive horizontal locations until the rightmost edge is reached. Further bytes are rendered on the next
row, one pixel lower.
framebuf.RGB565
framebuf.GS2_HMSB
framebuf.GS4_HMSB
framebuf.GS8
Resets the device in a manner similar to pushing the external RESET button.
machine.soft_reset()
Performs a soft reset of the interpreter, deleting all Python objects and resetting the Python heap. It tries to
retain the method by which the user is connected to the MicroPython REPL (eg serial, USB, Wifi).
machine.reset_cause()
Get the reset cause. See constants for the possible return values.
Disable interrupt requests. Returns the previous IRQ state which should be considered an opaque value.
This return value should be passed to the enable_irq() function to restore interrupts to their original
state, before disable_irq() was called.
machine.enable_irq(state)
Re-enable interrupt requests. The state parameter should be the value that was returned from the most
recent call to the disable_irq() function.
machine.idle()
Gates the clock to the CPU, useful to reduce power consumption at any time during short or long periods.
Peripherals continue working and execution resumes as soon as any interrupt is triggered (on many ports
this includes system timer interrupt occurring at regular intervals on the order of millisecond).
machine.sleep()
Note
This function is deprecated, use lightsleep() instead with no arguments.
machine.lightsleep([time_ms])
machine.deepsleep([time_ms])
If time_ms is specified then this will be the maximum time in milliseconds that the sleep will last for.
Otherwise the sleep can last indefinitely.
With or without a timeout, execution may resume at any time if there are events that require processing.
Such events, or wake sources, should be configured before sleeping, like Pin change or RTC timeout.
The precise behaviour and power-saving capabilities of lightsleep and deepsleep is highly dependent on
the underlying hardware, but the general properties are:
• A lightsleep has full RAM and state retention. Upon wake execution is resumed from the point
where the sleep was requested, with all subsystems operational.
• A deepsleep may not retain RAM or any other state of the system (for example peripherals or
network interfaces). Upon wake execution is resumed from the main script, similar to a hard or
power-on reset. The reset_cause() function will return machine.DEEPSLEEP and this can
be used to distinguish a deepsleep wake from other resets.
machine.wake_reason()
Get the wake reason. See constants for the possible return values.
Miscellaneous functions
machine.unique_id()
Returns a byte string with a unique identifier of a board/SoC. It will vary from a board/SoC instance to
another, if underlying hardware allows. Length varies by hardware (so use substring of a full value if you
expect a short ID). In some MicroPython ports, ID corresponds to the network MAC address.
Time a pulse on the given pin, and return the duration of the pulse in microseconds. The pulse_level
argument should be 0 to time a low pulse or 1 to time a high pulse.
If the current input value of the pin is different to pulse_level, the function first (*) waits until the pin
input becomes equal to pulse_level, then (**) times the duration that the pin is equal to pulse_level. If the
pin is already equal to pulse_level then timing starts straight away.
The function will return -2 if there was timeout waiting for condition marked (*) above, and -1 if there
was timeout during the main measurement, marked (**) above. The timeout is the same for both cases
and given by timeout_us (which is in microseconds).
machine.rng()
Availability: WiPy.
Constants
machine.IDLE
machine.SLEEP
machine.DEEPSLEEP
machine.PWRON_RESET
machine.HARD_RESET
machine.WDT_RESET
machine.DEEPSLEEP_RESET
machine.SOFT_RESET
Reset causes.
machine.WLAN_WAKE
machine.PIN_WAKE
machine.RTC_WAKE
Wake-up reasons.
Classes
• class Pin – control I/O pins
• class Signal – control and sense external I/O devices
• class ADC – analog to digital conversion
• class UART – duplex serial communication bus
• class SPI – a Serial Peripheral Interface bus protocol (master side)
• class I2C – a two-wire serial protocol
• class RTC – real time clock
• class Timer – control hardware timers
• class WDT – watchdog timer
• class SD – secure digital memory card (cc3200 port only)
• class SDCard – secure digital memory card
class Pin – control I/O pins
A pin object is used to control I/O pins (also known as GPIO - general-purpose input/output). Pin objects are
commonly associated with a physical pin that can drive an output voltage and read input voltages. The pin class
has methods to set the mode of the pin (IN, OUT, etc) and methods to get and set the digital logic level. For
analog control of a pin, see the ADC class.
A pin object is constructed by using an identifier which unambiguously specifies a certain I/O pin. The allowed
forms of the identifier and the physical pin that the identifier maps to are port-specific. Possibilities for the
identifier are an integer, a string or a tuple with port and pin number.
Usage Model:
from machine import Pin
Constructors
class machine.Pin(id, mode=- 1, pull=- 1, *, value, drive, alt)
Access the pin peripheral (GPIO pin) associated with the given id. If additional arguments are given in
the constructor then they are used to initialise the pin. Any settings that are not specified will remain in
their previous state.
• id is mandatory and can be an arbitrary object. Among possible value types are: int
(an internal Pin identifier), str (a Pin name), and tuple (pair of [port, pin]).
• Pin.IN - Pin is configured for input. If viewed as an output the pin is in high-
impedance state.
• pull specifies if the pin has a (weak) pull resistor attached, and can be one of:
• value is valid only for Pin.OUT and Pin.OPEN_DRAIN modes and specifies initial
output pin value if given, otherwise the state of the pin peripheral remains unchanged.
• drive specifies the output power of the pin and can be one of: Pin.LOW_POWER,
Pin.MED_POWER or Pin.HIGH_POWER. The actual current driving capabilities are
port dependent. Not all ports implement this argument.
• alt specifies an alternate function for the pin and the values it can take are port
dependent. This argument is valid only for Pin.ALT and Pin.ALT_OPEN_DRAIN
modes. It may be used when a pin supports more than one alternate function. If only
one pin alternate function is supported the this argument is not required. Not all ports
implement this argument.
As specified above, the Pin class allows to set an alternate function for a particular pin, but it
does not specify any further operations on such a pin. Pins configured in alternate-function
mode are usually not used as GPIO but are instead driven by other hardware peripherals. The
only operation supported on such a pin is re-initialising, by calling the constructor or
Pin.init() method. If a pin that is configured in alternate-function mode is re-initialised
with Pin.IN, Pin.OUT, or Pin.OPEN_DRAIN, the alternate function will be removed
from the pin.
Methods
Pin.init(mode=- 1, pull=- 1, *, value, drive, alt)
Re-initialise the pin using the given parameters. Only those arguments that are specified will be set. The
rest of the pin peripheral state will remain unchanged. See the constructor documentation for details of the
arguments.
Returns None.
Pin.value([x])
This method allows to set and get the value of the pin, depending on whether the argument x is supplied
or not.
If the argument is omitted then this method gets the digital logic level of the pin, returning 0 or 1
corresponding to low and high voltage signals respectively. The behaviour of this method depends on the
mode of the pin:
• Pin.IN - The method returns the actual input value currently present on the pin.
• Pin.OPEN_DRAIN - If the pin is in state ‘0’ then the behaviour and return value of
the method is undefined. Otherwise, if the pin is in state ‘1’, the method returns the
actual input value currently present on the pin.
If the argument is supplied then this method sets the digital logic level of the pin. The
argument x can be anything that converts to a boolean. If it converts to True, the pin is set to
state ‘1’, otherwise it is set to state ‘0’. The behaviour of this method depends on the mode of
the pin:
• Pin.IN - The value is stored in the output buffer for the pin. The pin state does not
change, it remains in the high-impedance state. The stored value will become active on
the pin as soon as it is changed to Pin.OUT or Pin.OPEN_DRAIN mode.
• Pin.OPEN_DRAIN - If the value is ‘0’ the pin is set to a low voltage state. Otherwise
the pin is set to high-impedance state.
Pin.__call__([x])
Pin objects are callable. The call method provides a (fast) shortcut to set and get the value of the pin. It is
equivalent to Pin.value([x]). See Pin.value() for more details.
Pin.on()
Pin.off()
Configure an interrupt handler to be called when the trigger source of the pin is active. If the pin mode is
Pin.IN then the trigger source is the external value on the pin. If the pin mode is Pin.OUT then the
trigger source is the output buffer of the pin. Otherwise, if the pin mode is Pin.OPEN_DRAIN then the
trigger source is the output buffer for state ‘0’ and the external pin value for state ‘1’.
• handler is an optional function to be called when the interrupt triggers. The handler
must take exactly one argument which is the Pin instance.
• trigger configures the event which can generate an interrupt. Possible values are:
• Pin.IRQ_FALLING interrupt on falling edge.
• priority sets the priority level of the interrupt. The values it can take are port-
specific, but higher values always represent higher priorities.
• wake selects the power mode in which this interrupt can wake up the system. It can be
machine.IDLE, machine.SLEEP or machine.DEEPSLEEP. These values can
also be OR’ed together to make a pin generate interrupts in more than one power
mode.
• hard if true a hardware interrupt is used. This reduces the delay between the pin
change and the handler being called. Hard interrupt handlers may not allocate
memory; see Writing interrupt handlers. Not all ports support this argument.
The following methods are not part of the core Pin API and only implemented on certain ports.
Pin.low()
Pin.high()
Pin.mode([mode])
Get or set the pin mode. See the constructor documentation for details of the mode argument.
Pin.pull([pull])
Get or set the pin pull state. See the constructor documentation for details of the pull argument.
Pin.drive([drive])
Get or set the pin drive strength. See the constructor documentation for details of the drive argument.
Pin.PULL_UP
Pin.PULL_DOWN
Pin.PULL_HOLD
Selects whether there is a pull up/down resistor. Use the value None for no pull.
Pin.LOW_POWER
Pin.MED_POWER
Pin.HIGH_POWER
Pin.IRQ_FALLING
Pin.IRQ_RISING
Pin.IRQ_LOW_LEVEL
Pin.IRQ_HIGH_LEVEL
# Now to light up both of them using Pin class, you'll need to set
# them to different values
led1_pin.value(1)
led2_pin.value(0)
# Even better:
led1.on()
led2.on()
• By wrapping existing Pin object - universal method which works for any board.
• By passing required Pin parameters directly to Signal constructor, skipping the need to create
intermediate Pin object. Available on many, but not all boards.
Methods
Signal.value([x])
This method allows to set and get the value of the signal, depending on whether the argument x is
supplied or not.
If the argument is omitted then this method gets the signal level, 1 meaning signal is asserted (active) and
0 - signal inactive.
If the argument is supplied then this method sets the signal level. The argument x can be anything that
converts to a boolean. If it converts to True, the signal is active, otherwise it is inactive.
Correspondence between signal being active and actual logic level on the underlying pin depends on
whether signal is inverted (active-low) or not. For non-inverted signal, active status corresponds to logical
1, inactive - to logical 0. For inverted/active-low signal, active status corresponds to logical 0, while
inactive - to logical 1.
Signal.on()
Activate signal.
Signal.off()
Deactivate signal.
class ADC – analog to digital conversion
The ADC class provides an interface to analog-to-digital convertors, and represents a single endpoint that can
sample a continuous voltage and convert it to a discretised value.
Example usage:
import machine
Constructors
class machine.ADC(id)
Access the ADC associated with a source identified by id. This id may be an integer (usually specifying a
channel number), a Pin object, or other value supported by the underlying machine.
Methods
ADC.read_u16()
Take an analog reading and return an integer in the range 0-65535. The return value represents the raw
reading taken by the ADC, scaled such that the minimum value is 0 and the maximum value is 65535.
class UART – duplex serial communication bus
UART implements the standard UART/USART duplex serial communications protocol. At the physical level it
consists of 2 lines: RX and TX. The unit of communication is a character (not to be confused with a string
character) which can be 8 or 9 bits wide.
UART objects can be created and initialised using:
from machine import UART
Constructors
class machine.UART(id, ...)
Methods
UART.init(baudrate=9600, bits=8, parity=None, stop=1, *, ...)
• timeout specifies the time to wait for the first character (in ms).
• pins is a 4 or 2 item list indicating the TX, RX, RTS and CTS pins (in that order). Any
of the pins can be None if one wants the UART to operate with limited functionality. If
the RTS pin is given the the RX pin must be given as well. The same applies to CTS.
When no pins are given, then the default set of TX and RX pins is taken, and hardware
flow control will be disabled. If pins is None, no pin assignment will be made.
UART.deinit()
UART.any()
Returns an integer counting the number of characters that can be read without blocking. It will return 0 if
there are no characters available and a positive number if there are characters. The method may return 1
even if there is more than one character available for reading.
poll = select.poll()
poll.register(uart, select.POLLIN)
poll.poll(timeout)
UART.read([nbytes])
Read characters. If nbytes is specified then read at most that many bytes, otherwise read as much data
as possible. It may return sooner if a timeout is reached. The timeout is configurable in the constructor.
Return value: a bytes object containing the bytes read in. Returns None on timeout.
UART.readinto(buf[, nbytes])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at
most len(buf) bytes. It may return sooner if a timeout is reached. The timeout is configurable in the
constructor.
Return value: number of bytes read and stored into buf or None on timeout.
UART.readline()
Read a line, ending in a newline character. It may return sooner if a timeout is reached. The timeout is
configurable in the constructor.
UART.write(buf)
Write the buffer of bytes to the bus.
UART.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration longer than required for a
normal transmission of a character.
• priority level of the interrupt. Can take values in the range 1-7. Higher values
represent higher priorities.
Note
The handler will be called whenever any of the following two conditions are met:
• At least 1 new character is waiting in the Rx buffer and the Rx line has been silent for
the duration of 1 complete frame.
This means that when the handler function is called there will be between 1 to 8 characters
waiting.
Availability: WiPy.
Constants
UART.RX_ANY
Availability: WiPy.
class SPI – a Serial Peripheral Interface bus
protocol (master side)
SPI is a synchronous serial protocol that is driven by a master. At the physical level, a bus consists of 3 lines:
SCK, MOSI, MISO. Multiple devices can share the same bus. Each device should have a separate, 4th signal,
SS (Slave Select), to select a particular device on a bus with which communication takes place. Management of
an SS signal should happen in user code (via machine.Pin class).
Both hardware and software SPI implementations exist via the machine.SPI and machine.SoftSPI classes.
Hardware SPI uses underlying hardware support of the system to perform the reads/writes and is usually
efficient and fast but may have restrictions on which pins can be used. Software SPI is implemented by bit-
banging and can be used on any pin but is not as efficient. These classes have the same methods available and
differ primarily in the way they are constructed.
Constructors
class machine.SPI(id, ...)
Construct an SPI object on the given bus, id. Values of id depend on a particular port and its hardware.
Values 0, 1, etc. are commonly used to select hardware SPI block #0, #1, etc.
With no additional parameters, the SPI object is created but not initialised (it has the settings from the last
initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See init for
parameters of initialisation.
Construct a new software SPI object. Additional parameters must be given, usually at least sck, mosi and
miso, and these are used to initialise the bus. See SPI.init for a description of the parameters.
Methods
SPI.init(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None,
miso=None, pins=SCK, MOSI, MISO)
• polarity can be 0 or 1, and is the level the idle clock line sits at.
• phase can be 0 or 1 to sample data on the first or second clock edge respectively.
• bits is the width in bits of each transfer. Only 8 is guaranteed to be supported by all
hardware.
• sck, mosi, miso are pins (machine.Pin) objects to use for bus signals. For most
hardware SPI blocks (as selected by id parameter to the constructor), pins are fixed
and cannot be changed. In some cases, hardware blocks allow 2-3 alternative pin sets
for a hardware SPI block. Arbitrary pin assignments are possible only for a bitbanging
SPI driver (id = -1).
• pins - WiPy port doesn’t sck, mosi, miso arguments, and instead allows to specify
them as a tuple of pins parameter.
In the case of hardware SPI the actual clock frequency may be lower than the requested
baudrate. This is dependant on the platform hardware. The actual rate may be determined by
printing the SPI object.
SPI.deinit()
SPI.read(nbytes, write=0)
Read a number of bytes specified by nbytes while continuously writing the single byte given by
write. Returns a bytes object with the data that was read.
SPI.readinto(buf, write=0)
Read into the buffer specified by buf while continuously writing the single byte given by write.
Returns None.
SPI.write(buf)
SPI.write_readinto(write_buf, read_buf)
Write the bytes from write_buf while reading into read_buf. The buffers can be the same or
different, but both buffers must have the same length. Returns None.
Constants
SPI.MASTER
for initialising the SPI bus to master; this is only used for the WiPy
SPI.MSB
SPI.LSB
Constructors
class machine.I2C(id, *, scl, sda, freq=400000)
Construct and return a new I2C object using the following parameters:
• id identifies a particular I2C peripheral. Allowed values for depend on the particular
port/board
• scl should be a pin object specifying the pin to use for SCL.
• sda should be a pin object specifying the pin to use for SDA.
• freq should be an integer which sets the maximum frequency for SCL.
Note that some ports/boards will have default values of scl and sda that can be changed in this
constructor. Others will have fixed values of scl and sda that cannot be changed.
• scl should be a pin object specifying the pin to use for SCL.
• sda should be a pin object specifying the pin to use for SDA.
• freq should be an integer which sets the maximum frequency for SCL.
• timeout is the maximum time in microseconds to wait for clock stretching (SCL held
low by another device on the bus), after which an OSError(ETIMEDOUT)
exception is raised.
General Methods
I2C.init(scl, sda, *, freq=400000)
I2C.deinit()
Availability: WiPy.
I2C.scan()
Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of those that respond. A device
responds if it pulls the SDA line low after its address (including a write bit) is sent on the bus.
I2C.start()
Generate a START condition on the bus (SDA transitions to low while SCL is high).
I2C.stop()
Generate a STOP condition on the bus (SDA transitions to high while SCL is high).
I2C.readinto(buf, nack=True, /)
Reads bytes from the bus and stores them into buf. The number of bytes read is the length of buf. An ACK
will be sent on the bus after receiving all but the last byte. After the last byte is received, if nack is true
then a NACK will be sent, otherwise an ACK will be sent (and in this case the slave assumes more bytes
are going to be read in a later call).
I2C.write(buf)
Write the bytes from buf to the bus. Checks that an ACK is received after each byte and stops transmitting
the remaining bytes if a NACK is received. The function returns the number of ACKs that were received.
Read nbytes from the slave specified by addr. If stop is true then a STOP condition is generated at the end
of the transfer. Returns a bytes object with the data read.
Read into buf from the slave specified by addr. The number of bytes read will be the length of buf. If stop
is true then a STOP condition is generated at the end of the transfer.
Write the bytes from buf to the slave specified by addr. If a NACK is received following the write of a
byte from buf then the remaining bytes are not sent. If stop is true then a STOP condition is generated at
the end of the transfer, even if a NACK is received. The function returns the number of ACKs that were
received.
Write the bytes contained in vector to the slave specified by addr. vector should be a tuple or list of
objects with the buffer protocol. The addr is sent once and then the bytes from each object in vector are
written out sequentially. The objects in vector may be zero bytes in length in which case they don’t
contribute to the output.
If a NACK is received following the write of a byte from one of the objects in vector then the remaining
bytes, and any remaining objects, are not sent. If stop is true then a STOP condition is generated at the
end of the transfer, even if a NACK is received. The function returns the number of ACKs that were
received.
Memory operations
Some I2C devices act as a memory device (or set of registers) that can be read from and written to. In this case
there are two addresses associated with an I2C transaction: the slave address and the memory address. The
following methods are convenience functions to communicate with such devices.
I2C.readfrom_mem(addr, memaddr, nbytes, *, addrsize=8)
Read nbytes from the slave specified by addr starting from the memory address specified by memaddr.
The argument addrsize specifies the address size in bits. Returns a bytes object with the data read.
Write buf to the slave specified by addr starting from the memory address specified by memaddr. The
argument addrsize specifies the address size in bits (on ESP8266 this argument is not recognised and the
address size is always 8 bits).
Constructors
class machine.RTC(id=0, ...)
Methods
RTC.init(datetime)
RTC.now()
RTC.deinit()
Resets the RTC to the time of January 1, 2015 and starts running it again.
RTC.alarm_left(alarm_id=0)
RTC.cancel(alarm_id=0)
• wake specifies the sleep mode from where this interrupt can wake up the system.
Constants
RTC.ALARM0
Constructors
class machine.Timer(id, ...)
Construct a new timer object of the given id. Id of -1 constructs a virtual timer (if supported by a board).
Methods
Timer.init(*, mode=Timer.PERIODIC, period=- 1, callback=None)
Keyword arguments:
• Timer.ONE_SHOT - The timer runs once until the configured period of the
channel expires.
Timer.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
Constants
Timer.ONE_SHOT
Timer.PERIODIC
Constructors
class machine.WDT(id=0, timeout=5000)
Create a WDT object and start it. The timeout must be given in milliseconds. Once it is running the
timeout cannot be changed and the WDT cannot be stopped either.
Notes: On the esp32 the minimum timeout is 1 second. On the esp8266 a timeout cannot be specified, it is
determined by the underlying system.
Methods
wdt.feed()
Feed the WDT to prevent it from resetting the system. The application should place this call in a sensible
place ensuring that the WDT is only fed after verifying that everything is functioning correctly.
class SD – secure digital memory card (cc3200 port
only)
Warning
This is a non-standard class and is only available on the cc3200 port.
The SD card class allows to configure and enable the memory card module of the WiPy and automatically
mount it as /sd as part of the file system. There are several pin combinations that can be used to wire the SD
card socket to the WiPy and the pins used can be specified in the constructor. Please check the pinout and
alternate functions table. for more info regarding the pins which can be remapped to be used with a SD card.
Example usage:
from machine import SD
import os
# clk cmd and dat0 pins must be passed along with
# their respective alternate functions
sd = machine.SD(pins=('GP10', 'GP11', 'GP15'))
os.mount(sd, '/sd')
# do normal file operations
Constructors
class machine.SD(id, ...)
Methods
SD.init(id=0, pins='GP10', 'GP11', 'GP15')
Enable the SD card. In order to initialize the card, give it a 3-tuple: (clk_pin, cmd_pin,
dat0_pin).
SD.deinit()
Both SD and MMC interfaces support being accessed with a variety of bus widths. When being accessed with a
1-bit wide interface they can be accessed using the SPI protocol. Different MicroPython hardware platforms
support different widths and pin configurations but for most platforms there is a standard configuration for any
given hardware. In general constructing an SDCard object with without passing any parameters will initialise
the interface to the default card slot for the current hardware. The arguments listed below represent the common
arguments that might need to be set in order to use either a non-standard slot or a non-standard pin assignment.
The exact subset of arguments supported will vary from platform to platform.
class machine.SDCard(slot=1, width=1, cd=None, wp=None, sck=None, miso=None, mosi=None,
cs=None, freq=20000000)
This class provides access to SD or MMC storage cards using either a dedicated SD/MMC interface
hardware or through an SPI channel. The class implements the block protocol defined by
uos.AbstractBlockDev. This allows the mounting of an SD card to be as simple as:
uos.mount(machine.SDCard(), "/sd")
• slot selects which of the available interfaces to use. Leaving this unset will select the
default interface.
• freq selects the SD/MMC interface frequency in Hz (only supported on the ESP32).
Implementation-specific details
Different implementations of the SDCard class on different hardware support varying subsets of the options
above.
PyBoard
The standard PyBoard has just one slot. No arguments are necessary or supported.
ESP32
The ESP32 provides two channels of SD/MMC hardware and also supports access to SD Cards through either
of the two SPI ports that are generally available to the user. As a result the slot argument can take a value
between 0 and 3, inclusive. Slots 0 and 1 use the built-in SD/MMC hardware while slots 2 and 3 use the SPI
ports. Slot 0 supports 1, 4 or 8-bit wide access while slot 1 supports 1 or 4-bit access; the SPI slots only support
1-bit access.
Note
Slot 0 is used to communicate with on-board flash memory on most ESP32 modules and so will be
unavailable to the user.
Note
Most ESP32 modules that provide an SD card slot using the dedicated hardware only wire up 1 data
pin, so the default value for width is 1.
The pins used by the dedicated SD/MMC hardware are fixed. The pins used by the SPI hardware can be
reassigned.
Note
If any of the SPI signals are remapped then all of the SPI signals will pass through a GPIO
multiplexer unit which can limit the performance of high frequency signals. Since the normal
operating speed for SD cards is 40MHz this can cause problems on some cards.
Slot 0 1 2 3
sck 6 14 18 14
cmd 11 15
cs 5 15
miso 19 12
mosi 23 13
D0 7 2
D1 8 4
D2 9 12
D3 10 13
D4 16
Slot 0 1 2 3
D5 17
D6 5
D7 18
cc3200
You can set the pins used for SPI access by passing a tuple as the pins argument.
Note: The current cc3200 SD card implementation names the this class machine.SD rather than
machine.SDCard .
micropython – access and control MicroPython
internals
Functions
micropython.const(expr)
Used to declare that the expression is a constant so that the compile can optimise it. The use of this
function should be as follows:
CONST_X = const(123)
CONST_Y = const(2 * CONST_X + 1)
Constants declared this way are still accessible as global variables from outside the module they are
declared in. On the other hand, if a constant begins with an underscore then it is hidden, it is not available
as a global variable, and does not take up any memory during execution.
This const function is recognised directly by the MicroPython parser and is provided as part of the
micropython module mainly so that scripts can be written which run under both CPython and
MicroPython, by following the above pattern.
micropython.opt_level([level])
If level is given then this function sets the optimisation level for subsequent compilation of scripts, and
returns None. Otherwise it returns the current optimisation level.
• Assertions: at level 0 assertion statements are enabled and compiled into the bytecode; at levels 1
and higher assertions are not compiled.
• Built-in __debug__ variable: at level 0 this variable expands to True; at levels 1 and higher it
expands to False.
• Source-code line numbers: at levels 0, 1 and 2 source-code line number are stored along with the
bytecode so that exceptions can report the line number they occurred at; at levels 3 and higher line
numbers are not stored.
micropython.alloc_emergency_exception_buf(size)
Allocate size bytes of RAM for the emergency exception buffer (a good size is around 100 bytes). The
buffer is used to create exceptions in cases when normal RAM allocation would fail (eg within an
interrupt handler) and therefore give useful traceback information in these situations.
A good way to use this function is to put it at the start of your main script (eg boot.py or main.py)
and then the emergency exception buffer will be active for all the code following it.
micropython.mem_info([verbose])
Print information about currently used memory. If the verbose argument is given then extra information is
printed.
The information that is printed is implementation dependent, but currently includes the amount of stack
and heap used. In verbose mode it prints out the entire heap indicating which blocks are used and which
are free.
micropython.qstr_info([verbose])
Print information about currently interned strings. If the verbose argument is given then extra information
is printed.
The information that is printed is implementation dependent, but currently includes the number of
interned strings and the amount of RAM they use. In verbose mode it prints out the names of all RAM-
interned strings.
micropython.stack_use()
Return an integer representing the current amount of stack that is being used. The absolute value of this is
not particularly useful, rather it should be used to compute differences in stack usage at different points.
micropython.heap_lock()
micropython.heap_unlock()
micropython.heap_locked()
Lock or unlock the heap. When locked no memory allocation can occur and a MemoryError will be
raised if any heap allocation is attempted. heap_locked() returns a true value if the heap is currently
locked.
These functions can be nested, ie heap_lock() can be called multiple times in a row and the lock-
depth will increase, and then heap_unlock() must be called the same number of times to make the
heap available again.
Both heap_unlock() and heap_locked() return the current lock depth (after unlocking for the
former) as a non-negative integer, with 0 meaning the heap is not locked.
If the REPL becomes active with the heap locked then it will be forcefully unlocked.
micropython.kbd_intr(chr)
Set the character that will raise a KeyboardInterrupt exception. By default this is set to 3 during
script execution, corresponding to Ctrl-C. Passing -1 to this function will disable capture of Ctrl-C, and
passing 3 will restore it.
This function can be used to prevent the capturing of Ctrl-C on the incoming stream of characters that is
usually used for the REPL, in case that stream is used for other purposes.
micropython.schedule(func, arg)
Schedule the function func to be executed “very soon”. The function is passed the value arg as its single
argument. “Very soon” means that the MicroPython runtime will do its best to execute the function at the
earliest possible time, given that it is also trying to be efficient, and that the following conditions hold:
• Scheduled functions are always executed “between opcodes” which means that all fundamental
Python operations (such as appending to a list) are guaranteed to be atomic.
• A given port may define “critical regions” within which scheduled functions will never be
executed. Functions may be scheduled within a critical region but they will not be executed until
that region is exited. An example of a critical region is a preempting interrupt handler (an IRQ).
A use for this function is to schedule a callback from a preempting IRQ. Such an IRQ puts restrictions on
the code that runs in the IRQ (for example the heap may be locked) and scheduling a function to call later
will lift those restrictions.
Note: If schedule() is called from a preempting IRQ, when memory allocation is not allowed and the
callback to be passed to schedule() is a bound method, passing this directly will fail. This is because
creating a reference to a bound method causes memory allocation. A solution is to create a reference to
the method in the class constructor and to pass that reference to schedule(). This is discussed in detail
here reference documentation under “Creation of Python objects”.
There is a finite queue to hold the scheduled functions and schedule() will raise a RuntimeError
if the queue is full.
network — network configuration
This module provides network drivers and routing configuration. To use this module, a MicroPython
variant/build with network capabilities must be installed. Network drivers for specific hardware are available
within this module and are used to configure hardware network interface(s). Network services provided by
configured interfaces are then available for use via the usocket module.
For example:
# connect/ show IP config a specific network interface
# see below for examples of specific drivers
import network
import utime
nic = network.Driver(...)
if not nic.isconnected():
nic.connect()
print("Waiting for connection...")
while not nic.isconnected():
utime.sleep(1)
print(nic.ifconfig())
Instantiate a network interface object. Parameters are network interface dependent. If there are more than one
interface of the same type, the first parameter should be id.
AbstractNIC.active([is_active])
Activate (“up”) or deactivate (“down”) the network interface, if a boolean argument is passed. Otherwise,
query current state if no argument is provided. Most other methods require an active interface (behavior
of calling them on inactive interface is undefined).
Connect the interface to a network. This method is optional, and available only for interfaces which are
not “always connected”. If no parameters are given, connect to the default (or the only) service. If a single
parameter is given, it is the primary identifier of a service to connect to. It may be accompanied by a key
(password) required to access said service. There can be further arbitrary keyword-only parameters,
depending on the networking medium type and/or particular device. Parameters can be used to: a) specify
alternative service identifier types; b) provide additional connection parameters. For various medium
types, there are different sets of predefined/recommended parameters, among them:
• WiFi: bssid keyword to connect to a specific BSSID (MAC address)
AbstractNIC.disconnect()
AbstractNIC.isconnected()
AbstractNIC.scan(*, ...)
Scan for the available network services/connections. Returns a list of tuples with discovered service
parameters. For various network media, there are different variants of predefined/ recommended tuple
formats, among them:
• WiFi: (ssid, bssid, channel, RSSI, authmode, hidden). There may be further fields, specific to a
particular device.
The function may accept additional keyword arguments to filter scan results (e.g. scan for a particular
service, on a particular channel, for services of a particular set, etc.), and to affect scan duration and other
parameters. Where possible, parameter names should match those in connect().
AbstractNIC.status([param])
Query dynamic status information of the interface. When called with no argument the return value
describes the network link status. Otherwise param should be a string naming the particular status
parameter to retrieve.
The return types and values are dependent on the network medium/technology. Some of the parameters
that may be supported are:
• WiFi AP: use 'stations' to retrieve a list of all the STAs connected to the AP. The list
contains tuples of the form (MAC, RSSI).
Get/set IP-level network interface parameters: IP address, subnet mask, gateway and DNS server. When
called with no arguments, this method returns a 4-tuple with the above information. To set the above
values, pass a 4-tuple with the required information. For example:
AbstractNIC.config('param')
AbstractNIC.config(param=value, ...)
Get or set general network interface parameters. These methods allow to work with additional parameters
beyond standard IP configuration (as dealt with by ifconfig()). These include network-specific and
hardware-specific parameters. For setting parameters, the keyword argument syntax should be used, and
multiple parameters can be set at once. For querying, a parameter name should be quoted as a string, and
only one parameter can be queried at a time:
# Set WiFi access point name (formally known as ESSID) and WiFi channel
ap.config(essid='My AP', channel=11)
# Query params one by one
print(ap.config('essid'))
print(ap.config('channel'))
Network functions
The following are functions available in the network module.
network.phy_mode([mode])
If the mode parameter is provided, sets the mode to its value. If the function is called without parameters,
returns the current mode.
Availability: ESP8266.
class WLAN – control built-in WiFi interfaces
This class provides a driver for WiFi network processors. Example usage:
import network
# enable station interface and connect to WiFi access point
nic = network.WLAN(network.STA_IF)
nic.active(True)
nic.connect('your-ssid', 'your-password')
# now use sockets as usual
Constructors
class network.WLAN(interface_id)
Create a WLAN network interface object. Supported interfaces are network.STA_IF (station aka client,
connects to upstream WiFi access points) and network.AP_IF (access point, allows other WiFi clients to
connect). Availability of the methods below depends on interface type. For example, only STA interface may
WLAN.connect() to an access point.
Methods
WLAN.active([is_active])
Activate (“up”) or deactivate (“down”) network interface, if boolean argument is passed. Otherwise,
query current state if no argument is provided. Most other methods require active interface.
Connect to the specified wireless network, using the specified password. If bssid is given then the
connection will be restricted to the access-point with that MAC address (the ssid must also be specified in
this case).
WLAN.disconnect()
WLAN.scan()
Scanning is only possible on STA interface. Returns list of tuples with the information about WiFi access
points:
bssid is hardware address of an access point, in binary form, returned as bytes object. You can use
ubinascii.hexlify() to convert it to ASCII form.
• 0 – open
• 1 – WEP
• 2 – WPA-PSK
• 3 – WPA2-PSK
• 4 – WPA/WPA2-PSK
• 0 – visible
• 1 – hidden
WLAN.status([param])
When called with no argument the return value describes the network link status. The possible statuses
are defined as constants:
When called with one argument param should be a string naming the status parameter to
retrieve. Supported parameters in WiFI STA mode are: 'rssi'.
WLAN.isconnected()
In case of STA mode, returns True if connected to a WiFi access point and has a valid IP address. In AP
mode returns True when a station is connected. Returns False otherwise.
Get/set IP-level network interface parameters: IP address, subnet mask, gateway and DNS server. When
called with no arguments, this method returns a 4-tuple with the above information. To set the above
values, pass a 4-tuple with the required information. For example:
WLAN.config('param')
WLAN.config(param=value, ...)
Get or set general network interface parameters. These methods allow to work with additional parameters
beyond standard IP configuration (as dealt with by WLAN.ifconfig()). These include network-
specific and hardware-specific parameters. For setting parameters, keyword argument syntax should be
used, multiple parameters can be set at once. For querying, parameters name should be quoted as a string,
and only one parameter can be queries at time:
# Set WiFi access point name (formally known as ESSID) and WiFi channel
ap.config(essid='My AP', channel=11)
# Query params one by one
print(ap.config('essid'))
print(ap.config('channel'))
Following are commonly supported parameters (availability of a specific parameter depends on network
technology type, driver, and MicroPython port).
Parameter Description
Constructors
class network.WLANWiPy(id=0, ...)
Create a WLAN object, and optionally configure it. See init() for params of configuration.
Note
The WLAN constructor is special in the sense that if no arguments besides the id are given, it will return the
already existing WLAN instance without re-configuring it. This is because WLAN is a system feature of the WiPy.
If the already existing instance is not initialized it will do the same as the other constructors an will initialize it
with default values.
Methods
WLANWiPy.init(mode, *, ssid, auth, channel, antenna)
Arguments are:
• ssid is a string with the ssid name. Only needed when mode is WLAN.AP.
• auth is a tuple with (sec, key). Security can be None, WLAN.WEP, WLAN.WPA or
WLAN.WPA2. The key is a string with the network password. If sec is WLAN.WEP
the key must be a string representing hexadecimal values (e.g. ‘ABC1DE45BF’). Only
needed when mode is WLAN.AP.
• channel a number in the range 1-11. Only needed when mode is WLAN.AP.
• antenna selects between the internal and the external antenna. Can be either
WLAN.INT_ANT or WLAN.EXT_ANT.
or:
# configure as an station
wlan.init(mode=WLAN.STA)
Connect to a WiFi access point using the given SSID, and other security parameters.
• auth is a tuple with (sec, key). Security can be None, WLAN.WEP, WLAN.WPA or
WLAN.WPA2. The key is a string with the network password. If sec is WLAN.WEP
the key must be a string representing hexadecimal values (e.g. ‘ABC1DE45BF’).
• bssid is the MAC address of the AP to connect to. Useful when there are several APs
with the same ssid.
• timeout is the maximum time in milliseconds to wait for the connection to succeed.
WLANWiPy.scan()
Performs a network scan and returns a list of named tuples with (ssid, bssid, sec, channel, rssi). Note that
channel is always None since this info is not provided by the WiPy.
WLANWiPy.disconnect()
WLANWiPy.isconnected()
In case of STA mode, returns True if connected to a WiFi access point and has a valid IP address. In AP
mode returns True when a station is connected, False otherwise.
if 'dhcp' is passed as a parameter then the DHCP client is enabled and the IP params are negotiated
with the AP.
WLANWiPy.mode([mode])
WLANWiPy.auth([auth])
WLANWiPy.channel([channel])
WLANWiPy.antenna([antenna])
WLANWiPy.mac([mac_addr])
Get or set a 6-byte long bytes object with the MAC address.
Create a callback to be triggered when a WLAN event occurs during machine.SLEEP mode. Events
are triggered by socket activity or by WLAN connection/disconnection.
• handler is the function that gets called when the IRQ is triggered.
Constants
WLANWiPy.STA
WLANWiPy.AP
WLANWiPy.WEP
WLANWiPy.WPA
WLANWiPy.WPA2
WLANWiPy.INT_ANT
WLANWiPy.EXT_ANT
For this example to work the CC3000 module must have the following connections:
• MOSI connected to Y8
• MISO connected to Y7
• CLK connected to Y6
• CS connected to Y5
• VBEN connected to Y4
• IRQ connected to Y3
It is possible to use other SPI busses and other pins for CS, VBEN and IRQ.
Constructors
class network.CC3K(spi, pin_cs, pin_en, pin_irq)
Create a CC3K driver object, initialise the CC3000 module using the given SPI bus and pins, and return
the CC3K object.
Arguments are:
• spi is an SPI object which is the SPI bus that the CC3000 is connected to (the MOSI,
MISO and CLK pins).
All of these objects will be initialised by the driver, so there is no need to initialise them
yourself. For example, you can use:
Connect to a WiFi access point using the given SSID, and other security parameters.
CC3K.disconnect()
CC3K.isconnected()
Returns True if connected to a WiFi access point and has a valid IP address, False otherwise.
CC3K.ifconfig()
Returns a 7-tuple with (ip, subnet mask, gateway, DNS server, DHCP server, MAC address, SSID).
CC3K.patch_version()
CC3K.patch_program('pgm')
Upload the current firmware to the CC3000. You must pass ‘pgm’ as the first argument in order for the
upload to proceed.
Constants
CC3K.WEP
CC3K.WPA
CC3K.WPA2
For this example to work the WIZnet5x00 module must have the following connections:
• MOSI connected to X8
• MISO connected to X7
• SCLK connected to X6
• nSS connected to X5
• nRESET connected to X4
It is possible to use other SPI busses and other pins for nSS and nRESET.
Constructors
class network.WIZNET5K(spi, pin_cs, pin_rst)
Create a WIZNET5K driver object, initialise the WIZnet5x00 module using the given SPI bus and pins,
and return the WIZNET5K object.
Arguments are:
• spi is an SPI object which is the SPI bus that the WIZnet5x00 is connected to (the
MOSI, MISO and SCLK pins).
All of these objects will be initialised by the driver, so there is no need to initialise them
yourself. For example, you can use:
Returns True if the physical Ethernet link is connected and up. Returns False otherwise.
When called with no arguments, this method returns a 4-tuple with the above information.
To set the above values, pass a 4-tuple with the required information. For example:
WIZNET5K.regs()
class BLE
Constructor
class ubluetooth.BLE
Configuration
BLE.active([active, ]/)
Optionally changes the active state of the BLE radio, and returns the current state.
The radio must be made active before using any other methods on this class.
BLE.config('param', /)
BLE.config(*, param=value, ...)
Get or set configuration values of the BLE interface. To get a value the parameter name should be quoted
as a string, and just one parameter is queried at a time. To set values use the keyword syntax, and one ore
more parameter can be set at a time.
• 'mac': The current address in use, depending on the current address mode. This returns a tuple of
(addr_type, addr).
By default the interface mode will use a PUBLIC address if available, otherwise it will use a
RANDOM address.
• 'gap_name': Get/set the GAP device name used by service 0x1800, characteristic 0x2a00. This
can be set at any time and changed multiple times.
• 'rxbuf': Get/set the size in bytes of the internal buffer used to store incoming events. This
buffer is global to the entire BLE driver and so handles incoming data for all events, including all
characteristics. Increasing this allows better handling of bursty incoming data (for example scan
results) and the ability to receive larger characteristic values.
• 'mtu': Get/set the MTU that will be used during a ATT MTU exchange. The resulting MTU will
be the minimum of this and the remote device’s MTU. ATT MTU exchange will not happen
automatically (unless the remote device initiates it), and must be manually initiated with
gattc_exchange_mtu. Use the _IRQ_MTU_EXCHANGED event to discover the MTU for a
given connection.
• 'bond': Sets whether bonding will be enabled during pairing. When enabled, pairing requests
will set the “bond” flag and the keys will be stored by both devices.
_IO_CAPABILITY_DISPLAY_ONLY = const(0)
_IO_CAPABILITY_DISPLAY_YESNO = const(1)
_IO_CAPABILITY_KEYBOARD_ONLY = const(2)
_IO_CAPABILITY_NO_INPUT_OUTPUT = const(3)
_IO_CAPABILITY_KEYBOARD_DISPLAY = const(4)
• 'le_secure': Sets whether “LE Secure” pairing is required. Default is false (i.e. allow
“Legacy Pairing”).
Event Handling
BLE.irq(handler, /)
Registers a callback for events from the BLE stack. The handler takes two arguments, event (which will
be one of the codes below) and data (which is an event-specific tuple of values).
In order to save space in the firmware, these constants are not included on the ubluetooth module. Add the
ones that you need from the list above to your program.
Starts advertising at the specified interval (in microseconds). This interval will be rounded down to the
nearest 625us. To stop advertising, set interval_us to None.
adv_data and resp_data can be any type that implements the buffer protocol (e.g. bytes, bytearray,
str). adv_data is included in all broadcasts, and resp_data is send in reply to an active scan.
Note: if adv_data (or resp_data) is None, then the data passed to the previous call to gap_advertise
will be re-used. This allows a broadcaster to resume advertising with just
gap_advertise(interval_us). To clear the advertising payload pass an empty bytes, i.e. b''.
Run a scan operation lasting for the specified duration (in milliseconds).
Use interval_us and window_us to optionally configure the duty cycle. The scanner will run for
window_us microseconds every interval_us microseconds for a total of duration_ms milliseconds. 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).
• 0x01 - RANDOM (either static, RPA, or NRPA, the type is encoded in the address itself)
active can be set True if you want to receive scan responses in the results.
When scanning is stopped (either due to the duration finishing or when explicitly stopped), the
_IRQ_SCAN_DONE event will be raised.
Central Role
A central device can connect to peripherals that it has discovered using the observer role (see gap_scan) or
with a known address.
BLE.gap_connect(addr_type, addr, scan_duration_ms=2000, /)
Connect to a peripheral.
Peripheral Role
A peripheral device is expected to send connectable advertisements (see gap_advertise). It will usually be
acting as a GATT server, having first registered services and characteristics using
gatts_register_services.
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).
Returns False if the connection handle wasn’t connected, and True otherwise.
GATT Server
A GATT server has a set of registered services. Each service may contain characteristics, which each have a
value. Characteristics can also contain descriptors, which themselves have values.
These values are stored locally, and are accessed by their “value handle” which is generated during service
registration. They can also be read from or written to by a remote client device. Additionally, a server can
“notify” a characteristic to a connected client via a connection handle.
A device in either central or peripheral roles may function as a GATT server, however in most cases it will be
more common for a peripheral device to act as the server.
Characteristics and descriptors have a default maximum size of 20 bytes. Anything written to them by a client
will be truncated to this length. However, any local write will increase the maximum size, so if you want to
allow larger writes from a client to a given characteristic, use gatts_write after registration. e.g.
gatts_write(char_handle, bytes(100)).
BLE.gatts_register_services(services_definition, /)
Configures the server with the specified services, replacing any existing services.
services_definition is a list of services, where each service is a two-element tuple containing a UUID and
a list of characteristics.
Each characteristic is a two-or-three-element tuple containing a UUID, a flags value, and optionally a
list of descriptors.
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, gatts_write,
gatts_notify, and gatts_indicate.
_FLAG_AUX_WRITE = const(0x0100)
_FLAG_READ_ENCRYPTED = const(0x0200)
_FLAG_READ_AUTHENTICATED = const(0x0400)
_FLAG_READ_AUTHORIZED = const(0x0800)
_FLAG_WRITE_ENCRYPTED = const(0x1000)
_FLAG_WRITE_AUTHENTICATED = const(0x2000)
_FLAG_WRITE_AUTHORIZED = const(0x4000)
As for the IRQs above, any required constants should be added to your Python code.
BLE.gatts_read(value_handle, /)
Reads the local value for this handle (which has either been written by gatts_write or by a remote
client).
BLE.gatts_write(value_handle, data, /)
Writes the local value for this handle, which can be read by a client.
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.
Otherwise, if data is None, then the current local value (as set with gatts_write) will be sent.
BLE.gatts_indicate(conn_handle, value_handle, /)
Note: This does not currently support sending a custom value, it will always send the current local value
(as set with gatts_write).
Sets the internal buffer size for a value in bytes. This will limit the largest possible write that can be
received. The default is 20.
Setting append to True will make all remote writes append to, rather than replace, the current value. At
most len bytes can be buffered in this way. When you use gatts_read, the value will be cleared after
reading. This feature is useful when implementing something like the Nordic UART Service.
GATT Client
A GATT client can discover and read/write characteristics on a remote GATT server.
It is more common for a central role device to act as the GATT client, however it’s also possible for a peripheral
to act as a client in order to discover information about the central that has connected to it (e.g. to read the
device name from the device information service).
BLE.gattc_discover_services(conn_handle, uuid=None, /)
For each service discovered, the _IRQ_GATTC_SERVICE_RESULT event will be raised, followed by
_IRQ_GATTC_SERVICE_DONE on completion.
You can use start_handle=1, end_handle=0xffff to search for a characteristic in any service.
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.
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:
If a response is received from the remote server the _IRQ_GATTC_WRITE_DONE event will
be raised.
BLE.gattc_exchange_mtu(conn_handle, /)
Initiate MTU exchange with a connected server, using the preferred MTU set using
BLE.config(mtu=value).
Note: MTU exchange is typically initiated by the central. When using the BlueKitchen stack in the
central role, it does not support a remote peripheral initiating the MTU exchange. NimBLE works for
both roles.
L2CAP connection-oriented-channels
This feature allows for socket-like data exchange between two BLE devices. Once the devices are
connected via GAP, either device can listen for the other to connect on a numeric PSM
(Protocol/Service Multiplexer).
Note: This is currently only supported when using the NimBLE stack on STM32 and Unix (not
ESP32). Only one L2CAP channel may be active at a given time (i.e. you cannot connect while
listening).
Active L2CAP channels are identified by the connection handle that they were established on and a
CID (channel ID).
Connection-oriented channels have built-in credit-based flow control. Unlike ATT, where devices
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.
BLE.l2cap_listen(psm, mtu, /)
Start listening for incoming L2CAP channel requests on the specified psm with the local MTU set to mtu.
When a remote device initiates a connection, the _IRQ_L2CAP_ACCEPT event will be raised, which
gives the listening server a chance to reject the incoming connection (by returning a non-zero integer).
Once the connection is accepted, the _IRQ_L2CAP_CONNECT event will be raised, allowing the server
to obtain the channel id (CID) and the local and remote MTU.
Connect to a listening peer on the specified psm with local MTU set to mtu.
On successful connection, the the _IRQ_L2CAP_CONNECT event will be raised, allowing the client to
obtain the CID and the local and remote (peer) MTU.
An unsuccessful connection will raise the _IRQ_L2CAP_DISCONNECT event with a non-zero status.
BLE.l2cap_disconnect(conn_handle, cid, /)
Disconnect an active L2CAP channel with the specified conn_handle and cid.
Send the specified buf (which must support the buffer protocol) on the L2CAP channel identified by
conn_handle and cid.
The specified buffer cannot be larger than the remote (peer) MTU, and no more than twice the size of the
local MTU.
This will return False if the channel is now “stalled”, which means that l2cap_send must not be
called again until the _IRQ_L2CAP_SEND_READY event is received (which will happen when the
remote device grants more credits, typically after it has received and processed the data).
Receive data from the specified conn_handle and cid into the provided buf (which must support the buffer
protocol, e.g. bytearray or memoryview).
Note: After receiving the _IRQ_L2CAP_RECV event, the application should continue calling
l2cap_recvinto until no more bytes are available in the receive buffer (typically up to the size of the
remote (peer) MTU).
Until the receive buffer is empty, the remote device will not be granted more channel credits and will be
unable to send any more data.
Note: This is currently only supported when using the NimBLE stack on STM32 and Unix (not
ESP32).
BLE.gap_pair(conn_handle, /)
Before calling this, ensure that the io, mitm, le_secure, and bond configuration options are set (via
config).
The passkey is a numeric value and will depend on on the action (which will depend on what I/O
capability has been set):
class UUID
Constructor
class ubluetooth.UUID(value, /)
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:
• mode is:
encrypt(in_buf[, out_buf])
Encrypt in_buf. If no out_buf is given result is returned as a newly allocated bytes object.
Otherwise, result is written into mutable buffer out_buf. in_buf and out_buf can also refer to the
same mutable buffer, in which case data is encrypted in-place.
decrypt(in_buf[, out_buf])
Standard Python way to access binary data structures (doesn’t scale well to large and complex structures).
Usage examples:
import uctypes
STRUCT1 = {
"data1": 0 | uctypes.UINT8,
"data2": 4 | uctypes.UINT32,
"ptr": (8 | uctypes.PTR, COORD),
}
WWDG.WWDG_CFR.WDGTB = 0b10
WWDG.WWDG_CR.WDGA = 1
print("Current counter:", WWDG.WWDG_CR.T)
Currently, uctypes requires explicit specification of offsets for each field. Offset are given in bytes from the
structure start.
Following are encoding examples for various field types:
• Scalar types:
"field_name": offset | uctypes.UINT32
in other words, the value is a scalar type identifier ORed with a field offset (in bytes) from the start of
the structure.
• Recursive structures:
"sub": (offset, {
"b0": 0 | uctypes.UINT8,
"b1": 1 | uctypes.UINT8,
})
i.e. value is a 2-tuple, first element of which is an offset, and second is a structure descriptor dictionary
(note: offsets in recursive descriptors are relative to the structure it defines). Of course, recursive
structures can be specified not just by a literal dictionary, but by referring to a structure descriptor
dictionary (defined earlier) by name.
• Arrays of primitive types:
"arr": (offset | uctypes.ARRAY, size | uctypes.UINT8),
i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar
element type ORed number of elements in the array.
• Arrays of aggregate types:
"arr2": (offset | uctypes.ARRAY, size, {"b": 0 | uctypes.UINT8}),
i.e. value is a 3-tuple, first element of which is ARRAY flag ORed with offset, second is a number of
elements in the array, and third is a descriptor of element type.
• Pointer to a primitive type:
"ptr": (offset | uctypes.PTR, uctypes.UINT8),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, and second is a scalar
element type.
• Pointer to an aggregate type:
"ptr2": (offset | uctypes.PTR, {"b": 0 | uctypes.UINT8}),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, second is a descriptor of type
pointed to.
• Bitfields:
"bitf0": offset | uctypes.BFUINT16 | lsbit << uctypes.BF_POS | bitsize <<
uctypes.BF_LEN,
i.e. value is a type of scalar value containing given bitfield (typenames are similar to scalar types, but
prefixes with BF), ORed with offset for scalar value containing the bitfield, and further ORed with
values for bit position and bit length of the bitfield within the scalar value, shifted by BF_POS and
BF_LEN bits, respectively. A bitfield position is counted from the least significant bit of the scalar
(having position of 0), and is the number of right-most bit of a field (in other words, it’s a number of bits
a scalar needs to be shifted right to extract the bitfield).
In the example above, first a UINT16 value will be extracted at offset 0 (this detail may be important
when accessing hardware registers, where particular access size and alignment are required), and then
bitfield whose rightmost bit is lsbit bit of this UINT16, and length is bitsize bits, will be extracted. For
example, if lsbit is 0 and bitsize is 8, then effectively it will access least-significant byte of UINT16.
Note that bitfield operations are independent of target byte endianness, in particular, example above will
access least-significant byte of UINT16 in both little- and big-endian structures. But it depends on the
least significant bit being numbered 0. Some targets may use different numbering in their native ABI,
but uctypes always uses the normalized numbering described above.
Module contents
class uctypes.struct(addr, descriptor, layout_type=NATIVE, /)
Instantiate a “foreign data structure” object based on structure address in memory, descriptor (encoded as
a dictionary), and layout type (see below).
uctypes.LITTLE_ENDIAN
Layout type for a little-endian packed structure. (Packed means that every field occupies exactly as many
bytes as defined in the descriptor, i.e. the alignment is 1).
uctypes.BIG_ENDIAN
uctypes.NATIVE
Layout type for a native structure - with data endianness and alignment conforming to the ABI of the
system on which MicroPython runs.
uctypes.sizeof(struct, layout_type=NATIVE, /)
Return size of data structure in bytes. The struct argument can be either a structure class or a specific
instantiated structure object (or its aggregate field).
uctypes.addressof(obj)
Return address of an object. Argument should be bytes, bytearray or other object supporting buffer
protocol (and address of this buffer is what actually returned).
uctypes.bytes_at(addr, size)
Capture memory at the given address and size as bytes object. As bytes object is immutable, memory is
actually duplicated and copied into bytes object, so if memory contents change later, created object
retains original value.
uctypes.bytearray_at(addr, size)
Capture memory at the given address and size as bytearray object. Unlike bytes_at() function above,
memory is captured by reference, so it can be both written too, and you will access current value at the
given memory address.
uctypes.UINT8
uctypes.INT8
uctypes.UINT16
uctypes.INT16
uctypes.UINT32
uctypes.INT32
uctypes.UINT64
uctypes.INT64
Integer types for structure descriptors. Constants for 8, 16, 32, and 64 bit types are provided, both signed
and unsigned.
uctypes.FLOAT32
uctypes.FLOAT64
uctypes.VOID
VOID is an alias for UINT8, and is provided to conviniently define C’s void pointers: (uctypes.PTR,
uctypes.VOID).
uctypes.PTR
uctypes.ARRAY
Type constants for pointers and arrays. Note that there is no explicit constant for structures, it’s implicit:
an aggregate type without PTR or ARRAY flags is a structure.
Structure descriptors and instantiating structure objects
Given a structure descriptor dictionary and its layout type, you can instantiate a specific structure instance at a
given memory address using uctypes.struct() constructor. Memory address usually comes from
following sources:
• Predefined address, when accessing hardware registers on a baremetal system. Lookup these addresses
in datasheet for a particular MCU/SoC.
• As a return value from a call to some FFI (Foreign Function Interface) function.
• From uctypes.addressof(), when you want to pass arguments to an FFI function, or
alternatively, to access some data for I/O (for example, data read from a file or network socket).
Structure objects
Structure objects allow accessing individual fields using standard dot notation:
my_struct.substruct1.field1. If a field is of scalar type, getting it will produce a primitive value
(Python integer or float) corresponding to the value contained in a field. A scalar field can also be assigned to.
If a field is an array, its individual elements can be accessed with the standard subscript operator [] - both read
and assigned to.
If a field is a pointer, it can be dereferenced using [0] syntax (corresponding to C * operator, though [0]
works in C too). Subscripting a pointer with other integer values but 0 are also supported, with the same
semantics as in C.
Summing up, accessing structure fields generally follows the C syntax, except for pointer dereference, when
you need to use [0] operator instead of *.
Limitations
1. Accessing non-scalar fields leads to allocation of intermediate objects to represent them. This means that
special care should be taken to layout a structure which needs to be accessed when memory allocation is
disabled (e.g. from an interrupt). The recommendations are:
• Avoid accessing nested structures. For example, instead of
mcu_registers.peripheral_a.register1, define separate layout descriptors for each
peripheral, to be accessed as peripheral_a.register1. Or just cache a particular peripheral:
peripheral_a = mcu_registers.peripheral_a. If a register consists of multiple bitfields,
you would need to cache references to a particular register: reg_a =
mcu_registers.peripheral_a.reg_a.
• Avoid other non-scalar data, like arrays. For example, instead of peripheral_a.register[0] use
peripheral_a.register0. Again, an alternative is to cache intermediate values, e.g.
register0 = peripheral_a.register[0].
2. Range of offsets supported by the uctypes module is limited. The exact range supported is considered an
implementation detail, and the general suggestion is to split structure definitions to cover from a few kilobytes
to a few dozen of kilobytes maximum. In most cases, this is a natural situation anyway, e.g. it doesn’t make
sense to define all registers of an MCU (spread over 32-bit address space) in one structure, but rather a
peripheral block by peripheral block. In some extreme cases, you may need to split a structure in several parts
artificially (e.g. if accessing native data structure with multi-megabyte array in the middle, though that would
be a very synthetic case).
pyb — functions related to the board
The pyb module contains specific functions related to the board.
pyb.udelay(us)
pyb.millis()
Returns the number of milliseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so after 2^30 milliseconds (about
12.4 days) this will start to return negative numbers.
Note that if pyb.stop() is issued the hardware counter supporting this function will pause for the
duration of the “sleeping” state. This will affect the outcome of pyb.elapsed_millis().
pyb.micros()
Returns the number of microseconds since the board was last reset.
The result is always a MicroPython smallint (31-bit signed number), so after 2^30 microseconds (about
17.8 minutes) this will start to return negative numbers.
Note that if pyb.stop() is issued the hardware counter supporting this function will pause for the
duration of the “sleeping” state. This will affect the outcome of pyb.elapsed_micros().
pyb.elapsed_millis(start)
This function takes care of counter wrap, and always returns a positive number. This means it can be used
to measure periods up to about 12.4 days.
Example:
start = pyb.millis()
while pyb.elapsed_millis(start) < 1000:
# Perform some operation
pyb.elapsed_micros(start)
This function takes care of counter wrap, and always returns a positive number. This means it can be used
to measure periods up to about 17.8 minutes.
Example:
start = pyb.micros()
while pyb.elapsed_micros(start) < 1000:
# Perform some operation
pass
Resets the pyboard in a manner similar to pushing the external RESET button.
pyb.bootloader()
pyb.fault_debug(value)
Enable or disable hard-fault debugging. A hard-fault is when there is a fatal error in the underlying
system, like an invalid memory access.
If the value argument is False then the board will automatically reset if there is a hard fault.
If value is True then, when the board has a hard fault, it will print the registers and the stack trace, and
then cycle the LEDs indefinitely.
Disable interrupt requests. Returns the previous IRQ state: False/True for disabled/enabled IRQs
respectively. This return value can be passed to enable_irq to restore the IRQ to its original state.
pyb.enable_irq(state=True)
Enable interrupt requests. If state is True (the default value) then IRQs are enabled. If state is
False then IRQs are disabled. The most common use of this function is to pass it the value returned by
disable_irq to exit a critical section.
If given no arguments, returns a tuple of clock frequencies: (sysclk, hclk, pclk1, pclk2). These correspond
to:
Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 72, 84, 96,
108, 120, 144, 168.
The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is 84MHz. Be sure not to
set frequencies above these values.
The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency using a prescaler (divider).
Supported prescalers for hclk are: 1, 2, 4, 8, 16, 64, 128, 256, 512. Supported prescalers for pclk1 and
pclk2 are: 1, 2, 4, 8. A prescaler will be chosen to best match the requested frequency.
A sysclk frequency of 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI (internal
oscillator) directly. The higher frequencies use the HSE to drive the PLL (phase locked loop), and then
use the output of the PLL.
Note that if you change the frequency while the USB is enabled then the USB may become unreliable. It
is best to change the frequency in boot.py, before the USB peripheral is started. Also note that sysclk
frequencies below 36MHz do not allow the USB to function correctly.
pyb.wfi()
This executes a wfi instruction which reduces power consumption of the MCU until any interrupt occurs
(be it internal or external), at which point execution continues. Note that the system-tick interrupt occurs
once every millisecond (1000Hz) so this function will block for at most 1ms.
pyb.stop()
This reduces power consumption to less than 500 uA. To wake from this sleep state requires an external
interrupt or a real-time-clock event. Upon waking execution continues where it left off.
pyb.standby()
This reduces power consumption to less than 50 uA. To wake from this sleep state requires a real-time-
clock event, or an external interrupt on X1 (PA0=WKUP) or X18 (PC13=TAMP1). Upon waking the
system undergoes a hard reset.
Miscellaneous functions
pyb.have_cdc()
pyb.hid((buttons, x, y, z))
Takes a 4-tuple (or list) and sends it to the USB host (the PC) to signal a HID mouse-motion event.
Note
This function is deprecated. Use pyb.USB_HID.send() instead.
pyb.info([dump_alloc_table])
pyb.main(filename)
Set the filename of the main script to run after boot.py is finished. If this function is not called then the
default file main.py will be executed.
Note
This function is deprecated. Mounting and unmounting devices should be performed by uos.mount()
and uos.umount() instead.
Mount a block device and make it available as part of the filesystem. device must be an object that
provides the block protocol. (The following is also deprecated. See uos.AbstractBlockDev for the
correct way to create a block device.)
• count(self)
• sync(self) (optional)
readblocks and writeblocks should copy data between buf and the block device,
starting from block number blocknum on the device. buf will be a bytearray with length a
multiple of 512. If writeblocks is not defined then the device is mounted read-only. The
return value of these two functions is ignored.
count should return the number of blocks available on the device. sync, if implemented, should sync
the data on the device.
The parameter mountpoint is the location in the root of the filesystem to mount the device. It must
begin with a forward-slash.
If readonly is True, then the device is mounted read-only, otherwise it is mounted read-write.
If mkfs is True, then a new filesystem is created if one does not already exist.
pyb.repl_uart(uart)
Get or set the UART object where the REPL is repeated on.
pyb.rng()
pyb.sync()
pyb.unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID of the MCU.
If called with modestr provided, attempts to configure the USB mode. The following values of modestr
are understood:
• 'VCP+MSC+HID': enabled with VCP, MSC and HID (only available on PYBD boards)
For backwards compatibility, 'CDC' is understood to mean 'VCP' (and similarly for 'CDC+MSC' and
'CDC+HID').
The port parameter should be an integer (0, 1, …) and selects which USB port to use if the board supports
multiple ports. A value of -1 uses the default or automatically selected port.
The vid and pid parameters allow you to specify the VID (vendor id) and PID (product id). A pid value of
-1 will select a PID based on the value of modestr.
If enabling MSC mode, the msc parameter can be used to specify a list of SCSI LUNs to expose on the
mass storage interface. For example msc=(pyb.Flash(), pyb.SDCard()).
If enabling HID mode, you may also specify the HID details by passing the hid keyword parameter. It
takes a tuple of (subclass, protocol, max packet length, polling interval, report descriptor). By default it
will set appropriate values for a USB mouse. There is also a pyb.hid_keyboard constant, which is an
appropriate tuple for a USB keyboard.
The high_speed parameter, when set to True, enables USB HS mode if it is supported by the hardware.
Classes
• class Accel – accelerometer control
• class ADC – analog to digital conversion
• class CAN – controller area network communication bus
• class DAC – digital to analog conversion
• class ExtInt – configure I/O pins to interrupt on external events
• class Flash – access to built-in flash storage
• class I2C – a two-wire serial protocol
• class LCD – LCD control for the LCD touch-sensor pyskin
• class LED – LED object
• class Pin – control I/O pins
• class PinAF – Pin Alternate Functions
• class RTC – real time clock
• class Servo – 3-wire hobby servo driver
• class SPI – a master-driven serial protocol
• class Switch – switch object
• class Timer – control internal timers
• class TimerChannel — setup a channel for a timer
• class UART – duplex serial communication bus
• class USB_HID – USB Human Interface Device (HID)
• class USB_VCP – USB virtual comm port
class Accel – accelerometer control
Accel is an object that controls the accelerometer. Example usage:
accel = pyb.Accel()
for i in range(10):
print(accel.x(), accel.y(), accel.z())
Constructors
class pyb.Accel
Methods
Accel.filtered_xyz()
Implementation note: this method is currently implemented as taking the sum of 4 samples, sampled from
the 3 previous calls to this function along with the sample from the current call. Returned values are
therefore 4 times the size of what they would be from the raw x(), y() and z() calls.
Accel.tilt()
Accel.x()
Accel.y()
Accel.z()
Hardware Note
The accelerometer uses I2C bus 1 to communicate with the processor. Consequently when readings are being
taken pins X9 and X10 should be unused (other than for I2C). Other devices using those pins, and which
therefore cannot be used concurrently, are UART 1 and Timer 4 channels 1 and 2.
class ADC – analog to digital conversion
Usage:
import pyb
Constructors
class pyb.ADC(pin)
Create an ADC object associated with the given pin. This allows you to then read analog values on that
pin.
Methods
ADC.read()
Read the value on the analog pin and return it. The returned value will be between 0 and 4095.
ADC.read_timed(buf, timer)
Read analog values into buf at a rate set by the timer object.
buf can be bytearray or array.array for example. The ADC values have 12-bit resolution and are stored
directly into buf if its element size is 16 bits or greater. If buf has only 8-bit elements (eg a bytearray)
then the sample resolution will be reduced to 8 bits.
timer should be a Timer object, and a sample is read each time the timer triggers. The timer must
already be initialised and running at the desired sampling frequency.
To support previous behaviour of this function, timer can also be an integer which specifies the
frequency (in Hz) to sample at. In this case Timer(6) will be automatically configured to run at the given
frequency.
This function does not allocate any heap memory. It has blocking behaviour: it does not return to the
calling program until the buffer is full.
This is a static method. It can be used to extract relative timing or phase data from multiple ADC’s.
It reads analog values from multiple ADC’s into buffers at a rate set by the timer object. Each time the
timer triggers a sample is rapidly read from each ADC in turn.
ADC and buffer instances are passed in tuples with each ADC having an associated buffer. All buffers
must be of the same type and length and the number of buffers must equal the number of ADC’s.
Buffers can be bytearray or array.array for example. The ADC values have 12-bit resolution and
are stored directly into the buffer if its element size is 16 bits or greater. If buffers have only 8-bit
elements (eg a bytearray) then the sample resolution will be reduced to 8 bits.
timer must be a Timer object. The timer must already be initialised and running at the desired sampling
frequency.
This function does not allocate any heap memory. It has blocking behaviour: it does not return to the
calling program until the buffers are full.
The function returns True if all samples were acquired with correct timing. At high sample rates the time
taken to acquire a set of samples can exceed the timer period. In this case the function returns False,
indicating a loss of precision in the sample interval. In extreme cases samples may be missed.
The maximum rate depends on factors including the data width and the number of ADC’s being read. In
testing two ADC’s were sampled at a timer rate of 210kHz without overrun. Samples were missed at
215kHz. For three ADC’s the limit is around 140kHz, and for four it is around 110kHz. At high sample
rates disabling interrupts for the duration can reduce the risk of sporadic data loss.
Constructors
class pyb.CAN(bus, ...)
Construct a CAN object on the given bus. bus can be 1-2, or 'YA' or 'YB'. With no additional
parameters, the CAN object is created but not initialised (it has the settings from the last initialisation of
the bus, if any). If extra arguments are given, the bus is initialised. See CAN.init() for parameters of
initialisation.
Class Methods
classmethod CAN.initfilterbanks(nr)
Reset and disable all filter banks and assign how many banks should be available for CAN(1).
STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers. This
function configures how many filter banks should be assigned to each. nr is the number of banks that will
be assigned to CAN(1), the rest of the 28 are assigned to CAN(2). At boot, 14 banks are assigned to each
controller.
Methods
CAN.init(mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8, auto_restart=False, baudrate=0,
sample_point=75)
• if extframe is True then the bus uses extended identifiers in the frames (29 bits);
otherwise it uses standard 11 bit identifiers
• prescaler is used to set the duration of 1 time quanta; the time quanta will be the input
clock (PCLK1, see pyb.freq()) divided by the prescaler
• sjw is the resynchronisation jump width in units of the time quanta; it can be 1, 2, 3, 4
• bs1 defines the location of the sample point in units of the time quanta; it can be
between 1 and 1024 inclusive
• bs2 defines the location of the transmit point in units of the time quanta; it can be
between 1 and 16 inclusive
• auto_restart sets whether the controller will automatically try and restart
communications after entering the bus-off state; if this is disabled then restart()
can be used to leave the bus-off state
• baudrate if a baudrate other than 0 is provided, this function will try to automatically
calculate a CAN bit-timing (overriding prescaler, bs1 and bs2) that satisfies both the
baudrate and the desired sample_point.
• sample_point given in a percentage of the bit time, the sample_point specifies the
position of the last bit sample with respect to the whole bit time. The default
sample_point is 75%.
The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN prescaler value
divided by PCLK1 (the frequency of internal peripheral bus 1); see pyb.freq() to
determine PCLK1.
A single bit is made up of the synchronisation segment, which is always 1 tq. Then follows bit segment 1,
then bit segment 2. The sample point is after bit segment 1 finishes. The transmit point is after bit
segment 2 finishes. The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied by the
time quanta tq.
For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of tq is 2.38
microseconds. The bittime is 35.7 microseconds, and the baudrate is 28kHz.
CAN.deinit()
CAN.restart()
Force a software restart of the CAN controller without resetting its configuration.
If the controller enters the bus-off state then it will no longer participate in bus activity. If the controller is
not configured to automatically restart (see init()) then this method can be used to trigger a restart,
and the controller will follow the CAN protocol to leave the bus-off state and go into the error active
state.
CAN.state()
Return the state of the controller. The return value can be one of:
• CAN.ERROR_WARNING – the controller is on and in the Error Warning state (at least one of TEC
or REC is 96 or greater);
• CAN.ERROR_PASSIVE – the controller is on and in the Error Passive state (at least one of TEC
or REC is 128 or greater);
• CAN.BUS_OFF – the controller is on but not participating in bus activity (TEC overflowed
beyond 255).
CAN.info([list])
Get information about the controller’s error states and TX and RX buffers. If list is provided then it
should be a list object with at least 8 entries, which will be filled in with the information. Otherwise a new
list will be created and filled in. In both cases the return value of the method is the populated list.
• TEC value
• REC value
• number of times the controller enterted the Error Warning state (wrapped around to 0 after 65535)
• number of times the controller enterted the Error Passive state (wrapped around to 0 after 65535)
• number of times the controller enterted the Bus Off state (wrapped around to 0 after 65535)
• fifo is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
• params is an array of values the defines the filter. The contents of the array depends on the mode
argument.
CAN.MASK32 As with CAN.MASK16 but with only one 32 bit id/mask pair.
• rtr is an array of booleans that states if a filter should accept a remote transmission request
message. If this argument is not given then it defaults to False for all entries. The length of the
array depends on the mode argument.
CAN.LIST16 4
CAN.LIST32 2
CAN.MASK16 2
CAN.MASK32 1
CAN.clearfilter(bank)
CAN.any(fifo)
If list is not None then it should be a list object with a least four elements. The fourth element should be a
memoryview object which is created from either a bytearray or an array of type ‘B’ or ‘b’, and this array
must have enough room for at least 8 bytes. The list object will then be populated with the first three
return values above, and the memoryview object will be resized inplace to the size of the data and filled
in with that data. The same list and memoryview objects can be reused in subsequent calls to this method,
providing a way of receiving data without using the heap. For example:
buf = bytearray(8)
lst = [0, 0, 0, memoryview(buf)]
# No heap memory is allocated in the following call
can.recv(0, lst)
• rtr is a boolean that specifies if the message shall be sent as a remote transmission
request. If rtr is True then only the length of data is used to fill in the DLC slot of the
frame; the actual bytes in data are unused.
If timeout is 0 the message is placed in a buffer in one of three hardware buffers and the
method returns immediately. If all three buffers are in use an exception is thrown. If timeout is
not 0, the method waits until the message is transmitted. If the message can’t be transmitted
within the specified time an exception is thrown.
CAN.rxcallback(fifo, fun)
• fun is the function to be called when the fifo becomes non empty.
The callback function takes two arguments the first is the can object it self the second is a integer that
indicates the reason for the callback.
Reason
Constants
CAN.NORMAL
CAN.LOOPBACK
CAN.SILENT
CAN.SILENT_LOOPBACK
CAN.STOPPED
CAN.ERROR_ACTIVE
CAN.ERROR_WARNING
CAN.ERROR_PASSIVE
CAN.BUS_OFF
CAN.LIST16
CAN.MASK16
CAN.LIST32
CAN.MASK32
Constructors
class pyb.DAC(port, bits=8, *, buffering=None)
port can be a pin object, or an integer (1 or 2). DAC(1) is on pin X5 and DAC(2) is on pin X6.
bits is an integer specifying the resolution, and can be 8 or 12. The maximum value for the write and
write_timed methods will be 2**``bits``-1.
The buffering parameter selects the behaviour of the DAC op-amp output buffer, whose purpose is to
reduce the output impedance. It can be None to select the default (buffering enabled for DAC.noise(),
DAC.triangle() and DAC.write_timed(), and disabled for DAC.write()), False to disable
buffering completely, or True to enable output buffering.
When buffering is enabled the DAC pin can drive loads down to 5KΩ. Otherwise it has an output
impedance of 15KΩ maximum: consequently to achieve a 1% accuracy without buffering requires the
applied load to be less than 1.5MΩ. Using the buffer incurs a penalty in accuracy, especially near the
extremes of range.
Methods
DAC.init(bits=8, *, buffering=None)
Reinitialise the DAC. bits can be 8 or 12. buffering can be None, False or True; see above constructor
for the meaning of this parameter.
DAC.deinit()
De-initialise the DAC making its pin available for other uses.
DAC.noise(freq)
Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given
frequency.
DAC.triangle(freq)
Generate a triangle wave. The value on the DAC output changes at the given frequency and ramps
through the full 12-bit range (up and down). Therefore the frequency of the repeating triangle wave itself
is 8192 times smaller.
DAC.write(value)
Direct access to the DAC output. The minimum value is 0. The maximum value is 2**``bits``-1, where
bits is set when creating the DAC object or by using the init method.
Initiates a burst of RAM to DAC using a DMA transfer. The input data is treated as an array of bytes in 8-
bit mode, and an array of unsigned half-words (array typecode ‘H’) in 12-bit mode.
freq can be an integer specifying the frequency to write the DAC samples at, using Timer(6). Or it can
be an already-initialised Timer object which is used to trigger the DAC sample. Valid timers are 2, 4, 5, 6,
7 and 8.
dac1 = DAC(1)
dac2 = DAC(2)
dac1.write_timed(buf1, pyb.Timer(6, freq=100), mode=DAC.CIRCULAR)
dac2.write_timed(buf2, pyb.Timer(7, freq=200), mode=DAC.CIRCULAR)
class ExtInt – configure I/O pins to interrupt on
external events
There are a total of 22 interrupt lines. 16 of these can come from GPIO pins and the remaining 6 are from
internal sources.
For lines 0 through 15, a given line can map to the corresponding line from an arbitrary port. So line 0 can map
to Px0 where x is A, B, C, … and line 1 can map to Px1 where x is A, B, C, …
def callback(line):
print("line =", line)
Now every time a falling edge is seen on the X1 pin, the callback will be called. Caution: mechanical
pushbuttons have “bounce” and pushing or releasing a switch will often generate multiple edges. See:
http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed explanation, along with various techniques for
debouncing.
Trying to register 2 callbacks onto the same pin will throw an exception.
If pin is passed as an integer, then it is assumed to map to one of the internal interrupt sources, and must be in
the range 16 through 22.
All other pin objects go through the pin mapper to come up with one of the gpio pins.
extint = pyb.ExtInt(pin, mode, pull, callback)
Constructors
class pyb.ExtInt(pin, mode, pull, callback)
• pin is the pin on which to enable the interrupt (can be a pin object or any valid pin
name).
• callback is the function to call when the interrupt triggers. The callback function
must accept exactly 1 argument, which is the line that triggered the interrupt.
Class methods
classmethod ExtInt.regs()
Methods
ExtInt.disable()
Disable the interrupt associated with the ExtInt object. This could be useful for debouncing.
ExtInt.enable()
ExtInt.line()
ExtInt.swint()
Constants
ExtInt.IRQ_FALLING
ExtInt.IRQ_RISING
ExtInt.IRQ_RISING_FALLING
Constructors
class pyb.Flash
Create and return a block device that represents the flash device presented to the USB mass storage
interface.
It includes a virtual partition table at the start, and the actual flash starts at block 0x100.
Create and return a block device that accesses the flash at the specified offset. The length defaults to the
remaining size of the device.
The start and len offsets are in bytes, and must be a multiple of the block size (typically 512 for internal
flash).
Methods
Flash.readblocks(block_num, buf)
Flash.readblocks(block_num, buf, offset)
Flash.writeblocks(block_num, buf)
Flash.writeblocks(block_num, buf, offset)
Flash.ioctl(cmd, arg)
These methods implement the simple and extended block protocol defined by
uos.AbstractBlockDev.
Hardware Note
On boards with external spiflash (e.g. Pyboard D), the MicroPython firmware will be configured to use that as
the primary flash storage. On all other boards, the internal flash inside the MCU will be used.
class I2C – a two-wire serial protocol
I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL
and SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on.
Example:
from pyb import I2C
Printing the i2c object gives you information about its configuration.
The basic methods are send and recv:
i2c.send('abc') # send 3 bytes
i2c.send(0x42) # send a single byte, given by the number
data = i2c.recv(3) # receive 3 bytes
Constructors
class pyb.I2C(bus, ...)
Construct an I2C object on the given bus. bus can be 1 or 2, ‘X’ or ‘Y’. With no additional parameters,
the I2C object is created but not initialised (it has the settings from the last initialisation of the bus, if
any). If extra arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the I2C busses on Pyboards V1.0 and V1.1 are:
• I2C(1) is on the X position: (SCL, SDA) = (X9, X10) = (PB6, PB7)
Calling the constructor with ‘X’ or ‘Y’ enables portability between Pyboard types.
Methods
I2C.deinit()
• dma is whether to allow the use of DMA for the I2C transfers (note that DMA
transfers have more precise timing but currently do not handle bus errors properly)
I2C.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in master mode.
• recv can be an integer, which is the number of bytes to receive, or a mutable buffer,
which will be filled with received bytes
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the
same buffer that was passed in to recv.
I2C.scan()
Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Only valid when in
master mode.
Constants
I2C.MASTER
I2C.SLAVE
This driver implements a double buffer for setting/getting pixels. For example, to make a bouncing dot, try:
x = y = 0
dx = dy = 1
while True:
# update the dot's position
x += dx
y += dy
Constructors
class pyb.LCD(skin_position)
Construct an LCD object in the given skin position. skin_position can be ‘X’ or ‘Y’, and should
match the position where the LCD pyskin is plugged in.
Methods
LCD.command(instr_data, buf)
Send an arbitrary command to the LCD. Pass 0 for instr_data to send an instruction, otherwise pass 1
to send data. buf is a buffer with the instructions/data to send.
LCD.contrast(value)
Set the contrast of the LCD. Valid values are between 0 and 47.
LCD.fill(colour)
Fill the screen with the given colour (0 or 1 for white or black).
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.get(x, y)
LCD.light(value)
Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off.
LCD.pixel(x, y, colour)
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.show()
LCD.text(str, x, y, colour)
Draw the given text to the position (x, y) using the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
LCD.write(str)
Constructors
class pyb.LED(id)
Methods
LED.intensity([value])
Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given,
return the LED intensity. If an argument is given, set the LED intensity and return None.
Note: Only LED(3) and LED(4) can have a smoothly varying intensity, and they use timer PWM to
implement it. LED(3) uses Timer(2) and LED(4) uses Timer(3). These timers are only configured for
PWM if the intensity of the relevant LED is set to a value between 1 and 254. Otherwise the timers are
free for general purpose use.
LED.off()
LED.on()
LED.toggle()
Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is
considered “on” and toggle will turn it off.
class Pin – control I/O pins
A pin is the basic object to control I/O pins. It has methods to set the mode of the pin (input, output, etc) and
methods to get and set the digital logic level. For analog control of a pin, see the ADC class.
Usage Model:
All Board Pins are predefined as pyb.Pin.board.Name:
x1_pin = pyb.Pin.board.X1
g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)
CPU pins which correspond to the board pins are available as pyb.Pin.cpu.Name. For the CPU pins, the
names are the port letter followed by the pin number. On the PYBv1.0, pyb.Pin.board.X1 and
pyb.Pin.cpu.A0 are the same pin.
pyb.Pin.mapper(MyMapper)
Constructors
class pyb.Pin(id, ...)
Create a new Pin object associated with the id. If additional arguments are given, they are used to
initialise the pin. See pin.init().
Class methods
classmethod Pin.debug([state])
classmethod Pin.dict([dict])
classmethod Pin.mapper([fun])
Methods
Pin.init(mode, pull=Pin.PULL_NONE, af=- 1)
• when mode is Pin.AF_PP or Pin.AF_OD, then af can be the index or name of one
of the alternate functions associated with a pin.
Returns: None.
Pin.value([value])
• With value given, set the logic level of the pin. value can be anything that converts
to a boolean. If it converts to True, the pin is set high, otherwise it is set low.
Pin.__str__()
Pin.af()
Returns the currently configured alternate-function of the pin. The integer returned will match one of the
allowed constants for the af argument to the init function.
Pin.af_list()
Pin.gpio()
Returns the base address of the GPIO block associated with this pin.
Pin.mode()
Returns the currently configured mode of the pin. The integer returned will match one of the allowed
constants for the mode argument to the init function.
Pin.name()
Pin.names()
Pin.pin()
Pin.port()
Pin.pull()
Returns the currently configured pull of the pin. The integer returned will match one of the allowed
constants for the pull argument to the init function.
Constants
Pin.AF_OD
Pin.AF_PP
Pin.ANALOG
Pin.IN
Pin.OUT_OD
Pin.OUT_PP
Pin.PULL_DOWN
Pin.PULL_NONE
Pin.PULL_UP
x3_af will now contain an array of PinAF objects which are available on pin X3.
For the pyboard, x3_af would contain:
[Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the af automatically, but sometimes the same function is available
on multiple pins, and having more control is desired.
To configure X3 to expose TIM2_CH3, you could use:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
or:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)
Methods
pinaf.__str__()
pinaf.index()
pinaf.name()
pinaf.reg()
Return the base register associated with the peripheral assigned to this alternate function. For example, if
the alternate function were TIM2_CH3 this would return stm.TIM2
class RTC – real time clock
The RTC is an independent clock that keeps track of the date and time.
Example usage:
rtc = pyb.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.datetime())
Constructors
class pyb.RTC
Methods
RTC.datetime([datetimetuple])
With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being
an 8-tuple) it sets the date and time (and subseconds is reset to 255).
RTC.wakeup(timeout, callback=None)
Set the RTC wakeup timer to trigger repeatedly at every timeout milliseconds. This trigger can wake
the pyboard from both the sleep states: pyb.stop() and pyb.standby().
If callback is given then it is executed at every trigger of the wakeup timer. callback must take
exactly one argument.
RTC.info()
• The lower 0xffff are the number of milliseconds the RTC took to start up.
RTC.calibration(cal)
Get or set RTC calibration.
With no arguments, calibration() returns the current calibration value, which is an integer in the
range [-511 : 512]. With one argument it sets the RTC calibration.
The RTC Smooth Calibration mechanism adjusts the RTC clock rate by adding or subtracting the given
number of ticks from the 32768 Hz clock over a 32 second period (corresponding to 2^20 clock ticks.)
Each tick added will speed up the clock by 1 part in 2^20, or 0.954 ppm; likewise the RTC clock it
slowed by negative values. The usable calibration range is: (-511 * 0.954) ~= -487.5 ppm up to (512 *
0.954) ~= 488.5 ppm
Note
The Servo objects use Timer(5) to produce the PWM output. You can use Timer(5) for Servo control, or your
own purposes, but not both at the same time.
Constructors
class pyb.Servo(id)
Methods
Servo.angle([angle, time=0])
If arguments are given, this function sets the angle of the servo:
Servo.speed([speed, time=0])
If arguments are given, this function sets the speed of the servo:
• time is the number of milliseconds to take to get to the specified speed. If omitted,
then the servo accelerates as quickly as possible.
Servo.pulse_width([value])
If no arguments are given, this function returns the current raw pulse-width value.
If no arguments are given, this function returns the current calibration data, as a 5-tuple.
Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be 0 or 1, and is the level the idle
clock line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively. Crc can be
None for no CRC, or a polynomial specifier.
Additional methods for SPI:
data = spi.send_recv(b'1234') # send 4 bytes and receive 4 bytes
buf = bytearray(4)
spi.send_recv(b'1234', buf) # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf
Constructors
class pyb.SPI(bus, ...)
Construct an SPI object on the given bus. bus can be 1 or 2, or ‘X’ or ‘Y’. With no additional parameters,
the SPI object is created but not initialised (it has the settings from the last initialisation of the bus, if
any). If extra arguments are given, the bus is initialised. See init for parameters of initialisation.
• SPI(1) is on the X position: (NSS, SCK, MISO, MOSI) = (X5, X6, X7,
X8) = (PA4, PA5, PA6, PA7)
• SPI(2) is on the Y position: (NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7,
Y8) = (PB12, PB13, PB14, PB15)
At the moment, the NSS pin is not used by the SPI driver and is free for other use.
Methods
SPI.deinit()
• prescaler is the prescaler to use to derive SCK from the APB bus frequency; use
of prescaler overrides baudrate.
• polarity can be 0 or 1, and is the level the idle clock line sits at.
• phase can be 0 or 1 to sample data on the first or second clock edge respectively.
• bits can be 8 or 16, and is the number of bits in each transferred word.
Note that the SPI clock frequency will not always be the requested baudrate. The hardware
only supports baudrates that are the APB bus frequency (see pyb.freq()) divided by a
prescaler, which can be 2, 4, 8, 16, 32, 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on
AHB1. For precise control over the SPI clock frequency, specify prescaler instead of
baudrate.
Printing the SPI object will show you the computed baudrate and the chosen prescaler.
SPI.recv(recv, *, timeout=5000)
• recv can be an integer, which is the number of bytes to receive, or a mutable buffer,
which will be filled with received bytes.
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the
same buffer that was passed in to recv.
SPI.send(send, *, timeout=5000)
• recv is a mutable buffer which will be filled with received bytes. It can be the same
as send, or omitted. If omitted, a new buffer will be created.
SPI.SLAVE
SPI.LSB
SPI.MSB
Example:
pyb.Switch().callback(lambda: pyb.LED(1).toggle())
Constructors
class pyb.Switch
Methods
Switch.__call__()
Call switch object directly to get its state: True if pressed down, False otherwise.
Switch.value()
Get the switch state. Returns True if pressed down, otherwise False.
Switch.callback(fun)
Register the given function to be called when the switch is pressed down. If fun is None, then it disables
the callback.
class Timer – control internal timers
Timers can be used for a great variety of tasks. At the moment, only the simplest case is implemented: that of
calling a function periodically.
Each timer consists of a counter that counts up at a certain rate. The rate at which it counts is the peripheral
clock frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an
event, and the counter resets back to zero. By using the callback method, the timer event can call a Python
function.
Example usage to toggle an LED at a fixed frequency:
tim = pyb.Timer(4) # create a timer object using timer 4
tim.init(freq=2) # trigger at 2Hz
tim.callback(lambda t:pyb.LED(1).toggle())
Further examples:
tim = pyb.Timer(4, freq=100) # freq in Hz
tim = pyb.Timer(4, prescaler=0, period=99)
tim.counter() # get counter (can also set)
tim.prescaler(2) # set prescaler (can also get)
tim.period(199) # set period (can also get)
tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
tim.callback(None) # clear callback
Note: Timer(2) and Timer(3) are used for PWM to set the intensity of LED(3) and LED(4) respectively. But
these timers are only configured for PWM if the intensity of the relevant LED is set to a value between 1 and
254. If the intensity feature of the LEDs is not used then these timers are free for general purpose use. Similarly,
Timer(5) controls the servo driver, and Timer(6) is used for timed ADC/DAC reading/writing. It is
recommended to use the other timers in your programs.
Note: Memory can’t be allocated during a callback (an interrupt) and so exceptions raised within a callback
don’t give much information. See micropython.alloc_emergency_exception_buf() for how to
get around this limitation.
Constructors
class pyb.Timer(id, ...)
Construct a new timer object of the given id. If additional arguments are given, then the timer is
initialised by init(...). id can be 1 to 14.
Methods
Timer.init(*, freq, prescaler, period, mode=Timer.UP, div=1, callback=None, deadtime=0)
Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period:
• freq — specifies the periodic frequency of the timer. You might also
view this as the frequency with which the timer goes through one complete
cycle.
Timer.deinit()
Disables any channel callbacks (and the associated irq). Stops the timer, and disables the timer peripheral.
Timer.callback(fun)
Set the function to be called when the timer triggers. fun is passed 1 argument, the timer object. If fun
is None then the callback will be disabled.
Timer.channel(channel, mode, ...)
If only a channel number is passed, then a previously initialized channel object is returned (or None if
there is no previous channel).
Each channel can be configured to perform pwm, output compare, or input capture. All channels share the
same underlying timer, which means that they share the same timer clock.
Keyword arguments:
• pin None (the default) or a Pin object. If specified (and not None) this will cause the
alternate function of the the indicated pin to be configured for this timer channel. An
error will be raised if the pin doesn’t support any alternate functions for this timer
channel.
Note that capture only works on the primary channel, and not on the complimentary channels.
• Requires 2 pins, so one or both pins will need to be configured to use the appropriate
timer AF using the Pin API.
PWM Example:
Timer.counter([value])
Timer.freq([value])
Get or set the frequency for the timer (changes prescaler and period if set).
Timer.period([value])
Timer.source_freq()
Methods
timerchannel.callback(fun)
Set the function to be called when the timer channel triggers. fun is passed 1 argument, the timer object.
If fun is None then the callback will be disabled.
timerchannel.capture([value])
Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases
for the same function. capture is the logical name to use when the channel is in input capture mode.
timerchannel.compare([value])
Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases
for the same function. compare is the logical name to use when the channel is in output compare mode.
timerchannel.pulse_width([value])
Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all
aliases for the same function. pulse_width is the logical name to use when the channel is in PWM mode.
In edge aligned mode, a pulse_width of period + 1 corresponds to a duty cycle of 100% In center
aligned mode, a pulse width of period corresponds to a duty cycle of 100%
timerchannel.pulse_width_percent([value])
Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100
and sets the percentage of the timer period for which the pulse is active. The value can be an integer or
floating-point number for more accuracy. For example, a value of 25 gives a duty cycle of 25%.
class UART – duplex serial communication bus
UART implements the standard UART/USART duplex serial communications protocol. At the physical level it
consists of 2 lines: RX and TX. The unit of communication is a character (not to be confused with a string
character) which can be 8 or 9 bits wide.
UART objects can be created and initialised using:
from pyb import UART
Note: The stream functions read, write, etc. are new in MicroPython v1.3.4. Earlier versions use
uart.send and uart.recv.
Constructors
class pyb.UART(bus, ...)
Construct a UART object on the given bus. For Pyboard bus can be 1-4, 6, ‘XA’, ‘XB’, ‘YA’, or ‘YB’.
For Pyboard Lite bus can be 1, 2, 6, ‘XB’, or ‘YA’. For Pyboard D bus can be 1-4, ‘XA’, ‘YA’ or ‘YB’.
With no additional parameters, the UART object is created but not initialised (it has the settings from the
last initialisation of the bus, if any). If extra arguments are given, the bus is initialised. See init for
parameters of initialisation.
The Pyboard D supports UART(1), UART(2), UART(3) and UART(4) only, pins are:
Note: Pyboard D has UART(1) on YA, unlike Pyboard and Pyboard Lite that both have
UART(1) on XB and UART(6) on YA.
Methods
UART.init(baudrate, bits=8, parity=None, stop=1, *, timeout=0, flow=0, timeout_char=0,
read_buf_len=64)
• flow sets the flow control type. Can be 0, UART.RTS, UART.CTS or UART.RTS |
UART.CTS.
• timeout is the timeout in milliseconds to wait for writing/reading the first character.
This method will raise an exception if the baudrate could not be set within 5% of the desired
value. The minimum baudrate is dictated by the frequency of the bus that the UART is on;
UART(1) and UART(6) are APB2, the rest are on APB1. The default bus frequencies give a
minimum baudrate of 1300 for UART(1) and UART(6) and 650 for the others. Use
pyb.freq to reduce the bus frequencies to get lower baudrates.
Note: with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are
supported.
UART.deinit()
UART.any()
UART.read([nbytes])
Read characters. If nbytes is specified then read at most that many bytes. If nbytes are available in
the buffer, returns immediately, otherwise returns when sufficient characters arrive or the timeout elapses.
If nbytes is not given then the method reads as much data as possible. It returns after the timeout has
elapsed.
Note: for 9 bit characters each character takes two bytes, nbytes must be even, and the number of
characters is nbytes/2.
Return value: a bytes object containing the bytes read in. Returns None on timeout.
UART.readchar()
UART.readinto(buf[, nbytes])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at
most len(buf) bytes.
Return value: number of bytes read and stored into buf or None on timeout.
UART.readline()
Read a line, ending in a newline character. If such a line exists, return is immediate. If the timeout
elapses, all available data is returned regardless of whether a newline exists.
UART.write(buf)
Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide then each byte is one character. If
characters are 9 bits wide then two bytes are used for each character (little endian), and buf must contain
an even number of bytes.
Return value: number of bytes written. If a timeout occurs and no bytes were written returns None.
UART.writechar(char)
Write a single character on the bus. char is an integer to write. Return value: None. See note below if
CTS flow control is used.
UART.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: None.
Constants
UART.RTS
UART.CTS
Flow Control
On Pyboards V1 and V1.1 UART(2) and UART(3) support RTS/CTS hardware flow control using the
following pins:
• UART(2) is on: (TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2,
PA3, PA1, PA0)
• UART(3) is on :(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10,
PB11, PB14, PB13)
On the Pyboard Lite only UART(2) supports flow control on these pins:
(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)
In the following paragraphs the term “target” refers to the device connected to the UART.
When the UART’s init() method is called with flow set to one or both of UART.RTS and UART.CTS the
relevant flow control pins are configured. nRTS is an active low output, nCTS is an active low input with
pullup enabled. To achieve flow control the Pyboard’s nCTS signal should be connected to the target’s nRTS
and the Pyboard’s nRTS to the target’s nCTS.
If buffered input is not used (read_buf_len == 0) the arrival of a character will cause nRTS to go False
until the character is read.
Constructors
class pyb.USB_HID
Methods
USB_HID.recv(data, *, timeout=5000)
• data can be an integer, which is the number of bytes to receive, or a mutable buffer,
which will be filled with received bytes.
Return value: if data is an integer then a new buffer of the bytes received, otherwise the
number of bytes read into data is returned.
USB_HID.send(data)
Constructors
class pyb.USB_VCP(id=0)
Create a new USB_VCP object. The id argument specifies which USB VCP port to use.
Methods
USB_VCP.init(*, flow=- 1)
Configure the USB VCP port. If the flow argument is not -1 then the value sets the flow control, which
can be a bitwise-or of USB_VCP.RTS and USB_VCP.CTS. RTS is used to control read behaviour and
CTS, to control write behaviour.
USB_VCP.setinterrupt(chr)
Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a
CTRL-C character is received over the USB VCP port, a KeyboardInterrupt exception is raised.
Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB
VCP port.
USB_VCP.isconnected()
USB_VCP.any()
USB_VCP.close()
This method does nothing. It exists so the USB_VCP object can act as a file.
USB_VCP.read([nbytes])
Read at most nbytes from the serial device and return them as a bytes object. If nbytes is not
specified then the method reads all available bytes from the serial device. USB_VCP stream implicitly
works in non-blocking mode, so if no pending data available, this method will return immediately with
None value.
USB_VCP.readinto(buf[, maxlen])
Read bytes from the serial device and store them into buf, which should be a buffer-like object. At most
len(buf) bytes are read. If maxlen is given and then at most min(maxlen, len(buf)) bytes
are read.
Returns the number of bytes read and stored into buf or None if no pending data available.
USB_VCP.readline()
Returns a bytes object containing the data, including the trailing newline character or None if no pending
data available.
USB_VCP.readlines()
Read as much data as possible from the serial device, breaking it into lines.
Returns a list of bytes objects, each object being one of the lines. Each line will include the newline
character.
USB_VCP.write(buf)
USB_VCP.recv(data, *, timeout=5000)
• data can be an integer, which is the number of bytes to receive, or a mutable buffer,
which will be filled with received bytes.
Return value: if data is an integer then a new buffer of the bytes received, otherwise the
number of bytes read into data is returned.
USB_VCP.send(data, *, timeout=5000)
Constants
USB_VCP.RTS
USB_VCP.CTS
class LCD160CR
The LCD160CR class provides an interface to the display. Create an instance of this class and use its methods
to draw to the LCD and get the status of the touch panel.
For example:
import lcd160cr
lcd = lcd160cr.LCD160CR('X')
lcd.set_orient(lcd160cr.PORTRAIT)
lcd.set_pos(0, 0)
lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0))
lcd.set_font(1)
lcd.write('Hello MicroPython!')
print('touch:', lcd.get_touch())
Constructors
class lcd160cr.LCD160CR(connect=None, *, pwr=None, i2c=None, spi=None, i2c_addr=98)
• connect is a string specifying the physical connection of the LCD display to the board;
valid values are “X”, “Y”, “XY”, “YX”. Use “X” when the display is connected to a
pyboard in the X-skin position, and “Y” when connected in the Y-skin position. “XY”
and “YX” are used when the display is connected to the right or left side of the
pyboard, respectively.
One must specify either a valid connect or all of pwr, i2c and spi. If a valid connect is given
then any of pwr, i2c or spi which are not passed as parameters (i.e. they are None) will be
created based on the value of connect. This allows to override the default interface to the
display if needed.
See this image for how the display can be connected to the pyboard.
Static methods
static LCD160CR.rgb(r, g, b)
Return a 16-bit integer representing the given rgb color values. The 16-bit value can be used to set the
font color (see LCD160CR.set_text_color()) pen color (see LCD160CR.set_pen()) and
draw individual pixels.
LCD160CR.clip_line(data, w, h):
LCD160CR.h
The width and height of the display, respectively, in pixels. These members are updated when calling
LCD160CR.set_orient() and should be considered read-only.
Setup commands
LCD160CR.set_power(on)
Turn the display on or off, depending on the given value of on: 0 or False will turn the display off, and
1 or True will turn it on.
LCD160CR.set_orient(orient)
Set the orientation of the display. The orient parameter can be one of PORTRAIT, LANDSCAPE,
PORTRAIT_UPSIDEDOWN, LANDSCAPE_UPSIDEDOWN.
LCD160CR.set_brightness(value)
LCD160CR.set_i2c_addr(addr)
Set the I2C address of the display. The addr value must have the lower 2 bits cleared.
LCD160CR.set_uart_baudrate(baudrate)
LCD160CR.set_startup_deco(value)
Set the start-up decoration of the display. The value parameter can be a logical or of
STARTUP_DECO_NONE, STARTUP_DECO_MLOGO, STARTUP_DECO_INFO.
LCD160CR.save_to_flash()
Save the following parameters to flash so they persist on restart and power up: initial decoration,
orientation, brightness, UART baud rate, I2C address.
Set the specified pixel to the given color. The color should be a 16-bit integer and can be created by
LCD160CR.rgb().
LCD160CR.get_pixel(x, y)
LCD160CR.get_line(x, y, buf)
Low-level method to get a line of pixels into the given buffer. To read n pixels buf should be 2*n+1 bytes
in length. The first byte is a dummy byte and should be ignored, and subsequent bytes represent the pixels
in the line starting at coordinate (x, y).
Dump the contents of the screen to the given buffer. The parameters x and y specify the starting
coordinate, and w and h the size of the region. If w or h are None then they will take on their maximum
values, set by the size of the screen minus the given x and y values. buf should be large enough to hold
2*w*h bytes. If it’s smaller then only the initial horizontal lines will be stored.
LCD160CR.screen_load(buf)
Drawing text
To draw text one sets the position, color and font, and then uses LCD160CR.write to draw the text.
LCD160CR.set_pos(x, y)
Set the position for text output using LCD160CR.write(). The position is the upper-left corner of the
text.
LCD160CR.set_text_color(fg, bg)
Set the font for the text. Subsequent calls to write will use the newly configured font. The parameters
are:
• scale is a scaling value for each character pixel, where the pixels are drawn as a square
with side length equal to scale + 1. The value can be between 0 and 63.
• bold controls the number of pixels to overdraw each character pixel, making a bold
effect. The lower 2 bits of bold are the number of pixels to overdraw in the horizontal
direction, and the next 2 bits are for the vertical direction. For example, a bold value of
5 will overdraw 1 pixel in both the horizontal and vertical directions.
• trans can be either 0 or 1 and if set to 1 the characters will be drawn with a transparent
background.
• scroll can be either 0 or 1 and if set to 1 the display will do a soft scroll if the text
moves to the next line.
LCD160CR.write(s)
Write text to the display, using the current position, color and font. As text is written the position is
automatically incremented. The display supports basic VT100 control codes such as newline and
backspace.
LCD160CR.set_pen(line, fill)
LCD160CR.erase()
LCD160CR.dot(x, y)
Draw a single pixel at the given location using the pen line color.
LCD160CR.rect(x, y, w, h)
LCD160CR.rect_outline(x, y, w, h)
LCD160CR.rect_interior(x, y, w, h)
Draw a rectangle at the given location and size using the pen line color for the outline, and the pen fill
color for the interior. The rect method draws the outline and interior, while the other methods just draw
one or the other.
Draw a line between the given coordinates using the pen line color.
LCD160CR.dot_no_clip(x, y)
LCD160CR.rect_no_clip(x, y, w, h)
LCD160CR.rect_outline_no_clip(x, y, w, h)
LCD160CR.rect_interior_no_clip(x, y, w, h)
These methods are as above but don’t do any clipping on the input coordinates. They are faster than the
clipping versions and can be used when you know that the coordinates are within the display.
LCD160CR.poly_dot(data)
Draw a sequence of dots using the pen line color. The data should be a buffer of bytes, with each
successive pair of bytes corresponding to coordinate pairs (x, y).
LCD160CR.poly_line(data)
• If calib is True then the call will trigger a touch calibration of the resistive touch
sensor. This requires the user to touch various parts of the screen.
• If save is True then the touch parameters will be saved to NVRAM to persist across
reset/power up.
• If irq is True then the display will be configured to pull the IRQ line low when a
touch force is detected. If irq is False then this feature is disabled. If irq is None (the
default value) then no change is made to this setting.
LCD160CR.is_touched()
Returns a boolean: True if there is currently a touch force on the screen, False otherwise.
LCD160CR.get_touch()
Returns a 3-tuple of: (active, x, y). If there is currently a touch force on the screen then active is 1,
otherwise it is 0. The x and y values indicate the position of the current or most recent touch.
Advanced commands
LCD160CR.set_spi_win(x, y, w, h)
LCD160CR.fast_spi(flush=True)
Ready the display to accept RGB pixel data on the SPI bus, resetting the location of the first byte to go to
the top-left corner of the window set by LCD160CR.set_spi_win(). The method returns an SPI
object which can be used to write the pixel data.
Pixels should be sent as 16-bit RGB values in the 5-6-5 format. The destination counter will increase as
data is sent, and data can be sent in arbitrary sized chunks. Once the destination counter reaches the end
of the window specified by LCD160CR.set_spi_win() it will wrap around to the top-left corner of
that window.
LCD160CR.show_framebuf(buf)
Show the given buffer on the display. buf should be an array of bytes containing the 16-bit RGB values
for the pixels, and they will be written to the area specified by LCD160CR.set_spi_win(), starting
from the top-left corner.
The framebuf module can be used to construct frame buffers and provides drawing primitives. Using a
frame buffer will improve performance of animations when compared to drawing directly to the screen.
LCD160CR.set_scroll(on)
Turn scrolling on or off. This controls globally whether any window regions will scroll.
• win is the window id to configure. There are 0..7 standard windows for general
purpose use. Window 8 is the text scroll window (the ticker).
• vec specifies the direction and speed of scroll: it is a 16-bit value of the form
0bF.ddSSSSSSSSSSSS. dd is 0, 1, 2, 3 for +x, +y, -x, -y scrolling. F sets the speed
format, with 0 meaning that the window is shifted S % 256 pixel every frame, and 1
meaning that the window is shifted 1 pixel every S frames.
• param is the parameter number to configure, 0..7, and corresponds to the parameters
in the set_scroll_win method.
LCD160CR.set_scroll_buf(s)
Set the string for scrolling in window 8. The parameter s must be a string with length 32 or less.
LCD160CR.jpeg(buf)
Display a JPEG. buf should contain the entire JPEG data. JPEG data should not include EXIF
information. The following encodings are supported: Baseline DCT, Huffman coding, 8 bits per sample, 3
color components, YCbCr4:2:2. The origin of the JPEG is set by LCD160CR.set_pos().
LCD160CR.jpeg_start(total_len)
LCD160CR.jpeg_data(buf)
Display a JPEG with the data split across multiple buffers. There must be a single call to jpeg_start
to begin with, specifying the total number of bytes in the JPEG. Then this number of bytes must be
transferred to the display using one or more calls to the jpeg_data command.
LCD160CR.feed_wdt()
The first call to this method will start the display’s internal watchdog timer. Subsequent calls will feed the
watchdog. The timeout is roughly 30 seconds.
LCD160CR.reset()
Constants
lcd160cr.PORTRAIT
lcd160cr.LANDSCAPE
lcd160cr.PORTRAIT_UPSIDEDOWN
lcd160cr.LANDSCAPE_UPSIDEDOWN
lcd160cr.STARTUP_DECO_NONE
lcd160cr.STARTUP_DECO_MLOGO
lcd160cr.STARTUP_DECO_INFO
Functions
wipy.heartbeat([enable])
Get or set the state (enabled or disabled) of the heartbeat LED. Accepts and returns boolean values (True
or False).
class ADCWiPy – analog to digital conversion
Note
This class is a non-standard ADC implementation for the WiPy. It is available simply as machine.ADC on the
WiPy but is named in the documentation below as machine.ADCWiPy to distinguish it from the more
general machine.ADC class.
Usage:
import machine
Constructors
class machine.ADCWiPy(id=0, *, bits=12)
Create an ADC object associated with the given pin. This allows you to then read analog values on that
pin. For more info check the pinout and alternate functions table.
Warning
ADC pin input range is 0-1.4V (being 1.8V the absolute maximum that it can withstand). When GP2,
GP3, GP4 or GP5 are remapped to the ADC block, 1.8 V is the maximum. If these pins are used in digital
mode, then the maximum allowed input is 3.6V.
Methods
ADCWiPy.channel(id, *, pin)
Create an analog pin. If only channel ID is given, the correct pin will be selected. Alternatively, only the
pin can be passed and the correct channel will be selected. Examples:
ADCWiPy.init()
ADCWiPy.deinit()
adcchannel.value()
adcchannel.init()
adcchannel.deinit()
Constructors
class machine.TimerWiPy(id, ...)
Construct a new timer object of the given id. Id of -1 constructs a virtual timer (if supported by a board).
Methods
TimerWiPy.init(mode, *, width=16)
Keyword arguments:
• width must be either 16 or 32 (bits). For really low frequencies < 5Hz (or large
periods), 32-bit timers should be used. 32-bit mode is only available for ONE_SHOT
AND PERIODIC modes.
TimerWiPy.deinit()
Deinitialises the timer. Stops the timer, and disables the timer peripheral.
If only a channel identifier passed, then a previously initialized channel object is returned (or None if
there is no previous channel).
The operating mode is is the one configured to the Timer object that was used to create the channel.
• channel if the width of the timer is 16-bit, then must be either TIMER.A, TIMER.B. If the
width is 32-bit then it must be TIMER.A | TIMER.B.
Note
Either freq or period must be given, never both.
• polarity this is applicable for PWM, and defines the polarity of the duty cycle
Note
When the channel is in PWM mode, the corresponding pin is assigned automatically, therefore there’s no
need to assign the alternate function of the pin via the Pin class. The pins which support PWM
functionality are the following:
The behavior of this callback is heavily dependent on the operating mode of the timer channel:
• If mode is TimerWiPy.PWM the callback is executed when reaching the duty cycle
value.
• priority level of the interrupt. Can take values in the range 1-7. Higher values
represent higher priorities.
timerchannel.freq([value])
timerchannel.period([value])
timerchannel.duty_cycle([value])
Get or set the duty cycle of the PWM signal. It’s a percentage (0.00-100.00). Since the WiPy doesn’t
support floating point numbers the duty cycle must be specified in the range 0-10000, where 10000 would
represent 100.00, 5050 represents 50.50, and so on.
Constants
TimerWiPy.ONE_SHOT
TimerWiPy.PERIODIC