Python 串口上位机(推荐学习)
约定串口数据格式,用 uv 项目中的 pyserial 与 matplotlib 读取单片机数据、实时绘制曲线并保存 CSV。
先约定一种程序能读的格式
LAB 004 的串口日志是写给人看的,每条格式不完全一样,程序很难稳定解析。电脑上的程序(上位机)要读取数据,先让单片机额外输出一种固定格式的数据行:
DATA,1523,1489,36.8 每行以 DATA 开头,逗号分隔,依次是温度传感器原始值、VREFINT 原始值、芯片结温估算值(保留一位小数),以换行结束。其他日志照常输出,上位机只处理以 DATA, 开头的行。
在当前 STM32F103 工程(LAB 004 板载外设控制器)中增加数据流输出,保留全部已有功能和日志。
新增串口命令 stream on 和 stream off:开启后每 200 ms 输出一行
DATA,温度传感器原始值,VREFINT 原始值,芯片结温估算值(一位小数)
行尾使用 \r\n,同一行中不夹杂其他内容;stream off 后停止输出。默认关闭。
确认 9600 波特率下 200 ms 一行不会阻塞其他功能,说明修改的文件,编译、烧录,
用串口助手验证后提交 Git。 可见成果:串口助手中输入 stream on 后,每 0.2 秒出现一行 DATA, 开头的数据;输入 stream off 后停止。
创建上位机项目
按 Python 环境与虚拟环境入门的流程,在项目根目录创建一个独立的 Python 项目,与单片机工程并列:
cd D:\Projects\STM32_Learn
uv init stm32-monitor --no-package --python 3.13
cd stm32-monitor
uv add pyserial matplotlib pyserial 负责串口通信,matplotlib 负责画图。之后的目录结构是:
D:\Projects\STM32_Learn
├─ Doc\
├─ STM32F103\
├─ RT-Thread-nano\
└─ stm32-monitor\ Python 上位机
├─ pyproject.toml
├─ uv.lock
└─ .venv\ 不提交到 Git 执行 git status --short,确认列表中没有 .venv。如果出现了,在根目录的 .gitignore 中加入一行 .venv/。
查看电脑当前识别到的串口:
uv run python -m serial.tools.list_ports 读取串口数据
在 stm32-monitor 中新建 read_serial.py,把 PORT 改成上一步看到的实际 COM 口:
import serial
PORT = "COM4" # 改成实际的 COM 口
BAUDRATE = 9600 # 与 LAB 004 的串口设置一致
with serial.Serial(PORT, BAUDRATE, timeout=1) as port:
port.write(b"stream on\r\n")
try:
while True:
line = port.readline().decode("utf-8", errors="replace").strip()
if line.startswith("DATA,"):
print(line)
except KeyboardInterrupt:
port.write(b"stream off\r\n") 运行前先关闭串口助手:同一个 COM 口同时只能被一个程序打开,否则会提示 PermissionError 或 “拒绝访问”。
uv run read_serial.py readline 读到换行符为止;timeout=1 表示最多等 1 秒,没有数据时返回空内容,程序不会卡死。按 Ctrl + C 结束时,脚本会发送 stream off 关闭数据流。
实时绘制曲线
新建 plot_serial.py,持续读取数据并刷新曲线,只保留最近 300 个点(200 ms 一个点,约 1 分钟):
from collections import deque
import matplotlib.pyplot as plt
import serial
from matplotlib.animation import FuncAnimation
PORT = "COM4"
BAUDRATE = 9600
MAX_POINTS = 300 # 200 ms 一个点,约显示最近 60 秒
port = serial.Serial(PORT, BAUDRATE, timeout=0) # timeout=0:有多少读多少,不等待
port.write(b"stream on\r\n")
temperatures = deque(maxlen=MAX_POINTS)
pending = b""
figure, axis = plt.subplots()
(curve,) = axis.plot([], [])
axis.set_xlabel("sample")
axis.set_ylabel("chip temperature estimate (C)")
def update(_frame):
global pending
pending += port.read(port.in_waiting or 1)
*lines, pending = pending.split(b"\n") # 最后一段可能不完整,留到下次拼接
for raw in lines:
fields = raw.decode("utf-8", errors="replace").strip().split(",")
if len(fields) == 4 and fields[0] == "DATA":
try:
temperatures.append(float(fields[3]))
except ValueError:
pass # 跳过传输出错的行
curve.set_data(range(len(temperatures)), temperatures)
axis.relim()
axis.autoscale_view()
return (curve,)
animation = FuncAnimation(figure, update, interval=100, cache_frame_data=False)
plt.show() # 关闭窗口后继续执行下面两行
port.write(b"stream off\r\n")
port.close() uv run plot_serial.py 用手指轻按芯片几秒,曲线会缓慢上升。坐标轴标题使用英文,是因为 matplotlib 默认字体不含中文,直接写中文会显示为方框。
可见成果:弹出的窗口中出现一条持续向右延伸的温度曲线;关闭窗口后,串口助手中不再收到 DATA 行。
保存数据并继续扩展
需要事后分析时,把数据保存为 CSV 文件,可以直接用 Excel 打开。在 read_serial.py 的基础上加入时间戳和文件写入:
import csv
from datetime import datetime
import serial
PORT = "COM4"
BAUDRATE = 9600
with serial.Serial(PORT, BAUDRATE, timeout=1) as port, \
open("data.csv", "w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(["time", "temp_raw", "vref_raw", "temp_c"])
port.write(b"stream on\r\n")
try:
while True:
line = port.readline().decode("utf-8", errors="replace").strip()
fields = line.split(",")
if len(fields) == 4 and fields[0] == "DATA":
writer.writerow([datetime.now().isoformat(timespec="milliseconds"), *fields[1:]])
file.flush() # 每行立即写盘,程序意外退出也不丢数据
except KeyboardInterrupt:
port.write(b"stream off\r\n") utf-8-sig 编码让 Excel 正确识别文件编码。完成后,把 stm32-monitor 中的脚本、pyproject.toml 和 uv.lock 一起提交到 Git;data.csv 这类采集结果按需决定是否提交。
之后可以让 AI 继续扩展上位机,例如图形界面按钮发送 mode auto、period 250 等命令,或同时绘制多条曲线:
在 D:\Projects\STM32_Learn\stm32-monitor 中扩展上位机,不修改单片机工程。
串口参数 9600 8N1,COM 口通过命令行参数传入;数据格式为 DATA,温度原始值,VREFINT 原始值,结温估算值。
增加一个窗口:上方实时绘制结温曲线,下方提供 mode auto、mode manual、mode pause、
period 250、period 500、period 1000 按钮,点击后发送对应命令并以 \r\n 结尾。
依赖用 uv add 添加,说明运行命令,完成后提交 Git。