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 を得るには、まずターミナルを raw モードに設定する必要がある場合があります。

$ 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.cSRC_C リストに追加し、さらに同じファイルを SRC_QSTR に追加する新しい行を加える必要があります(この新しいファイル内で qstr が検索されるようにするため)。次のようになります。

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

SRC_QSTR += modmyport.c

すべてが正しく行われていれば、再ビルド後に新しいモジュールをインポートできるはずです。

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