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:

Result: Adding M5Stack CoreS3 later reuses axp2101, ili9342c, ft6336u, and bm8563 with zero code duplication!


2. How PylotOS Boots (C -> Python Lifecycle)

  1. ESP-IDF Bootloader reads otadata (0xF000) and boots the active app partition (ota_0 or ota_1).
  2. Early C Startup (MICROPY_BOARD_STARTUP):
  1. MicroPython Task (mp_task):
  1. Frozen Python Kernel (kernel/pylot/):

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.