入门篇:从 Arduino IDE 迁移到专业工具链

知识库
知识库文档
/tech-stacks/platformio/tutorial/入门篇:从 Arduino IDE 迁移到专业工具链.md

文档

PlatformIO 开发全流程

本章目标

掌握 PlatformIO 的项目管理、库依赖、调试和 CI/CD 集成,从 Arduino IDE 用户升级为专业嵌入式开发者。


1. 为什么从 Arduino IDE 迁移到 PlatformIO?

痛点 Arduino IDE PlatformIO
代码补全 基本无 完整 IntelliSense
多文件项目 手动管理 tabs 文件夹树形结构
库版本管理 全局安装 项目级 .ini 声明
Git 友好 需要手动整理 .ini + src/ 即可
多板支持 切换板卡管理器 [env:xxx] 多环境
CI/CD 困难 命令行原生支持

2. platformio.ini 详解

[platformio]
default_envs = uno

[env:uno]
platform = atmelavr
board = uno
framework = arduino
monitor_speed = 115200

; 库依赖
lib_deps =
    adafruit/DHT sensor library @ ^1.4.4    ; 语义版本
    https://github.com/me/my-lib.git          ; Git 仓库
    symlink://../my-local-lib                 ; 本地库

; 编译标志
build_flags =
    -D DEBUG_MODE
    -D VERSION_STRING=\"1.0.0\"

; 上传配置
upload_port = /dev/ttyUSB0
upload_speed = 115200

; 自定义脚本
extra_scripts = pre:build_info.py

库依赖三种方式

语法 场景
owner/lib @ ^1.2.3 PlatformIO Registry 中的库
https://github.com/... Git 仓库(私有库用 git+ssh://
symlink://path 本地开发的库

3. 项目目录结构

my-firmware/
├── platformio.ini          ← 项目配置核心
├── src/
│   ├── main.cpp            ← 入口
│   └── modules/
│       ├── sensor.cpp
│       └── sensor.h
├── include/
│   └── config.h
├── lib/
│   └── my-custom-lib/      ← 项目私有库
├── test/
│   └── test_sensor.cpp     ← 单元测试
└── data/                   ← ESP8266/ESP32 SPIFFS 数据

4. 调试与日志

条件编译日志宏

// debug.h
#pragma once
#include <Arduino.h>

#ifdef DEBUG_MODE
  #define LOG_INFO(fmt, ...)  Serial.printf("[INFO] " fmt "\n", ##__VA_ARGS__)
  #define LOG_WARN(fmt, ...)  Serial.printf("[WARN] " fmt "\n", ##__VA_ARGS__)
  #define LOG_ERR(fmt, ...)   Serial.printf("[ERR]  " fmt "\n", ##__VA_ARGS__)
#else
  #define LOG_INFO(...)
  #define LOG_WARN(...)
  #define LOG_ERR(...)
#endif

单元测试(Unity 框架)

// test/test_sensor.cpp
#include <unity.h>
#include "sensor.h"

void test_temperature_conversion() {
    float expected = 25.0;
    float actual = raw_to_celsius(512, 10);  // 10bit ADC
    TEST_ASSERT_FLOAT_WITHIN(0.5, expected, actual);
}

int main() {
    UNITY_BEGIN();
    RUN_TEST(test_temperature_conversion);
    return UNITY_END();
}

运行:pio test -e uno


5. CI/CD 集成

GitHub Actions

# .github/workflows/build.yml
name: PlatformIO CI
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/cache@v3
        with:
          path: ~/.platformio
          key: ${{ runner.os }}-pio
      - uses: actions/setup-python@v4
        with: { python-version: '3.10' }
      - run: pip install platformio
      - run: pio run -e uno -e esp32

6. 实用技巧

  • pio device list — 列出串口设备
  • pio lib search "DHT22" — 搜索库
  • pio system info — 系统诊断
  • pio run -t clean — 清理构建
  • pio run --verbose — 详细输出(调试用)

思考题

  1. PlatformIO 的 ${common.xxx} 继承语法适用什么场景?
  2. 为什么 ESP32 项目建议用 monitor_filters = esp32_exception_decoder
  3. 如何为团队项目固定工具链版本?

信息

路径
/tech-stacks/platformio/tutorial/入门篇:从 Arduino IDE 迁移到专业工具链.md
更新时间
2026/5/31