移植 MicroPython

MicroPython 项目包含针对不同微控制器系列和架构的若干移植。项目仓库有一个 ports 目录,其中为每个受支持的移植包含一个子目录。

一个移植通常会包含针对多个“开发板”的定义,每个开发板都是该移植可以运行其上的特定硬件,例如某个开发套件或设备。

minimal port 作为 MicroPython 移植的一个简化参考实现可供使用。它既可以在主机系统上运行,也可以在 STM32F4xx MCU 上运行。

一般来说,开始一项移植需要:

  • 设置工具链(配置 Makefile 等)。

  • 实现引导配置和 CPU 初始化。

  • 初始化开发和调试所需的基本驱动程序(例如 GPIO、UART)。

  • 执行特定于开发板的配置。

  • 实现特定于移植的模块。

最小 MicroPython 固件

开始将 MicroPython 移植到新开发板的最佳方式是先集成一个最小的 MicroPython 解释器。在本次演练中,请在 ports 目录中为新移植创建一个子目录:

$ cd ports
$ mkdir example_port

基本的 MicroPython 固件在主移植文件中实现,例如 main.c

#include "py/builtin.h"
#include "py/compile.h"
#include "py/gc.h"
#include "py/mperrno.h"
#include "shared/runtime/gchelper.h"
#include "shared/runtime/pyexec.h"

// Allocate memory for the MicroPython GC heap.
static char heap[4096];

int main(int argc, char **argv) {
    // Initialise the MicroPython runtime.
    mp_cstack_init_with_sp_here(2048);
    gc_init(heap, heap + sizeof(heap));
    mp_init();

    // Start a normal REPL; will exit when ctrl-D is entered on a blank line.
    pyexec_friendly_repl();

    // Deinitialise the runtime.
    gc_sweep_all();
    mp_deinit();
    return 0;
}

// Handle uncaught exceptions (should never be reached in a correct C implementation).
void nlr_jump_fail(void *val) {
    for (;;) {
    }
}

// Do a garbage collection cycle.
void gc_collect(void) {
    gc_collect_start();
    gc_helper_collect_regs_and_stack();
    gc_collect_end();
}

// There is no filesystem so stat'ing returns nothing.
mp_import_stat_t mp_import_stat(const char *path) {
    return MP_IMPORT_STAT_NO_EXIST;
}

// There is no filesystem so opening a file raises an exception.
mp_lexer_t *mp_lexer_new_from_file(qstr filename) {
    mp_raise_OSError(MP_ENOENT);
}

此时我们还需要为该移植准备一个 Makefile:

# Include the core environment definitions; this will set $(TOP).
include ../../py/mkenv.mk

# Include py core make definitions.
include $(TOP)/py/py.mk
include $(TOP)/extmod/extmod.mk

# Set CFLAGS and libraries.
CFLAGS += -I. -I$(BUILD) -I$(TOP)
LIBS += -lm

# Define the required source files.
SRC_C = \
    main.c \
    mphalport.c \
    shared/readline/readline.c \
    shared/runtime/gchelper_generic.c \
    shared/runtime/pyexec.c \
    shared/runtime/stdout_helpers.c \

# Define source files containing qstrs.
SRC_QSTR += shared/readline/readline.c shared/runtime/pyexec.c

# Define the required object files.
OBJ = $(PY_CORE_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o))

# Define the top-level target, the main firmware.
all: $(BUILD)/firmware.elf

# Define how to build the firmware.
$(BUILD)/firmware.elf: $(OBJ)
    $(ECHO) "LINK $@"
    $(Q)$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
    $(Q)$(SIZE) $@

# Include remaining core make rules.
include $(TOP)/py/mkrules.mk

请记得使用正确的制表符来缩进 Makefile。

MicroPython 配置

在集成上述最小代码后,下一步是为该移植创建 MicroPython 配置文件。编译期配置在 mpconfigport.h 中指定,而额外的硬件抽象函数(例如计时)在 mphalport.h 中指定。

以下是一个 mpconfigport.h 文件的示例:

#include <stdint.h>

// Python internal features.
#define MICROPY_ENABLE_GC                       (1)
#define MICROPY_HELPER_REPL                     (1)
#define MICROPY_ERROR_REPORTING                 (MICROPY_ERROR_REPORTING_TERSE)
#define MICROPY_FLOAT_IMPL                      (MICROPY_FLOAT_IMPL_FLOAT)

