作者:Leonard(QA测试工程师)| 日期:2026-04-16 | 目标读者:嵌入式开发工程师、Team Leader、想提升研发效率的团队

一、项目背景:工业温度计需求

硬件规格

  • 主控芯片:STM32F103C8T6(ARM Cortex-M3)
  • 温度传感器:DS18B20(-55°C ~ +125°C,精度±0.5°C)
  • 显示:0.96寸 OLED(I2C接口)
  • 通信:USART1(调试信息输出)
  • 供电:12V DC → 5V → 3.3V

功能需求

  1. 采集 DS18B20 温度,每秒刷新一次
  2. OLED 实时显示温度值(保留1位小数)
  3. 温度超过阈值时,LED 报警
  4. USART 输出温度日志
  5. 按键可设置报警阈值(上下限)

代码仓库结构

stm32-thermometer/
├── Core/                  # HAL库核心文件(STM32CubeMX生成)
├── Drivers/              # 外设驱动(含 DS18B20)
├── App/                  # 应用层代码
├── Tests/                # 单元测试(PC端,含 Unity 框架)
├── Makefile
└── .github/workflows/ci.yml

二、整体架构:CI/CD 流水线

阶段工具做什么
编译构建ARM GCC + Makefile交叉编译,生成 .hex / .bin
单元测试Unity (PC端)测试纯C逻辑函数,不依赖硬件
集成测试Python + 串口自动化测试目标板功能
固件上传stm32flash / OpenOCD自动烧录(可选)
测试报告CTest + JUnit XML生成可视化报告

三、环境准备:工具链安装(Ubuntu)

sudo apt-get update
sudo apt-get install -y gcc-arm-none-eabi binutils-arm-none-eabi stm32flash openocd git
sudo apt-get install -y python3 python3-pip
pip3 install pyserial pytest pytest-html Jinja2

四、核心代码实现

DS18B20 驱动(drivers/ds18b20.c)

DS18B20 单总线驱动,通过 PA8 采集温度数据,12位分辨率,返回温度值×10(例如 250 = 25.0°C)。

温度采集(app/temperature.c)

  • 滑动平均滤波(窗口=5)
  • 传感器状态检测(DS18B20 未连接返回 85°C)
  • 日志输出格式:[TEMP] 25.0C, status=0

报警模块(app/alarm.c)

温度超限时触发 LED 和蜂鸣器,支持上下限阈值设置。


五、单元测试(PC端)

使用 Unity 测试框架,在不连接硬件的情况下验证温度计算逻辑:

cd Tests
gcc -I unity -I .. -o test_runner test_temperature.c unity/unity.c -lm
./test_runner

测试用例(共6个):

  • test_DS18B20_normal_read:正常温度读取(25.0°C)
  • test_DS18B20_negative:零下温度(-10.5°C)
  • test_filter_smooth:滑动平均滤波
  • test_format_positive:正数格式化
  • test_format_negative:负数格式化
  • test_alarm_threshold:报警阈值判断

六、GitHub Actions CI/CD 配置

创建 .github/workflows/ci.yml,包含4个 Job:

  1. build — ARM GCC 编译固件,上传 .hex / .bin
  2. unit-test — PC端单元测试,生成测试报告
  3. integration-test — Python + 串口集成测试(需要硬件)
  4. code-quality — cppcheck 静态代码分析

七、集成测试(Python + 串口)

Tests/hardware/test_integration.py 包含:

  • 温度输出格式验证
  • 温度值范围检查
  • 传感器状态查询
  • 报警功能测试
  • 阈值设置与读取
  • 固件版本查询
  • 重启功能测试
python3 -m pytest test_integration.py -v --html=report.html --self-contained-html

八、效果对比

阶段测试方式覆盖率人工介入
Level 0手动调试(kill)~20%100%
Level 1PC端单元测试~50%50%
Level 2PC端 + 集成测试~80%20%
Level 3全自动CI/CD~90%+5%

九、推荐落地路径

  • 第1周:搭建单元测试环境,接入 Unity 框架
  • 第2周:接入 GitHub Actions,实现编译+测试自动化
  • 第3周:编写 Python 集成测试脚本
  • 第4周:代码质量检查 + 测试报告优化

十、参考资源

资源链接
ARM GCC 工具链https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm
Unity 测试框架https://github.com/ThrowTheSwitch/Unity
GitHub Actions 文档https://docs.github.com/en/actions
pytest 文档https://docs.pytest.org/

本文档由 Leonard(QA测试工程师)编写 | 2026-04-16