Labs / MicroPython tutorials

01 Introduction to MicroPython Language — Draft Document Tutorial

Author: Li Zisheng · Source: FreakStudio open documentation, v1.1.0 · License: CC BY 4.0

Contents

1.Introduction to MicroPython

We can compare standard Python (commonly referred to as CPython) to the full-featured office software installed on a computer: it comes with a complete set of functions and can handle complex tasks, yet it takes up large storage space, consumes heavy resources, and can only run on devices with strong computing power and large memory such as computers.MicroPython is a streamlined version tailored specifically for embedded microcontrollers. It strips out the "redundant features" in standard Python that are unnecessary for embedded devices, while retaining Python's core syntax and commonly used functionalities. Boasting a small footprint and low resource consumption, it can run on devices with limited computing power and memory such as microcontrollers and development boards.Just as you wouldn't use the full-fledged office software on a computer to operate a smartwatch, MicroPython is the "lightweight Python" that can run on smartwatches and development boards. It retains the advantages of Python, such as being easy to learn and having concise code, while also adapting to the hardware limitations of microcontrollers.

MicroPython is a streamlined version of Python that implements the full syntax of Python 3.4 (including exceptions, the with statement, yield from, etc. , plus the async/await keywords from Python 3.5 and a selection of features from later versions). MicroPython runs on a wide range of microcontrollers, as well as Unix-like systems (including Linux, BSD, macOS, and WSL) and Windows systems. Microcontroller targets can be as small as 256 kiB flash + 16 kiB RAM, though devices with at least 512 kiB flash + 128 kiB RAM deliver a more comprehensive feature set. The Unix and Windows ports enable development and testing of MicroPython itself, and provide a lightweight alternative to CPython on these platforms — particularly on embedded Linux systems.

MicroPython provides the following core data types: str (with basic Unicode support), bytes, bytearray, tuple, list, dict, set, frozenset, array.array, collections.namedtuple, classes and instances. Its built-in modules include os, sys, time, re, struct, and more.It also supports the _thread module (multithreading), socket sockets for networking, SSL, and asyncio coroutines.

However, not all chips support the modules provided above. In some cases, it is necessary to tailor them according to the specific conditions of different chips, similar to building a Linux kernel, by selectively incorporating some key C driver codes related to hardware.

To adapt to embedded microcontrollers, most of the standard libraries have been trimmed, and only some modules such as parts of the functions and classes of math and sys are retained. In addition, many standard modules such as json and re have become ujson and ure prefixed with u in MicroPython, indicating that these are standard libraries developed for MicroPython.Currently, in addition to running on the originally developed pyboard microcontroller, MicroPython can also operate on a large number of ARM-based embedded development boards and chips, such as Arduino UNO R3, Raspberry Pi Pico, STM32 series, etc. , which enables us to conveniently develop applications like automatic control and robotics using Python.

MicroPython-enabled hardware platform

MicroPython can run on a variety of embedded hardware platforms, including pyboard, STM32, Raspberry Pi Pico, ESP32, ESP8266, MSP430/432, etc. At present, many developers are also trying to port MicroPython to more hardware platforms. Below we will introduce several common hardware platforms that support MicroPython.

1.pyboard

The pyboard is the official microcontroller development board that supports the full feature set of the MicroPython software. It connects to a computer via USB, has a built-in USB flash drive for storing Python programs, and can run as soon as it is powered on. It is compatible with Windows, macOS and Linux. MicroPython can run on the pyboard, and the built-in pyb module provides functions and classes for controlling the peripherals available on the board, such as UART, I2C, SPI, ADC and DAC.

For more related introductions and pictures, please visit: https://pico.nxez.com/what-is-pyboard

2.ESP8266

The ESP8266 Wi-Fi module, a module capable of Wi-Fi transmission, integrates the industry-leading Tensilica L106 ultra-low-power 32-bit micro MCU, comes with a 16-bit Lite Mode, and has a maximum clock frequency of up to 160MHz.It supports the integration of Wi-Fi MAC/BB/RF/PA/LNA with RTOS (Real Time Operating System) and IEEE802.11 b/g/n protocols, is compatible with the complete TCP/IP protocol stack, and also supports three modes: STA (Station), AP (Access Point), and STA+ AP.