// Fine control over Python builtins, classes, modules, etc.
#define MICROPY_PY_ASYNC_AWAIT                  (0)
#define MICROPY_PY_BUILTINS_SET                 (0)
#define MICROPY_PY_ATTRTUPLE                    (0)
#define MICROPY_PY_COLLECTIONS                  (0)
#define MICROPY_PY_MATH                         (0)
#define MICROPY_PY_IO                           (0)
#define MICROPY_PY_STRUCT                       (0)

// Type definitions for the specific machine.

typedef long mp_off_t;

// We need to provide a declaration/definition of alloca().
#include <alloca.h>

// Define the port's name and hardware.
#define MICROPY_HW_BOARD_NAME "example-board"
#define MICROPY_HW_MCU_NAME   "unknown-cpu"

#define MP_STATE_PORT MP_STATE_VM

此配置文件包含特定于机器的配置,涉及诸如是否应启用不同的 MicroPython 特性等方面,例如 #define MICROPY_ENABLE_GC (1)。将其设置为 (0) 会禁用该特性。

其他配置包括类型定义、根指针、开发板名称、微控制器名称等。

类似地,一个最小的 mphalport.h 文件示例如下:

static inline void mp_hal_set_interrupt_char(char c) {}

对标准输入/输出的支持

MicroPython 至少需要一种输出字符的方式,而要拥有 REPL,它还需要一种输入字符的方式。实现这些功能的函数可以在文件 mphalport.c 中实现,例如:

#include <unistd.h>
#include "py/mpconfig.h"

// Receive single character, blocking until one is available.
int mp_hal_stdin_rx_chr(void) {
    unsigned char c = 0;
    int r = read(STDIN_FILENO, &c, 1);
    (void)r;
    return c;
}

// Send the string of given length.
void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) {
    int r = write(STDOUT_FILENO, str, len);
    (void)r;
}

这些输入和输出函数必须根据具体的开发板 API 进行修改。本示例使用标准输入/输出流。

构建与运行

在此阶段,新移植的目录应包含::

ports/example_port/
├── main.c
├── Makefile
├── mpconfigport.h
├── mphalport.c
└── mphalport.h

现在可以通过运行 make(或视你的系统而定的其他方式)来构建该移植。

如果你使用上面给出的 Makefile 中的默认编译器设置,那么这将创建一个名为 build/firmware.elf 的可执行文件,它可以直接执行。要获得一个可用的 REPL,你可能需要先将终端配置为原始模式:

$ stty raw opost -echo
$ ./build/firmware.elf

这应该会给你一个 MicroPython REPL。然后你可以运行以下命令:

MicroPython v1.26.0-preview on 2025-08-01; minimal with unknown-cpu
>>> def sum(n, m):
...     return n + m
...
>>> 3, 4, sum(3, 4)
(3, 4, 7)
>>>

使用 Ctrl-D 退出,然后运行 reset 以重置终端。

向移植添加模块

要添加诸如 myport 之类的自定义模块,首先在文件 modmyport.c 中添加模块定义:

#include "py/runtime.h"

static mp_obj_t myport_info(void) {
    mp_printf(&mp_plat_print, "info about my port\n");
    return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_0(myport_info_obj, myport_info);

static const mp_rom_map_elem_t myport_module_globals_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_myport) },
    { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&myport_info_obj) },
};
static MP_DEFINE_CONST_DICT(myport_module_globals, myport_module_globals_table);

const mp_obj_module_t myport_module = {
    .base = { &mp_type_module },
    .globals = (mp_obj_dict_t *)&myport_module_globals,
};

MP_REGISTER_MODULE(MP_QSTR_myport, myport_module);

你还需要编辑 Makefile,将 modmyport.c 添加到 SRC_C 列表中,并新增一行将同一文件添加到 SRC_QSTR(以便在这个新文件中搜索 qstr),如下所示:

SRC_C = \
    main.c \
    modmyport.c \
    mphalport.c \
    ...

SRC_QSTR += modmyport.c

如果一切正确,那么在重新构建后,你应该能够导入这个新模块:

>>> import myport
>>> myport.info()
info about my port
>>>