<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>数据包 on 吾思 梦阁</title><link>https://wstek.win/tags/%E6%95%B0%E6%8D%AE%E5%8C%85/</link><description>Recent content from 吾思 梦阁</description><generator>Hugo</generator><language>zh-cn</language><managingEditor>wusitech@qq.com (WuSi09)</managingEditor><webMaster>wusitech@qq.com (WuSi09)</webMaster><copyright>本博客所有文章除特别声明外，均采用 BY-NC-SA 许可协议。转载请注明出处！</copyright><lastBuildDate>Fri, 06 Nov 2026 23:59:00 +0800</lastBuildDate><atom:link href="https://wstek.win/tags/%E6%95%B0%E6%8D%AE%E5%8C%85/index.xml" rel="self" type="application/rss+xml"/><item><title>STM32 串口数据包：HEX/文本协议、状态机、校验与串口下载</title><link>https://wstek.win/posts/stm32-usart-packet/</link><pubDate>Mon, 02 Nov 2026 19:30:00 +0800</pubDate><author>wusitech@qq.com (WuSi09)</author><guid>https://wstek.win/posts/stm32-usart-packet/</guid><description>
<![CDATA[<h1>STM32 串口数据包：HEX/文本协议、状态机、校验与串口下载</h1><p>作者：WuSi09（wusitech@qq.com）</p>
        
          <p>总结自：<a href="https://www.bilibili.com/video/BV1th411z7sn">STM32入门教程-2023版</a> 第 9 章后半（9-4、9-5、9-6）。</p>
<p>代码基于 <strong>STM32F103C8T6 + STM32F10x 标准外设库 3.5.0</strong>（API 已按 STM32F10x StdPeriph 3.5 头文件核对；Delay/OLED/Key 为课程配套驱动），不包含新建工程和接线步骤。</p>
<table>
	<thead>
			<tr>
					<th>视频</th>
					<th>视频里讲了什么</th>
					<th>本文对应</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>9-4</td>
					<td>数据包格式（固定/变长 HEX、文本）、状态机接收、校验</td>
					<td>0x00 ~ 0x30</td>
			</tr>
			<tr>
					<td>9-5</td>
					<td>串口收发 HEX 数据包、串口收发文本数据包（代码）</td>
					<td>0x40、0x60</td>
			</tr>
			<tr>
					<td>9-6</td>
					<td>FlyMcu 串口下载、STLINK Utility、选项字节</td>
					<td>0x50</td>
			</tr>
	</tbody>
</table>
<p>视频之外还补了：CRC16 校验、变长包转义、应答/重传、环形缓冲 + 状态机结合、ISP 协议细节、读保护与量产注意事项、12 条故障排查。</p>
<h2 id="0x00-为什么裸字节不够">
<a class="header-anchor" href="#0x00-%e4%b8%ba%e4%bb%80%e4%b9%88%e8%a3%b8%e5%ad%97%e8%8a%82%e4%b8%8d%e5%a4%9f"></a>
0x00 为什么裸字节不够
</h2><p>串口一次只给你一个字节。如果上位机连续发：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">01 02 03 04 05 06
</span></span></code></pre></div><p>从机怎么知道这是“两个 3 字节命令”还是“一个 6 字节命令”？如果中间丢了一个字节，又怎么发现？</p>
<p>实际通信里必须把字节组织成<strong>数据包（帧）</strong>：</p>
<ul>
<li><strong>边界</strong>：包头/包尾/长度，让接收方知道从哪开始、到哪结束；</li>
<li><strong>长度</strong>：数据有多长；</li>
<li><strong>校验</strong>：数据有没有错；</li>
<li><strong>超时</strong>：一帧没收完怎么办。</li>
</ul>
<p>串口是字节流，没有“消息边界”。不设计协议，就只能靠“刚好一次中断收一包”的运气——而中断可能一次收半个包，也可能一次收两个包。</p>
<h2 id="0x10-数据包设计">
<a class="header-anchor" href="#0x10-%e6%95%b0%e6%8d%ae%e5%8c%85%e8%ae%be%e8%ae%a1"></a>
0x10 数据包设计
</h2><h3 id="0x11-固定长度-hex-包">
<a class="header-anchor" href="#0x11-%e5%9b%ba%e5%ae%9a%e9%95%bf%e5%ba%a6-hex-%e5%8c%85"></a>
0x11 固定长度 HEX 包
</h3><p>课程里最常用的格式：</p>
        
        <hr><p>本文2026-11-02首发于<a href='https://wstek.win/'>吾思 梦阁</a>，最后修改于2026-11-06</p>]]></description><category>STM32</category></item></channel></rss>