machine — functions related to the hardware
The machine module contains specific functions related to the hardware
on a particular board. Most functions in this module allow to achieve direct
and unrestricted access to and control of hardware blocks on a system
(like CPU, timers, buses, etc.). Used incorrectly, this can lead to
malfunction, lockups, crashes of your board, and in extreme cases, hardware
damage.
Memory access
The module exposes three objects used for raw memory access.
- machine.mem8
Read/write 8 bits of memory.
- machine.mem16
Read/write 16 bits of memory.
- machine.mem32
Read/write 32 bits of memory.
Use subscript notation [...] to index these objects with the address of
interest. Note that the address is the byte address, regardless of the size of
memory being accessed.
Example use (registers are specific to an stm32 microcontroller):
import machine
from micropython import const
GPIOA = const(0x48000000)
GPIO_BSRR = const(0x18)
GPIO_IDR = const(0x10)
# set PA2 high
machine.mem32[GPIOA + GPIO_BSRR] = 1 << 2
# read PA3
value = (machine.mem32[GPIOA + GPIO_IDR] >> 3) & 1
Note: the returned values are signed integers. Example: reading the cpuid register on esp8266
value = mem32[0x40001000]
will return a negative value, that could be counter-intuitive.
To always read a positive integer
value = mem32[0x40001000] & 0xffffffff
- machine.mem_backup(region=0)
Return a writable
memoryviewover a persistent hardware memory region that survives at least Soft Reset on all ports; battery-backed ports also survive power-off. Per-port persistence guarantees vary, see the table below.region selects which backup region to access (default 0, the primary region). Pass
-1to get a tuple of all available regions instead.The element type depends on the port’s hardware alignment requirements:
'B'(unsigned byte) on ports with byte-addressable backup memory,'I'(unsigned 32-bit) on ports backed by word-sized registers. Usemem.itemsizeto discover the access granularity at runtime.The total size in bytes is
len(mem) * mem.itemsize, wherelen(mem)is the number of elements andmem.itemsizeis the size of each element. For example, on a port with 4 word-sized registers,len(mem)is 4 andmem.itemsizeis 4, giving 16 bytes total. On a port with 4096 bytes of byte-addressable backup SRAM,len(mem)is 4096 andmem.itemsizeis 1.Cross-port guarantees for portable code:
mem.itemsizeis either1or4; valid indices are0..len(mem)-1; out-of-range access raisesIndexError; values are stored in host-native byte order. Region index semantics are not portable, see notes below forstm32in particular.Usage:
import machine mem = machine.mem_backup() mem[0] = 0x12345678 # write element 0 print(hex(mem[0])) # read element 0 print(len(mem)) # number of elements print(mem.itemsize) # bytes per element print(len(mem) * mem.itemsize) # total bytes available # Discover all available regions for i, r in enumerate(machine.mem_backup(-1)): print(i, len(r), r.itemsize)
The total byte size and backing hardware vary by port:
Port
Backing storage
Total bytes
Battery-backed
alif
Backup SRAM
4096
yes
esp32
RTC slow memory
2048
no
mimxrt
SNVS LPGPR registers (4 per chip)
12-16
yes
nrf
POWER GPREGRET registers
1-2
no
rp2
Watchdog scratch registers
28-60
no
samd
Backup RAM (SAMD51 only)
8192
yes
stm32
Backup SRAM + BKP registers (F4/F7/H5/H7/U5/N6)
2048-8192
yes
stm32
RTC BKP registers (other families)
20-128
yes
Note
On esp32 and rp2, data persists across Soft Reset,
machine.reset()andmachine.deepsleep()wake but is lost on power-off and on poweron-style resets. On esp32 in particular this includes pressing the EN/RESET button on most dev boards, which the chip reports as a power-on reset.Some ports split backup storage across multiple regions, or exclude registers reserved by the bootloader or system firmware:
Port
Register(s)
Note
mimxrt
LPGPR[3]
Excluded; used by TinyUF2 (when used)
rp2
scratch[4]
Excluded; used by pico-sdk on reset
rp2
powman scratch[0..7]
Region 2 on RP2350 only
stm32
BKP registers
Region 1 on BKPSRAM families (F4/F7/H5/H7/U5/N6)
Use
machine.mem_backup(-1)to discover available regions and their sizes.On stm32 the region index does not have a uniform meaning across boards: region 0 is BKPSRAM (
itemsize=1) on BKPSRAM families and BKP registers (itemsize=4) on others. Portable code should branch onmem.itemsizebefore structuring data.Some registers within a region are accessible but reserved by convention and should not be overwritten. The BKP register file is region 1 on BKPSRAM families and region 0 on the others:
Port
Register(s)
Used by
stm32
BKP0R
Arduino bootloader (Portenta H7, Giga, Opta, Nicla)
stm32
BKP16R-BKP18R
rfcore_firmware.pyon STM32WBstm32
last BKP reg
clock frequency (
MICROPY_HW_CLK_LAST_FREQ)stm32
BKP31R (N6)
mboot bootloader entry
The buffer allows direct register access and can be combined with
uctypesfor structured layouts:import machine, uctypes mem = machine.mem_backup() # Structured access via uctypes (check len(mem) for your board) layout = { "flags": (0 * 4, uctypes.UINT32), # register 0 "counter": (1 * 4, uctypes.UINT32), # register 1 } regs = uctypes.struct(uctypes.addressof(mem), layout) regs.flags = 0x01 print(regs.counter)
Availability: alif, esp32, mimxrt, nrf, rp2, samd, stm32 ports.
Miscellaneous functions
- machine.unique_id()
Returns a byte string with a unique identifier of a board/SoC. It will vary from a board/SoC instance to another, if underlying hardware allows. Length varies by hardware (so use substring of a full value if you expect a short ID). In some MicroPython ports, ID corresponds to the network MAC address.
- machine.time_pulse_us(pin, pulse_level, timeout_us=1000000, /)
Time a pulse on the given pin, and return the duration of the pulse in microseconds. The pulse_level argument should be 0 to time a low pulse or 1 to time a high pulse.
If the current input value of the pin is different to pulse_level, the function first (*) waits until the pin input becomes equal to pulse_level, then (**) times the duration that the pin is equal to pulse_level. If the pin is already equal to pulse_level then timing starts straight away.
The function will return -2 if there was timeout waiting for condition marked (*) above, and -1 if there was timeout during the main measurement, marked (**) above. The timeout is the same for both cases and given by timeout_us (which is in microseconds).
- machine.bitstream(pin, encoding, timing, data, /)
Transmits data by bit-banging the specified pin. The encoding argument specifies how the bits are encoded, and timing is an encoding-specific timing specification.
The supported encodings are:
0for “high low” pulse duration modulation. This will transmit 0 and 1 bits as timed pulses, starting with the most significant bit. The timing must be a four-tuple of nanoseconds in the format(high_time_0, low_time_0, high_time_1, low_time_1). For example,(400, 850, 800, 450)is the timing specification for WS2812 RGB LEDs at 800kHz.
The accuracy of the timing varies between ports. On Cortex M0 at 48MHz, it is at best +/- 120ns, however on faster MCUs (ESP8266, ESP32, STM32, Pyboard), it will be closer to +/-30ns.
Note
For controlling WS2812 / NeoPixel strips, see the
neopixelmodule for a higher-level API.
- machine.rng()
Return a 24-bit software generated random number.
Availability: WiPy.
Constants
Classes
- class Pin – control I/O pins
- class Signal – control and sense external I/O devices
- class ADC – analog to digital conversion
- class ADCBlock – control ADC peripherals
- class DAC – digital to analog conversion
- class PWM – pulse width modulation
- class UART – duplex serial communication bus
- class SPI – a Serial Peripheral Interface bus protocol (controller side)
- class I2C – a two-wire serial protocol
- class I2CTarget – an I2C target device
- class I2S – Inter-IC Sound bus protocol
- class CAN – Controller Area Network protocol
- class RTC – real time clock
- class Timer – control hardware timers
- class Counter – pulse counter
- class Encoder – quadrature decoding
- class WDT – watchdog timer
- class SD – secure digital memory card (cc3200 port only)
- class SDCard – secure digital memory card
- class USBDevice – USB Device driver