Tutorial: C HAL & MicroPython Architecture
This tutorial explains how PylotOS combines classical C hardware drivers with a MicroPython runtime without modifying a single file inside the upstream micropython/ repository.
1. The Four Layers
Layer 3: Python Runtime -> kernel/pylot/ (frozen ROM) + /vfs/apps/ (dynamic apps)
Layer 2: C <-> Python Glue -> cmodules/hal/, cmodules/sys_ota/, cmodules/sys_bridge/
Layer 1: Pure-C HAL -> drivers/ (reusable chip drivers) + boards/ (thin profiles)
Layer 0: ESP-IDF v5.5.2 -> FreeRTOS, esp_lcd, i2c_master, spi_master, esp_https_ota
Why Separate drivers/ from boards/?
In many embedded projects, LCD, touch, battery, and SD drivers are copy-pasted into every board directory. In PylotOS:
drivers/include/*.hdefines strict C vtables (hal_pmic_ops_t,hal_display_ops_t,hal_board_desc_t).drivers/<subsystem>/implements reusable chip drivers (e.g.,axp2101.c,ili9342c.c,ft6336u.c) that take GPIO/I2C/SPI handles as parameters — never hardcoded pins.boards/<board_id>/only defines pinouts (board_config.h), flash/PSRAM/partition settings (sdkconfig.board), andboard_init.cto wire the right drivers together.
Result: Adding M5Stack CoreS3 later reuses axp2101, ili9342c, ft6336u, and bm8563 with zero code duplication!
2. How PylotOS Boots (C -> Python Lifecycle)
- ESP-IDF Bootloader reads
otadata(0xF000) and boots the active app partition (ota_0orota_1). - Early C Startup (
MICROPY_BOARD_STARTUP):
boards/m5stack_core2/mpconfigboard.hpointsMICROPY_BOARD_STARTUPtopylotos_board_startup().- Before the MicroPython VM even starts,
pylotos_board_startup()runs MicroPython's default NVS/flash init (boardctrl_startup()) followed byhal_board_init()(initializing shared buses and PMIC power rails).
- MicroPython Task (
mp_task):
- Initializes heap (backed by 8 MiB PSRAM on Core2), mounts LittleFS (
vfspartition at/), and exposes allUSER_C_MODULES(import hal,import sys_ota).
- Frozen Python Kernel (
kernel/pylot/):
- Compiled into ROM via
kernel/manifest.py, soimport pylotalways works even if/vfsis wiped.
3. How a C Function Becomes a Python Function
Inside cmodules/hal/mod_hal.c:
// 1. Write the C implementation taking/returning mp_obj_t
static mp_obj_t hal_py_has_cap(mp_obj_t cap_obj) {
const char *cap_name = mp_obj_str_get_str(cap_obj);
const hal_board_desc_t *desc = hal_board_get_desc();
/* ... check bitmask ... */
return mp_obj_new_bool(found);
}
// 2. Wrap it as a 1-argument MicroPython function object
static MP_DEFINE_CONST_FUN_OBJ_1(hal_py_has_cap_obj, hal_py_has_cap);
// 3. Register it in the module dictionary and expose `import hal`
MP_REGISTER_MODULE(MP_QSTR_hal, mp_module_hal);
Because cmodules/micropython.cmake adds each module as a CMake INTERFACE library linked to usermod, MicroPython's build system automatically scans all MP_QSTR_* names and compiles the C code directly into the firmware image.