一、项目背景:工业温度计需求
硬件规格
- 主控芯片:STM32F103C8T6(ARM Cortex-M3)
- 温度传感器:DS18B20(-55°C ~ +125°C,精度±0.5°C)
- 显示:0.96寸 OLED(I2C接口)
- 通信:USART1(调试信息输出)
- 供电:12V DC → 5V → 3.3V
功能需求
- 采集 DS18B20 温度,每秒刷新一次
- OLED 实时显示温度值(保留1位小数)
- 温度超过阈值时,LED 报警
- USART 输出温度日志
- 按键可设置报警阈值(上下限)
代码仓库结构
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:
- build — ARM GCC 编译固件,上传 .hex / .bin
- unit-test — PC端单元测试,生成测试报告
- integration-test — Python + 串口集成测试(需要硬件)
- 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 1 | PC端单元测试 | ~50% | 50% |
| Level 2 | PC端 + 集成测试 | ~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