The ESP8266 can function as an auxiliary Wi-Fi/Bluetooth module for data transmission, or be directly used as a development board for development via the Arduino IDE or MicroPython.

For more related introductions and pictures, please visit: https://docs.ai-thinker.com/esp8266

3.ESP32

The ESP32 SoC chip supports the following functions: 2.4 GHz Wi-Fi, Bluetooth, high-performance Xtensa® 32-bit LX6 dual-core processor, ultra-low power co-processor, and a variety of peripherals.

The ESP32 is fabricated using a 40 nm process, delivering optimal power consumption performance, radio frequency performance, stability, versatility and reliability, making it suitable for a wide range of application scenarios and diverse power consumption requirements.

For more related introductions and pictures, please visit: https://www.espressif.com.cn/zh-hans/products/socs/esp32

4.micro:bit

micro: bit is a microcomputer development board designed specifically for teenagers' programming education, which was launched by the British Broadcasting Corporation (BBC).

Micro: bit has the following features:

  • 25 independently programmable LEDs
  • 2 programmable buttons
  • Connect the pins
  • Light Sensor and Temperature Sensor
  • Motion Sensors (Accelerometer and Compass)
  • Wireless communication via radio and Bluetooth
  • USB interface
  • The v2 version is equipped with a microphone and a buzzer

For more related introductions and pictures, please refer to: https://baike.baidu.com/item/micro:bit/22482911

5.STM32 DISCOVERY/NUCLEO/EVAL

ST officially offers NUCLEO boards, DISCOVERY boards, and EVAL boards, with configurations ranging from entry-level to high-end, and prices following the same gradient. NUCLEO boards generally only lead out the MCU pins and come with one serial port (virtualized via STLINK USB); DISCOVERY boards, compared to NUCLEO boards, additionally feature USB (for MCUs with USB support), audio decoding, and a headphone jack.The EVAL board is a complete demonstration and development platform designed for ARM Cortex STM32 MCUs, which is equipped with transceivers, sensors, memory interfaces, display devices and a variety of other external circuits.

For more related introductions and pictures, please refer to:

https://www.st.com.cn/zh/evaluation-tools/stm32-mcu-mpu-eval-tools.html

6. SensorTile

SensorTile is a tiny square IoT module featuring powerful processing capabilities, leveraging an 80 MHz STM32L476JGY microcontroller, Bluetooth low energy connectivity based on the BlueNRG-MS network processor, as well as a variety of motion and environmental MEMS sensors including a digital microphone. SensorTile can be tightly integrated into IoT hubs or sensor network nodes to serve as the core of a solution.

For more related introductions and pictures, please refer to:

https://www.st.com/en/evaluation-tools/steval-stlkt01v1.html

MicroPython can execute scripts in textual source form (. py files) or as pre-compiled bytecode (. mpy files), and in both cases the scripts can be loaded either from the device's filesystem or be "frozen" into the MicroPython executable.

Pre-compiled bytecode (. mpy files)

MicroPython defines the concept of. mpy files, which are binary container file formats containing pre-compiled code and can be imported just like regular. py modules. These. mpy files are usually generated by cross-compiling programs from Python source files (. py files). For some architectures, . mpy files can also contain native machine code, which can be generated in a variety of ways, most typically from C source code.

. mpy files are typically used in the following scenarios:

  • When the RAM of the chip is insufficient to compile all modules, you can use precompiled modules to compile Python modules into bytecode, and the generated bytecode files carry the. mpy extension.
  • Native machine code can be dynamically imported via. mpy scripts. Unlike external MicroPython C modules that need to be compiled into the main firmware image, . mpy files do not require rebuilding the main MicroPython firmware.
  • If you want to protect your Python code, you can compile it into bytecode for execution

A given. mpy file may or may not be compatible with the given MicroPython system. For information on version control and compatibility of. mpy files, please refer to: http://www.86x.org/en/latet/reference/mpyfiles.html

