micropython – Access and control MicroPython internal functions

Functions

micropython.const(expr)

Used to declare that an expression is a constant, so that the compiler can optimize it. This function is used as follows:

from micropython import const

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

Constants declared in this way can still be accessed as global variables from outside the module that declares them. On the other hand, if a constant begins with an underscore, it is hidden, cannot be used as a global variable, and does not take up any memory during execution.

This const function is directly recognized by the MicroPython parser and provided as part of the micropython module, mainly so that scripts can run under both CPython and MicroPython following the above pattern.

micropython.opt_level([level])

If level is provided, this function sets the optimization level for subsequent script compilation and returns None. Otherwise, it returns the current optimization level.

The optimization level controls the following compilation features:

  • Assertions: at level 0, assertion statements are enabled and compiled into the bytecode; at level 1 and above, assertions are not compiled.

  • The built-in __debug__ variable: at level 0, this variable expands to True; at level 1 and above, it expands to False.

  • Source code line numbers: at levels 0, 1 and 2, source code line numbers are stored with the bytecode so that exceptions can report the line number where they occur; at level 3 and above, line numbers are not stored.

The default optimization level is usually level 0.

micropython.alloc_emergency_exception_buf(size)

Allocate size bytes of RAM for the emergency exception buffer (a suitable size is about 100 bytes). This buffer is used to create exceptions when normal RAM allocation fails (for example in an interrupt handler), thereby providing useful traceback information in these situations.

A good way to use this function is to place it at the beginning of the main script (e.g. boot.py or main.py), so that the emergency exception buffer will be valid for all subsequent code.

micropython.mem_info([verbose])

Print information about the memory currently in use. If the verbose argument is provided, extra information is printed.

The printed information depends on the implementation, but currently includes the amount of stack and heap in use. 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 the currently interned strings. If the verbose argument is provided, extra information is printed.

The printed information depends on the implementation, 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 amount of stack currently in use. The absolute value of this number is not particularly useful; instead it should be used to compute the difference in stack usage at different points.

micropython.heap_lock()
micropython.heap_unlock()
micropython.heap_locked()

Lock or unlock the heap. When locked, memory allocation cannot occur, and if any heap allocation is attempted, a MemoryError will be raised. heap_locked() returns a truthy value when the heap is currently locked.

These functions can be nested, i.e. heap_lock() can be called multiple times in succession, increasing the lock depth, 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 (the former after unlocking) as a non-negative integer, where 0 means the heap is not locked.

If the REPL becomes active while the heap is locked, it will be forcibly unlocked.

Note: heap_locked() is not enabled by default on most ports; it requires MICROPY_PY_MICROPYTHON_HEAP_LOCKED.

micropython.kbd_intr(chr)

Set the character that will raise a KeyboardInterrupt exception. By default, during script execution, this is set to 3, corresponding to Ctrl-C. Passing -1 to this function disables the capture of Ctrl-C, and passing 3 restores it.

This function can be used to prevent the capture of Ctrl-C on the incoming character stream that is normally used for the REPL, in case that stream is used for other purposes.

micropython.schedule(func, arg)

Schedule the function func to be executed “soon”. The function is passed the value arg as its only argument. “Soon” means the MicroPython runtime will do its best to execute the function at the earliest possible time, provided that it also tries to be efficient, and the following conditions are met:

  • A scheduled function never preempts another scheduled function.

  • Scheduled functions always execute “between opcodes”, which means that all basic Python operations (such as appending to a list) are guaranteed to be atomic.

  • A given port may define “critical regions” in which scheduled functions are never executed. Functions can be scheduled within a critical region, but they will not execute until that region is exited. An example of a critical region is a preempting interrupt handler (IRQ).

One use of this function is to schedule callbacks from a preempting IRQ. Such an IRQ imposes restrictions on the code running in the IRQ (for example the heap may be locked), and scheduling a function to be called later lifts these restrictions.

On multi-threaded ports, the behavior of scheduled functions depends on whether the particular port has enabled the global interpreter lock (GIL):

  • If the GIL is enabled, the function can preempt any thread and run in its context.

  • If the GIL is disabled, the function only preempts the main thread and runs in its context.

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 it directly will fail. This is because creating a reference to a bound method causes memory allocation. The solution is to create a reference to the method in the class constructor and pass that reference to schedule(). This is discussed in detail under “Creation of Python objects” in the reference documentation.

There is a limited queue to hold scheduled functions, and if the queue is full, schedule() will raise a RuntimeError.

Classes

class micropython.RingIO(size)
class micropython.RingIO(buffer)

Provides a fixed-size ring buffer of bytes with a stream interface. It can be regarded as a fifo queue variant of io.BytesIO.

When created with an integer size, an appropriate buffer will be allocated. Alternatively, a bytearray or similar buffer protocol object can be provided to the constructor for in-place use.

Uses the classic ring buffer algorithm, which allows a buffer of any size to be used but consumes one byte for tracking. If initialized with an integer size, this is taken into account; for example RingIO(16) will internally allocate a 17-byte buffer so that it can hold 16 bytes of data. However, when a pre-allocated buffer is passed in, one byte less than its original length will be available for storage; for example RingIO(bytearray(16)) will only hold 15 bytes of data.

When a RingIO instance is used to pass data in a single direction, it can be IRQ/thread-safe, for example writing in an IRQ and reading in a non-IRQ function (or vice versa). This will not hold if, for example, a single instance is written from both IRQ and non-IRQ code, which usually leads to data corruption.

any()

Return an integer representing the number of characters that can be read.

read([nbytes])

Read the available characters. This is a non-blocking function. If nbytes is specified, read at most that many bytes, otherwise read as much data as possible.

Return value: a bytes object containing the read bytes. If no data is available, it will be a zero-length bytes object.

readline([nbytes])

Read a line, ending at a newline or returning if one exists in the buffer, otherwise return the available bytes in the buffer. If nbytes is specified, read at most that many bytes.

Return value: a bytes object containing the read line.

readinto(buf[, nbytes])

Read available bytes into the provided buf. If nbytes is specified, read at most that many bytes. Otherwise, read at most len(buf) bytes.

Return value: an integer representing the number of bytes read into buf.

write(buf)

Write bytes from buf into the ring buffer in a non-blocking manner, limited by the available space in the ring buffer.

Return value: an integer representing the number of bytes written.

close()

A no-op provided as part of the standard stream interface. It has no effect on the data in the ring buffer.