移植 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

請記得使用正確的 tab 來縮排 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 這個新模組:

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