Meanwhile, the. mpy file is a binary container format, with code objects stored internally in a nested hierarchy. To learn about the structure of mpy files and the specific information they contain, you can refer to: https://blog.csdn.net/Clover_pofu/article/details/137043894

MicroPython also provides a set of MicroPython-specific modules for accessing hardware-specific functions and peripherals, such as GPIO, timers, ADC, DAC, PWM, SPI, I2C, CAN, Bluetooth and USB.

Scripting Language:

A scripting language is a computer programming language designed to differ from the traditional edit-compile-link-run process of compiled languages. Early scripting languages were often referred to as batch languages or job control languages. A script is typically executed by interpretation rather than being compiled. Scripting languages generally feature simplicity, ease of learning and use, with the aim of enabling programmers to complete program development quickly.

It has the following characteristics:

  • Grammar and structures are usually relatively simple
  • Learning and using it are usually relatively simple
  • It usually adopts the "interpretation" execution mode that allows easy program modification, and does not require to "compile"
  • The development productivity of the program takes precedence over its execution performance

Although many scripting languages, such as JavaScript, Perl, PHP, Python, Ruby and Tcl, have gone beyond the realm of simple computer task automation and matured to the point where they can be used to write sophisticated programs, they are still referred to as scripts. There is a scripting language at almost every level of computer systems, including the operating system layer, as seen in applications like computer games, network applications, word processing documents, and network software. In many respects, high-level programming languages and scripting languages overlap with each other, and there is no clear-cut boundary between the two.

1.1 Development History of the MicroPython Language

In recent years, the popularity of Python has skyrocketed. Today, it is used everywhere, ranging from DevOps and statistical analysis to even desktop software. However, for a long time, there was a noticeable absence of Python in the embedded field. This all changed in 2013, when Damien George launched a Kickstarter crowdfunding campaign. Damien was an undergraduate at the University of Cambridge and an avid robotics programmer.He wants to shift the Python world from machines that handle gigabytes of capacity to machines with kilobyte-level capacity. He tried to support his own development through a Kickstarter crowdfunding campaign, while turning the Proof of Concept into the final implementation.

01 Introduction to MicroPython Language — Draft Document Tutorial
Figure 1.1 Damien George, founder of MicroPython

Damien spent six months developing MicroPython. MicroPython itself is developed using GNU C, implements the basic functions of Python 3 on STMicroelectronics' microcontrollers, and is equipped with a complete parser, compiler, virtual machine, class libraries and other components. While retaining the main features and basic functions of the Python language, he also encapsulated common embedded functions, and wrote dedicated driver libraries for some common hardware and sensors.

The original Kickstarter campaign released MicroPython for the "pyboard" development board driven by STM32F4, which is a purpose-built hardware development board that runs MicroPython as an operating system (OS). The board is equipped with 4 color-coded LED indicators, a 3-axis accelerometer, a microSD card slot, and supports user program downloading and firmware upgrading via USB.

01 Introduction to MicroPython Language — Draft Document Tutorial
Figure 1.2 MicroPython development board pyboard

MicroPython supports embedded hardware platforms, and the chips supported in the mainline include ARM Cortex-M series chips (STM32, RP2040, TI CC3200), ESP8266, ESP32,16-bit PIC, etc.

In 2016, a MicroPython version was created for the BBC Micro Bit as part of the Python Software Foundation's contribution to the Micro Bit's partnership with the BBC.

