micropython-skills
AI Agent programmable co-processor skill collection. You (the Agent) generate MicroPython code,
push it to devices via REPL, parse structured output, and iterate — turning hardware into your
extended capability.
Quick Start
Python command: Use python3 on macOS/Linux, python on Windows.
On Windows, python3 is often a Microsoft Store stub that silently fails (exit code 49).
On macOS/Linux, python may not exist or may point to Python 2.
Every interaction follows this flow:
- 1. Probe — Run
python3 {SKILL_DIR}/scripts/device_probe.py to discover connected devices
-
status: "ok" → Device has MicroPython, proceed to step 2
-
status: "no_firmware" → ESP chip detected but no MicroPython. Ask user to confirm, then flash:
python3 {SKILL_DIR}/scripts/firmware_flash.py --port PORT --yes
-
status: "no_device" → No device connected. Guide user to connect hardware.
-
status: "permission_denied" → Serial port not accessible. On Linux:
sudo chmod 666 /dev/ttyACM0. On Windows: check Device Manager for driver issues.
- 2. Connect — Default: USB via mpremote. Optional: WiFi via WebREPL (user must request)
- Execute — Generate MicroPython code and push to device
- Parse — Scan stdout for tagged lines (RESULT:/ERROR:/STATUS:/LOG:)
- Iterate — Adjust code based on results, repeat steps 3-5
Where {SKILL_DIR} is the directory containing this SKILL.md file.
Connection Management
Default: USB (mpremote)
Always start by probing for devices:
CODEBLOCK0
Execute code on device:
CODEBLOCK1
Run a script file:
CODEBLOCK2
For multi-line code, write a temporary .py file locally, then mpremote run /path/to/task.py.
Serial port names vary by platform:
| Platform | Port Format | Example |
|---|
| Linux | /dev/ttyUSB0, /dev/ttyACM0 | INLINECODE14 |
| macOS |
/dev/cu.usbserial-
, /dev/cu.usbmodem |
mpremote connect /dev/cu.usbmodem14101 |
| Windows | COM3, COM4, ... |
mpremote connect COM3 |
The scripts auto-detect the port — you rarely need to specify it manually.
Optional: WiFi (WebREPL)
Only switch to WiFi when the user explicitly requests it. The switch flow:
- 1. Ask user for WiFi SSID and password
- Push WiFi + WebREPL config to device via USB:
python3 {SKILL_DIR}/scripts/wifi_setup.py --ssid "SSID" --password "PASS" --webrepl-password "repl123"
- 3. Note the IP address from the output
- From now on, execute code over WiFi:
python3 {SKILL_DIR}/scripts/webrepl_exec.py --host 192.168.1.100 --password repl123 --code "print('hello')"
- 5. USB cable can be disconnected
For detailed command reference, read ./references/connections.md.
Sub-skill Router
Based on user intent, read the corresponding sub-skill for domain-specific templates:
| User Intent Keywords | Sub-skill Path | Safety Tier |
|---|
| temperature, humidity, DHT, BME280, pressure, IMU, accelerometer, ADC, analog, ultrasonic, light sensor, photoresistor, read sensor | INLINECODE18 | Safe |
| GPIO, LED, blink, PWM, servo, motor, stepper, relay, NeoPixel, WS2812, buzzer, output, control, drive |
./skills/actuator/SKILL.md | Cautious |
| WiFi, MQTT, HTTP, BLE, Bluetooth, NTP, WebSocket, AP mode, network, connect internet, publish, subscribe |
./skills/network/SKILL.md | Cautious |
| PID, filter, Kalman, state machine, scheduler, data logging, moving average, control loop, algorithm |
./skills/algorithm/SKILL.md | Safe |
| scan I2C, scan SPI, device info, memory, filesystem, diagnose, health check, benchmark, pin state, what's connected |
./skills/diagnostic/SKILL.md | Safe |
| save to device, 保存到设备, 开机自启, auto start, 下次还能用, persist, 断电保存 | See "Program Persistence" section below | Cautious/Dangerous |
| flash firmware, burn firmware, install MicroPython, no firmware, 烧录, 刷固件, 刷机 |
scripts/firmware_flash.py | Dangerous |
| recovery, not responding, stuck, boot.py, main.py, reflash, brick |
./references/safety.md | Dangerous |
When a task spans multiple domains (e.g., "read sensor and publish via MQTT"), read all relevant sub-skills.
Structured Output Protocol
All MicroPython code you generate for the device MUST use tagged output lines:
| Tag | Purpose | Example |
|---|
| INLINECODE25 | Success data (JSON) | INLINECODE26 |
| INLINECODE27 |
Error info |
ERROR:OSError: [Errno 19] ENODEV |
|
STATUS: | Status indicator |
STATUS:ok |
|
LOG: | Debug info |
LOG:sampling at 100Hz |
Code template — every snippet you generate should follow this pattern:
CODEBLOCK5
Parse rules:
- - Scan device stdout line by line
- Extract lines starting with
RESULT:, ERROR:, STATUS:, INLINECODE36 - Ignore all other output (MicroPython boot messages, REPL prompts, etc.)
- If
ERROR: is found, diagnose and retry with adjusted code
Safety Rules
| Tier | Operations | Agent Behavior |
|---|
| Safe | Sensor read, I2C/SPI scan, memory check, pin read, diagnostics | Execute directly |
| Cautious |
GPIO output, PWM, WiFi connect, file write on device | Inform user what you're about to do, then execute |
| Dangerous | Overwrite boot.py/main.py, format filesystem, OTA update, flash firmware |
Must get explicit user confirmation. Always backup first:
mpremote fs cp :boot.py /tmp/boot.py.bak |
Hard constraints:
- - Never hardcode WiFi passwords in scripts saved to device — use variables or prompt user
- All loops must have iteration limits or timeouts — never generate infinite loops without exit conditions
- Before overwriting boot.py or main.py, always backup the existing file first
- Before controlling high-current devices (motors, relays), ask user to confirm wiring
For complete recovery procedures, read ./references/safety.md.
Workflow
As the Agent operating this co-processor, follow this mental model:
- 1. Understand intent — What does the user want to achieve with the hardware?
- Check connection — Run device_probe.py if you haven't yet. Know your device's platform and capabilities.
- Route to sub-skill — Read the relevant sub-skill SKILL.md for code templates and domain knowledge
- Generate code — Write MicroPython code following the output protocol. Adapt pin numbers and parameters to the target platform.
- Push and capture — Execute via mpremote or WebREPL, capture full stdout
- Parse results — Extract RESULT:/ERROR: lines, parse JSON data
- Decide next step — If ERROR, diagnose and adjust. If RESULT, present to user or use for next operation.
- Maintain state — Remember which pins are in use, which peripherals are initialized, what the device's platform is
- Offer persistence — After a program runs successfully, ask the user if they want to save it to the device or set it to auto-start on boot
Program Persistence
After a program runs successfully, offer the user two options:
Option 1: Save to Device (for later manual use)
Save the script to the device's filesystem so it can be run anytime without re-uploading:
CODEBLOCK6
This is a Cautious operation — inform the user before writing files to the device.
Option 2: Auto-start on Boot (write to main.py)
If the user wants the program to run automatically every time the device powers on:
- 1. Always ask first — "要设置为开机自动运行吗?注意:如果程序有问题可能导致设备无法正常连接。"
- Backup existing main.py (if any):
mpremote fs cp :main.py ./main.py.bak
- 3. Upload as main.py:
mpremote fs cp local_script.py :main.py
- 4. Important: For auto-start scripts, wrap the main logic in a try/except and add a short startup delay so the user can interrupt if needed:
CODEBLOCK9
This is a Dangerous operation — require explicit user confirmation.
Disable Auto-start
If the device becomes hard to access due to a problematic main.py:
CODEBLOCK10
If the device is completely unresponsive, follow the recovery steps in ./references/safety.md.
Platform Adaptation
After probing, adapt code to the detected platform:
| Platform | Key Capabilities |
|---|
| esp32 / esp32s3 | WiFi, BLE, Touch Pad, Deep Sleep, ULP, Hall Sensor |
| rp2040 |
PIO state machines, dual core, no WiFi (unless Pico W) |
| stm32 | More timers, CAN bus, DAC |
| Generic | Standard
machine module API only |
For ESP32-specific pin maps and APIs, read ./references/esp32.md.
Reference Files
Read these on demand — not every interaction needs them:
| File | When to Read |
|---|
| INLINECODE43 | Troubleshooting connection issues, mpremote advanced usage, WebREPL protocol details |
| INLINECODE44 |
ESP32-specific pin maps, strapping pin warnings, deep sleep, NVS, BLE/WiFi API details |
|
./references/safety.md | Device recovery, boot.py restore, filesystem repair, electrical safety |
Dependencies
Agent-side requirements:
- -
mpremote — pip install mpremote (required for USB connection) - INLINECODE48 —
pip install esptool (required for chip detection and firmware flashing) - INLINECODE50 —
pip install pyserial (required on Windows for COM port auto-detection; recommended on all platforms) - INLINECODE52 —
pip install websocket-client (only needed for WiFi/WebREPL mode) - Python 3.8+
Windows notes:
- - Use
python instead of python3 to run scripts. On many Windows systems, python3 is a Microsoft Store stub that returns exit code 49. On macOS/Linux, use python3. - Without
pyserial, the scripts fall back to parsing the mode command output for COM port detection, which provides less detail (no VID/PID info). Install pyserial for best results.
Device-side requirements:
- - MicroPython firmware v1.19+ (v1.22+ recommended) — auto-installed by
firmware_flash.py if missing - USB connection or WiFi reachability
External Endpoints
This skill accesses external services during specific operations:
| Endpoint | When Accessed | Purpose | Required? |
|---|
| INLINECODE62 | Firmware flashing only (firmware_flash.py) | Download latest stable MicroPython firmware binary for the detected chip | Only when flashing firmware |
| INLINECODE64 |
Firmware flashing only | Direct firmware
.bin download URL | Only when flashing firmware |
No telemetry, analytics, or data is sent to any external service. The skill operates entirely locally except for firmware downloads.
Security & Privacy
- - No data collection: This skill does not collect, transmit, or store any user data
- No telemetry: No usage analytics, crash reports, or tracking of any kind
- Local-only operation: All device communication happens over local USB serial or local WiFi (WebREPL). No cloud relay or proxy is used
- WiFi credentials: When provided by the user, WiFi credentials are passed directly to the device via
mpremote and written to the device's boot.py. They are never logged, stored on the host machine, or transmitted to external services - Firmware source: Firmware binaries are downloaded exclusively from
micropython.org, the official MicroPython project site - File system access: Helper scripts only access serial ports and the system temp directory (for firmware caching). No other host files are read or modified
Trust & Verification
- - Open source: Full source code is available at the homepage repository
- No obfuscation: All Python scripts and Markdown files are human-readable
- Auditable: The
scripts/ directory contains 4 self-contained Python scripts with no external dependencies beyond mpremote, esptool, pyserial, and INLINECODE73 - Evals included: The
evals/evals.json file contains 5 test scenarios covering device probe, sensor read, actuator control, diagnostics, and recovery
micropython-skills
AI Agent可编程协处理器技能集合。你(Agent)生成MicroPython代码,通过REPL将其推送到设备,解析结构化输出,并进行迭代——将硬件转化为你的扩展能力。
快速开始
Python命令:macOS/Linux使用python3,Windows使用python。
在Windows上,python3通常是Microsoft Store的存根程序,会静默失败(退出码49)。
在macOS/Linux上,python可能不存在或指向Python 2。
每次交互遵循以下流程:
- 1. 探测 — 运行python3 {SKILLDIR}/scripts/deviceprobe.py发现连接的设备
- status: ok → 设备有MicroPython,进入步骤2
- status: no
firmware → 检测到ESP芯片但没有MicroPython。请用户确认,然后刷写:python3 {SKILLDIR}/scripts/firmware_flash.py --port PORT --yes
- status: no_device → 没有连接设备。引导用户连接硬件。
- status: permission_denied → 串口不可访问。Linux上:sudo chmod 666 /dev/ttyACM0。Windows上:检查设备管理器中的驱动问题。
- 2. 连接 — 默认:通过mpremote使用USB。可选:通过WebREPL使用WiFi(用户必须请求)
- 执行 — 生成MicroPython代码并推送到设备
- 解析 — 扫描stdout中的标记行(RESULT:/ERROR:/STATUS:/LOG:)
- 迭代 — 根据结果调整代码,重复步骤3-5
其中{SKILL_DIR}是包含此SKILL.md文件的目录。
连接管理
默认:USB(mpremote)
始终从探测设备开始:
bash
python3 {SKILLDIR}/scripts/deviceprobe.py
在设备上执行代码:
bash
mpremote exec import machine; print(RESULT: + str(machine.freq()))
运行脚本文件:
bash
mpremote run script.py
对于多行代码,在本地编写临时.py文件,然后mpremote run /path/to/task.py。
串口名称因平台而异:
| 平台 | 端口格式 | 示例 |
|---|
| Linux | /dev/ttyUSB0, /dev/ttyACM0 | mpremote connect /dev/ttyACM0 |
| macOS |
/dev/cu.usbserial-
, /dev/cu.usbmodem | mpremote connect /dev/cu.usbmodem14101 |
| Windows | COM3, COM4, ... | mpremote connect COM3 |
脚本会自动检测端口——你很少需要手动指定。
可选:WiFi(WebREPL)
仅在用户明确请求时才切换到WiFi。切换流程:
- 1. 询问用户的WiFi SSID和密码
- 通过USB将WiFi + WebREPL配置推送到设备:
bash
python3 {SKILL
DIR}/scripts/wifisetup.py --ssid SSID --password PASS --webrepl-password repl123
- 3. 从输出中记下IP地址
- 此后,通过WiFi执行代码:
bash
python3 {SKILL
DIR}/scripts/webreplexec.py --host 192.168.1.100 --password repl123 --code print(hello)
- 5. USB线可以断开
详细命令参考,请阅读./references/connections.md。
子技能路由
根据用户意图,读取相应的子技能以获取领域特定模板:
| 用户意图关键词 | 子技能路径 | 安全等级 |
|---|
| 温度、湿度、DHT、BME280、气压、IMU、加速度计、ADC、模拟、超声波、光敏传感器、光敏电阻、读取传感器 | ./skills/sensor/SKILL.md | 安全 |
| GPIO、LED、闪烁、PWM、舵机、电机、步进电机、继电器、NeoPixel、WS2812、蜂鸣器、输出、控制、驱动 |
./skills/actuator/SKILL.md | 谨慎 |
| WiFi、MQTT、HTTP、BLE、蓝牙、NTP、WebSocket、AP模式、网络、连接互联网、发布、订阅 | ./skills/network/SKILL.md | 谨慎 |
| PID、滤波器、卡尔曼、状态机、调度器、数据记录、移动平均、控制循环、算法 | ./skills/algorithm/SKILL.md | 安全 |
| 扫描I2C、扫描SPI、设备信息、内存、文件系统、诊断、健康检查、基准测试、引脚状态、已连接什么 | ./skills/diagnostic/SKILL.md | 安全 |
| 保存到设备、save to device、开机自启、auto start、下次还能用、persist、断电保存 | 参见下方程序持久化部分 | 谨慎/危险 |
| 刷写固件、烧录固件、安装MicroPython、无固件、烧录、刷固件、刷机 | scripts/firmware_flash.py | 危险 |
| 恢复、无响应、卡住、boot.py、main.py、重新刷写、变砖 | ./references/safety.md | 危险 |
当任务跨越多个领域时(例如读取传感器并通过MQTT发布),读取所有相关的子技能。
结构化输出协议
你为设备生成的所有MicroPython代码必须使用标记输出行:
| 标记 | 用途 | 示例 |
|---|
| RESULT: | 成功数据(JSON) | RESULT:{temp:23.5,hum:61} |
| ERROR: |
错误信息 | ERROR:OSError: [Errno 19] ENODEV |
| STATUS: | 状态指示 | STATUS:ok |
| LOG: | 调试信息 | LOG:sampling at 100Hz |
代码模板——你生成的每个代码片段应遵循此模式:
python
import json
from machine import Pin
try:
# ... 你的操作在这里 ...
print(RESULT: + json.dumps({key: value}))
except Exception as e:
print(ERROR: + str(e))
解析规则:
- - 逐行扫描设备stdout
- 提取以RESULT:、ERROR:、STATUS:、LOG:开头的行
- 忽略所有其他输出(MicroPython启动消息、REPL提示等)
- 如果发现ERROR:,诊断并用调整后的代码重试
安全规则
| 等级 | 操作 | Agent行为 |
|---|
| 安全 | 传感器读取、I2C/SPI扫描、内存检查、引脚读取、诊断 | 直接执行 |
| 谨慎 |
GPIO输出、PWM、WiFi连接、设备上写文件 | 告知用户将要执行的操作,然后执行 |
| 危险 | 覆盖boot.py/main.py、格式化文件系统、OTA更新、刷写固件 |
必须获得用户明确确认。始终先备份:mpremote fs cp :boot.py /tmp/boot.py.bak |
硬约束:
- - 切勿在保存到设备的脚本中硬编码WiFi密码——使用变量或提示用户
- 所有循环必须有迭代限制或超时——切勿生成没有退出条件的无限循环
- 在覆盖boot.py或main.py之前,始终先备份现有文件
- 在控制大电流设备(电机、继电器)之前,请用户确认接线
完整的恢复流程,请阅读./references/safety.md。
工作流程
作为操作此协处理器的Agent,遵循以下思维模型:
- 1. 理解意图 — 用户希望通过硬件实现什么?
- 检查连接 — 如果尚未运行,运行device_probe.py。了解设备的平台和能力。
- 路由到子技能 — 读取相关子技能的SKILL.md以获取代码模板和领域知识
- 生成代码 — 按照输出协议编写MicroPython代码。根据目标平台调整引脚编号和参数。
- 推送并捕获 — 通过mpremote或WebREPL执行,捕获完整stdout
- 解析结果 — 提取RESULT:/ERROR:行,解析JSON数据
- 决定下一步 — 如果是ERROR,诊断并调整。如果是RESULT,呈现给用户或用于下一步操作。
- 维护状态 — 记住哪些引脚正在使用,哪些外设已初始化,设备的平台是什么
- 提供持久化 — 程序成功运行后,询问用户是否要保存到设备或设置为开机自启
程序持久化
程序成功运行后,为用户提供两个选项:
选项1:保存到设备(供后续手动使用)
将脚本保存