In July 2017, MicroPython was forked to create CircuitPython, a version of MicroPython that emphasizes education and ease of use. MicroPython and CircuitPython support slightly different hardware sets (for example, CircuitPython supports Atmel SAM D21 and D51 boards but has dropped support for the ESP8266).Starting from version 4.0, CircuitPython is based on MicroPython version 1.9.4. [

In 2017, Microsemi developed a MicroPython port for the RISC-V (RV32 and RV64) architecture.

In April 2019, a MicroPython version for Lego Mindstorms EV3 was created.

In January 2021, the MicroPython port for the RP2040 (ARM Cortex-M0+) was created.

Apart from MicroPython, there are other scripting programming languages for embedded systems such as Lua, JavaScript and MMBasic. However, none of them boasts as complete functionality as MicroPython, nor do they match its performance; they also fall short of MicroPython in portability and ease of use, with far fewer available resources.

1.2 Other Examples of Embedded Programming with Python

1.2.1 PyMite

01 Introduction to MicroPython Language — Draft Document Tutorial

PyMite is a lightweight Python interpreter written from the ground up, designed to run on 8-bit and larger microcontrollers with limited resources: 64 KiB of program memory (flash) and 4 KiB of RAM. It supports a subset of Python 2.5 syntax and can execute a subset of Python 2.5 bytecode. PyMite can also be compiled, tested and run on desktop computers.

1.2.2 CircuitPython

01 Introduction to MicroPython Language — Draft Document Tutorial

CircuitPython is a programming language based on MicroPython, designed to simplify experimentation and learning through coding on low-cost microcontroller boards. Most CircuitPython libraries can also run on single-board computers (SBCs) such as the Raspberry Pi. Linux runs "desktop" Python (commonly referred to as CPython) rather than CircuitPython.

1.3 Differences between CircuitPython and MicroPython

CircuitPython is a beginner-friendly open-source version of Python. Built on MicroPython, it is designed for small, low-cost computers known as microcontrollers. Microcontrollers serve as the core processing unit of a wide range of electronic devices, including various development boards used for building hobbyist projects and prototypes.

CircuitPython in electronics is one of the best ways to learn coding, as it connects code to the real world. You can usually install CircuitPython on a supported USB board simply by dragging and dropping, then code.py edit the file on the CIRCUITPY drive. The code will reload automatically. No software needs to be installed other than a text editor (we recommend one for beginners).

Compared with MicroPython, the most intuitive differences of CircuitPython are as follows:

1.4 Why Use MicroPython to Build Our Project

1.4.1 Reduce Development Difficulty

MicroPython has built proven hardware systems and low-level driver libraries, allowing us to focus our programming efforts on application-layer development instead of building projects from the absolute bottom, which greatly reduces the time spent on low-level hardware design and software debugging while significantly lowering the technical threshold for embedded development.

1.4.2 High Portability

When programming with traditional C/C++, it is often necessary to use SDK packages or driver functions provided by chip vendors, such as ST's CubeIDE and NXP's PE. While these tools can greatly reduce the difficulty of development, the tools from different manufacturers vary, and their library functions are incompatible, making it very difficult to directly port programs developed with these tools.

However, the emergence of MicroPython enables us to complete the porting of the application layer without re-implementing the underlying functions. As a scripting language itself, MicroPython has low correlation with hardware, and coupled with the concise syntax of the Python language, it makes program porting and upgrading extremely easy.

1.4.3 Openness

MicroPython and Pyboard adopt the permissive MIT license approach. The MIT license is a Licensing Agreement as permissive as BSD. The author only intends to retain the copyright without imposing any other restrictions. Anyone may use, modify, and distribute it, and may also incorporate it into commercial products free of charge.

You only need to include the statement of the original Licensing Agreement in your distribution, whether you are distributing it in binary form or source code form.

The open nature of MicroPython has enabled it to achieve tremendous growth in just a few years, and a large number of engineers and enthusiasts around the world are learning and using it.

01 Introduction to MicroPython Language — Draft Document Tutorial
Figure 1.3 MicroPython project architecture

2. Introduction to MicroPython Project Architecture

We can compare the project architecture of MicroPython to "a customizable set of embedded Python development building blocks": the core blocks are the general-purpose Python functions available for all devices, while the device-specific blocks are the platform code adapted to hardware. This design not only ensures the versatility of MicroPython but also enables flexible adaptation to various microcontrollers and systems. Before diving into the architecture, let's first understand several core concepts:

The project code of MicroPython is divided into different directories according to the logic of "common core + platform adaptation + auxiliary tools", and each directory has a clear functional division. The specific architecture composition is as follows:

How MicroPython Code Runs

A piece of Python code enters the interpreter's cache via the REPL; the interpreter program will interpret this code (compile it into ByteCode), then execute it using the interpreted code, which is pushed onto the interpreter's function stack for execution during the process.

minimal port provides a very basic example of a MicroPython port that can be compiled as a standalone Linux binary as well as for ARM Cortex M4. If you want to port MicroPython to another microcontroller, start here. Additionally, the "bare-arm" port is an example of an absolute minimal configuration, used to track the code size of the core runtime and virtual machine.

01 Introduction to MicroPython Language — Draft Document Tutorial
Figure 2.4 MicroPython project port code structure

In addition, the following ports are also provided in this repository:

We can compare the system architecture of MicroPython to the operating system of a smartphone: the smartphone hardware corresponds to the microcontroller hardware, the smartphone's operating system (such as Android/iOS) corresponds to the MicroPython firmware, and the apps we install correspond to the user-written MicroPython programs. Firmware is the core of the entire system, responsible for connecting hardware and user programs, just as the smartphone system connects hardware and apps. Before understanding the system architecture, let's first grasp several key basic concepts:

3.1 System Architecture of MicroPython

The typical structure of a MicroPython system is as follows:

Diagram: 01 Introduction to MicroPython Language — Draft Document Tutorial

It consists of user programs, MicroPython firmware and microcontroller hardware. The firmware and hardware are the most fundamental and fixed components, and we can only write and modify the user programs. MicroPython firmware is similar to an embedded operating system, which is mainly used to run user programs and provide a REPL command interpreter.

bare metal bare-metal approach

The bare metal framework refers to the role that MicroPython plays in the OS of the microcontroller it is installed on.

Unlike other OSes, MicroPython can access and control the machine code of microcontrollers, such as instantiating MicroPython to disable hardware interrupts, writing built-in assembly code, and so on.

Before programming an MCU with MicroPython, we first need to flash the MicroPython firmware corresponding to the specific MCU chip. Once the flashing is complete, upload the written MicroPython program to the microcontroller, and then restart the MCU:

  1. After the device is powered on, the bootloader is responsible for loading the MicroPython firmware from flash memory into RAM, and the firmware contains the interpreter and the basic Runtime Environment;
  2. Before MicroPython starts executing Python code, it initializes the necessary hardware and peripherals, including setting up clocks, initializing GPIOs, and configuring peripherals.
  3. MicroPython will locate and execute predefined startup scripts (such as main.py), which can contain user-defined initialization code or program logic. The MicroPython interpreter will first compile Python code into bytecode, a process that is completed dynamically on the device, eliminating the need for the complex pre-compilation process;
  4. The compiled bytecode is executed by the MicroPython interpreter, which converts the bytecode into specific operations and runs these operations on the hardware;
  5. MicroPython manages the stack and Memory Space in microcontrollers, and its built-in garbage collector (GC) also periodically cleans up unused objects to free up Memory Space;
  6. Once the startup script finishes executing, MicroPython enters the REPL mode and waits for the user to input commands or code.

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 system hardware blocks such as CPU, timers, buses, etc. Improper use may lead to board failure, locking up, crashing, and in extreme cases, even hardware damage.

Diagram: 01 Introduction to MicroPython Language — Draft Document Tutorial

3.3 rp2 module — RP2040-specific features

This rp2 module contains functions and classes specific to the RP2040, such as those used in the Raspberry Pi Pico.

Diagram: 01 Introduction to MicroPython Language — Draft Document Tutorial

3.4 MicroPython Standard Micro-library

The following standard Python libraries have been "micro-optimized" to align with the philosophy of MicroPython. They provide the core functionality of the corresponding modules and are intended to replace the standard Python libraries.

Diagram: 01 Introduction to MicroPython Language — Draft Document Tutorial

3.5 MicroPython-Specific Libraries

Diagram: 01 Introduction to MicroPython Language — Draft Document Tutorial

4. Implementation Features of MicroPython

4.1 Optimization Steps

The process of developing high-performance code consists of the following phases, which shall be executed in the listed order:

  1. Identify the slowest parts in the code
  2. Improve the efficiency of Python code
  3. Use the native code emitter
  4. Use the viper code emitter
  5. Use hardware-specific optimizations

When identifying the slowest code segments, we can typically establish the function group utime recorded in ticks through the judicious use of timing. Code execution time can be measured in milliseconds, microseconds, or CPU cycles.

The following allows you to time any function or method by adding the @timed_function decorator:

def timed_function(f, *args, **kwargs):
    myname = str(f).split(' ')[1]
    def new_func(*args, **kwargs):
        t = time.ticks_us()
        result = f(*args, **kwargs)
        delta = time.ticks_diff(time.ticks_us(), t)
        print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
        return result
    return new_func

4.2 Maximizing MicroPython Runtime Speed

Optimization Idea: Optimize in the order of "from simple to complex, from software to hardware", first locate the performance bottleneck, then make gradual adjustments to achieve the maximum performance improvement at low cost.

Core tools and methodologies include:

Optimization Direction:

For details, please refer to: How to Speed Up the Operation of MicroPython

4.3 Minimize MicroPython Memory Footprint

MicroPython is mainly used for microcontrollers (such as Raspberry Pi Pico, ESP32). Such devices have limited resources in terms of RAM (Random Access Memory, ranging from tens of KB to hundreds of KB, with fast read/write speed but data loss upon power-off) and Flash (storage memory, several MB, which retains data after power-off but has slow read/write speed), so memory optimization is the key to stable program operation.

Memory optimization methods include:

For details, please refer to: How to Minimize Memory Usage of MicroPython

4.4 Distribution Packages, Package Management and Deployment Applications

Taking Python on the host computer as an example, Python modules and packages can be packaged into archive files suitable for transmission between systems and stored on the Python Package Index (PyPI). Users who need to install these modules and packages only need to execute the corresponding pip installation command to complete the download and deployment.

Packaging refers to further encapsulating your source code and pre-configuring all project deployment tasks, so that users can get it up and running immediately without worrying about deployment issues; while distribution means uploading the packaged Python modules and packages to the Python Package Index, so that they can be used as an open-source library installed via the pip install command.

PyPI: Python Package Index

The Python Package Index (PyPI) is a software repository for the Python programming language. PyPI helps you find and install software developed and shared by the Python community, while package authors use PyPI to distribute their software.

Distribution of Python packages can be divided into two categories:

Just like the Python for host computers, MicroPython supports creating "third-party" packages, distributing them, and installing them easily in each user's environment.

The distribution package format of MicroPython is the well-known tar.gz format, where the Gzip compressor acts as an external wrapper for the TAR Compressed Packet, with a default dictionary size of 4KB.

4.4.1 Installation Package Process

The basic process of the installation package is as follows:

For the specific process, please refer to: Overview and Installation Methods of MicroPython Packages and Modules

4.4.2 Creating and Distributing Your Own Packages and Modules

The process for creating and distributing your own packages and modules for MicroPython is briefly summarized as follows:

  1. Standard package structure: organize the file directory, including the core function. py file, the optional __init__. py (marked as a package), README.md (documentation), LICENSE (open source license), examples folder (sample code), etc.
  2. Code specification check: By means of the pre-commit hook, the tools black and Flake8 are automatically invoked to conduct code format specification and static check, so as to ensure that the code complies with the specifications.
  3. Compile / Optimization (Adaptation for Embedded Environments): Convert. py files into. mpy bytecode; for low-memory devices, packages can be "frozen" into firmware bytecode (pre-compiled and stored in ROM).
  4. Prepare for metadata distribution: Write files such as package.json and manifest.py, and specify information including the package name, version, and dependencies.
  5. Distribution and Deployment:
    1. Public distribution: upload to PyPI (for others to install via upip), or publish to a GitHub repository for download.
    2. Device deployment: Network-free devices can be cross-installed into the directory image via Unix ports and then transferred to the device; low-memory devices are directly flashed with firmware containing a frozen package.

You can refer to the following link for the specific process: https://www.cnblogs.com/FreakEmbedded/p/18757480

5. MicroPython Kernel Development

Since this tutorial mainly focuses on using MicroPython to write driver programs for sensor modules and develop simple programs, as well as how to get started with MCU programming using the Raspberry Pi Pico, we will only provide a brief overview of the content in this section.

First of all, we need to understand the basic terms:

For specific details about MicroPython kernel development, you can refer to: https://docs.micropython.org/en/latest/develop/index.html .

01 Introduction to MicroPython Language — Draft Document Tutorial
Figure 2.20 MicroPython internal development guide structure

This chapter, MicroPython Internals, is a hands-on tutorial designed for developers who want to go from beginner level to being able to contribute code hands-on. It starts with the basics of obtaining source code and setting up the build environment, then gradually walks you through understanding how the compiler compiles Python code into bytecode, how the runtime manages objects and memory, and how to write extension modules in C or port MicroPython to a new hardware platform.

It mainly includes the following contents:

Appendix: Differences between CPython and MicroPython

For the specific content of this section, please refer to: https://docs.micropython.org/en/latest/genrst/index.html .

01 Introduction to MicroPython Language — Draft Document Tutorial

This section is specially designed for beginners who are new to MicroPython. Its core purpose is to help you quickly understand the differences between it and the CPython (the standard Python running on computers) that we commonly use — there's no need to get tangled up in complicated technical details. As long as you grasp the two key points of "version support scope" and "practical usage differences" first, you can avoid pitfalls when writing code later.

First, it is necessary to clarify MicroPython 's " Python version foundation": it does not support the latest Python version, but is implemented with Python 3.4 as the core, and additionally incorporates a number of selected features from Python 3.5 and later versions.For example, it supports some features from versions 3.5, 3.6 up to 3.10, but not all of them. The tutorial will clearly list exactly which "optional features" it supports in the order of versions from 3.5 to 3.10. You don't need to memorize all of them; it's enough to know that it is based on version 3.4 and comes with some features from higher versions.

More importantly, there are "practical behavioral differences": even if MicroPython implements a feature with the same name as CPython, its usage may still differ. These differences mainly concentrate in 5 areas commonly used by beginners, which you will most likely encounter when writing code on a regular basis:

Finally, keep in mind that these differences do not mean that MicroPython is "incomplete"; rather, they are optimizations it has made to adapt to the "small memory and low performance" characteristics of embedded devices such as microcontrollers.

Here, we have briefly compiled a table to summarize these differences:

AreaCPython BehaviorMicroPython BehaviorQuick Advice / Alternative
Underscores in numeric literalsStrict: consecutive or trailing underscores are not allowedMore lenient or different: sometimes accepted (the implementation ignores underscores)Follow CPython syntax (no consecutive or trailing _) to stay compatible
Number followed by keyword/.CPython separates the number from what follows (may emit a SyntaxWarning)The lexer treats 1and as a single token → syntax errorAdd a space between the number and the keyword/dot, or use parentheses (0x1).to_bytes()
Walrus operator := (nested comprehensions)Rebinding the iteration variable inside a comprehension is prohibitedMay not perform full checks, allowing some violationsAvoid using := to bind the outer iteration variable in nested comprehensions
Unicode name escape \N{...}SupportedNot implemented (NotImplementedError)Use \uXXXX or direct character literals
Argument unpacking limitsAny number (limited by memory)Limited by the implementation flag bits (MP_SMALL_INT); too many raises "too many args"Avoid passing a very large number of positional arguments at once; pass them in batches or use a sequence object
__del__ (user classes)Is called (during garbage collection)__del__ is usually not guaranteed to be called for user-defined classesDo not rely on __del__ for critical cleanup; use try/finally or a context manager
__init_subclass__ / PEP487Called automatically; supports parameterization and cooperationPEP 487 is not implemented: not called automatically, not implicitly a classmethod, no parameterization, no recursive call supportIf needed, call A.__init_subclass__() manually or use class variables instead of parameterization
MRO / super()Uses C3 (linearization); the multiple-inheritance call chain is completeUses a depth-first, non-complete algorithm; super() may call only some parent classesAvoid complex multiple inheritance; call parent constructors explicitly or simplify the inheritance structure
Private names (name-mangling)__name is automatically rewritten to _Class__nameNo name-mangling; may conflict with a module-level name of the same nameManually add a unique prefix or avoid double-underscore private names
Inheriting from built-in types (list/tuple)Parent class methods can be used safely before __init__Calling built-in methods before super().__init__() may raise an error or crashCall super().__init__() first, on the first line of the subclass __init__
Function object attributesSupports __module__; attributes can be attached dynamicallyMinimal implementation: no __module__; attributes cannot be added to functions dynamicallyUse an external dict FUNC_X[f]=... or a subclass/wrapper
locals() / eval() access to local variableslocals() returns a mapping of local names; eval can access local variablesLocals are implemented with a slot array; locals() does not keep local names, and eval uses only globalsAvoid relying on eval to access local variables; use explicit arguments or globals/closures instead
f-strings featuresSupports complex expressions, !a, etc.To save space: cannot concatenate literals containing braces, no !a, cannot handle unbalanced nestingIf complex, split into multiple steps or use +/format (note the slight differences)
Exception chainingDisplays context (During handling of the above...)Exception chaining is not implementedDo not rely on automatic chained display; manually include the original exception's information in the new exception
Exception attributesOnly some exceptions have value/errnoTo save implementation space, many exceptions have both value and errno (behavior differs)Use these fields only on StopIteration/OSError; or pass data through a subclass
OSError subclassesMapped to specific subclasses according to errno (FileNotFoundError, etc.)Only plain OSError exists; use e.errno to distinguishexcept OSError as e: handle_by_errno(e.errno)
bytes/bytearray behaviorSupports more methods/arguments (such as bytes(..., encoding=...), slicing, etc.)Some methods/keywords are not supported; slice step≠1 is often not supported; bytearray slice assignment requires the RHS to be array/bytesUse positional arguments, use explicit loops instead of stepped slicing, call list() first and then assign
Slice step ≠ 1Widely supported (str/bytes/list/tuple)Most built-in types support only step=1; otherwise NotImplementedErrorUse an explicit loop or build a new sequence first
memoryview safetyThe underlying object is protected and cannot be resized while a view existsDoes not prevent resizing of the underlying object, which may cause use-after-freeDo not change the length of the underlying object while holding a memoryview; use with caution
array / structStricter (type comparison, overflow checks, spaces in struct are ignored)Some features are missing: type code comparison/deletion/some checks are not implemented; struct behaves differently with regard to argument count or spacesManually mask out-of-range values, avoid spaces in format strings, and do not rely on automatic argument checks
randomgetrandbits(n) can return any n (limited by memory/implementation)The PRNG has only 32-bit state, so getrandbits returns at most 32 bits; randint is limited by the native word sizeIf large random numbers with many bits are needed, use the enhanced implementation in micropython-lib
struct.pack checksChecks the number of arguments and the formatToo many or too few arguments may not all raise an error, returning a partial packManually validate the argument length and avoid spaces in format strings
Keyword arguments of module functionsMost CPython functions accept keyword argumentsMany functions accept only positional arguments (signature ends with /)Use positional arguments (see the MicroPython documentation for signatures)
os / sys differencesos.environ, redirectable sys.stdin, etc.os.environ may not exist; sys.stdin/out/err are often read-only or missingUse getenv/putenv to manage the environment; do not try to rebind sys.stdin
range / big integer boundariesCorrectly handles very large ranges and raises appropriate errorsMay overflow or return an incorrect len on extreme start/stop valuesAvoid constructing very large ranges; check the sys.maxsize boundary
List slice-store with a non-iterable RHSCPython supports storing any iterable into a sliceMicroPython requires the RHS to be a list/tuple, otherwise TypeErrorConvert explicitly with list(iterable) before assigning

References

https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers/posts/664832

Version Record

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/16

Initialize the document, based on MicroPython version V1.23.0.

Added 5. MicroPython core development and supplementation: content on the differences between CPython and MicroPython.

Here, the content related to MicroPython kernel development has not been supplemented yet, and a separate chapter needs to be dedicated to it.

v1.1.0

Li Zisheng

2025/12/05

Figure captions have been added, and please note that the content in section 4.3.5 needs to be elaborated on in detail.