
本文来源:http://www.lpqz.cn/news/130159
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。
1. 为什么“铁头山羊”的STM32新版教程值得从头跟一遍如果你最近在搜“stm32入门教程”大概率已经刷到过“铁头山羊”这个名字。我最早接触这套教程是在一个学弟的推荐下当时他拿着一块最小系统板跟着视频一步步点灯、串口打印、定时器中断两周时间就把基础外设跑了个遍。后来我自己也把新版教程完整过了一遍发现它和市面上很多“念手册式”的教学完全不是一个路子——它更像一个做过实际项目的工程师坐在你旁边告诉你“这一步为什么要这么干”“哪里容易翻车”“怎么查问题”。STM32入门这件事说难不难说简单也不简单。难的是你面对的是一个拥有几十个外设、上百个寄存器、多种时钟源和复杂中断系统的32位微控制器简单的是只要你把GPIO、时钟、中断、定时器、串口这几块吃透后面学什么外设都是同一套逻辑。铁头山羊新版教程最大的价值就是把这套逻辑用非常接地气的方式讲清楚了而且新版在旧版基础上补了不少实战内容比如STM32Cu
beMX的配合使用、HAL库与标准库的对比、调试技巧和常见故障排查。这篇文章不是教程的简单复述而是我跟着这套教程走完一遍之后结合自己踩过的坑和实际项目经验把STM32入门阶段最核心的知识点、最容易被忽略的细节、以及最值得反复练习的实操环节系统地梳理出来。无论你是完全零基础的小白还是学过51单片机想进阶的爱好者或者是被毕业设计逼着上手的同学都能从下面这些内容里找到可以直接抄作业的步骤和避坑指南。2. 入门前的整体设计与学习路线拆解2.1 为什么STM32入门不能“从寄存器手册第一页开始看”很多人学STM32的第一个误区就是买了一块开发板然后打开参考手册从第一页开始啃。结果看了三天连GPIO都没点亮点。这不是你笨而是方法错了。STM32的参考手册有上千页寄存器描述密密麻麻如果你没有实际的操作场景去对应看再多也记不住。铁头山羊新版教程的思路很聪明先用最直观的方式让你看到结果再回头解释原理。比如点
灯这一课它不会一上来就讲BSRR寄存器的每一位是什么意思而是先让你用CubeMX生成代码烧进去看到LED亮了然后再告诉你“刚才那个HAL_GPIO_WritePin函数背后其实操作了哪个寄存器”。这种“先跑通再深挖”的路径对初学者来说心理负担小很多也更容易建立信心。我自己的经验是STM32入门阶段应该遵循“外设驱动为主、寄存器理解为辅”的原则。你不需要背下来每个寄存器的地址但你需要知道当你调用一个库函数时它大概动了哪些硬件资源。这样出了问题你才有排查的方向而不是对着代码发呆。2.2 新版教程的学习路线图与阶段目标跟着铁头山羊新版走整个入门阶段可以分成四个台阶每个台阶都有明确的目标和验收标准。我把它整理成下面这张表你可以对照自己的进度看看走到哪了。阶段核心内容验收标准建议耗时第一阶段开发环境搭建、GPIO输入输出、按键检测能独立点亮LED、读取按键状态、实现按键控制LED3-5天第二阶段中断
系统、定时器基础、串口通信能用定时器做精准延时、串口收发数据、中断响应按键1-2周第三阶段PWM输出、输入捕获、ADC采样能控制舵机、测量频率、读取电位器电压1-2周第四阶段DMA、I2C/SPI通信、综合小项目能驱动OLED、读写EEPROM、完成一个多外设协同的小项目2-3周这个路线不是死的你可以根据自己的基础调整。比如你之前用过Arduino那第一阶段可能一天就过了如果你连C语言指针都不太熟那在第二阶段学中断回调的时候可能会卡一下需要回头补补C语言基础。2.3 工具选型Keil、CubeMX、VS Code到底怎么配STM32开发环境的搭建是劝退新手的第一个大坑。铁头山羊新版教程里主要用的是Keil MDK但同时也提到了CubeMX和VS Code的配合方案。我三种方式都试过说说我的实际感受。Keil MDK的优势是生态成熟、调试方便、教程资料多缺点是界面老旧、代码补全弱、免费版有3
2KB限制。对于入门来说32KB其实够用点灯、串口、定时器这些例程编译出来通常也就几KB到十几KB。但如果你后面要加FreeRTOS或者文件系统可能就会超。CubeMX是一个图形化配置工具你可以用鼠标点选引脚功能、时钟树、外设参数然后一键生成初始化代码。它的最大价值是帮你避开时钟配置和引脚复用这些容易出错的地方。我建议新手一定要学会用CubeMX哪怕你后面不用HAL库用它来查引脚定义和时钟树也非常方便。VS Code加PlatformIO或者STM32扩展的方案适合有一定基础、追求开发体验的人。代码补全、Git集成、终端操作都很舒服但配置过程对新手不太友好尤其是调试器的配置容易出问题。我的建议是入门阶段先用Keil加CubeMX的组合把主要精力放在理解外设原理上等你有了一定基础再折腾VS Code。注意安装Keil5的时候如果你之前装过Keil C51需要注意安装路径不要冲突。另外STM3
2的芯片包需要单独下载安装新版教程里会告诉你从哪里获取。安装完芯片包后最好用ST-Link Utility或者STM32CubeProgrammer测试一下能否识别到芯片这一步能帮你提前排除很多下载器驱动的问题。3. 核心细节解析与实操要点3.1 GPIO看似最简单实则最容易埋坑的外设GPIO是STM32入门的第一课也是很多人觉得“太简单了没什么好讲”的地方。但我在实际带新人的过程中发现GPIO的坑其实不少。比如推挽输出和开漏输出的区别什么时候该用上拉电阻输入模式下的浮空、上拉、下拉到底怎么选这些问题如果不搞清楚后面驱动一些特殊外设的时候就会莫名其妙失败。铁头山羊新版教程在讲GPIO的时候用了一个很形象的比喻推挽输出就像两个人推拉门一个负责推一个负责拉能主动输出高电平和低电平开漏输出就像只有一个人拉门只能主动拉低高电平需要外部上拉电阻来提供。这个比喻我后来在给学弟讲I2C总线的时候又用了一
次因为I2C的SDA和SCL就是典型的开漏输出加外部上拉。实操层面点灯例程里有一个细节值得注意LED的限流电阻怎么选。假设你用的是红色LED正向压降约1.8V工作电流取5mA到10mASTM32的GPIO输出高电平约3.3V那么限流电阻R (3.3 - 1.8) / 0.01 150欧姆。实际选用220欧姆或330欧姆都可以亮度会稍暗但更安全。如果你直接用0欧姆电阻或者不接电阻短时间可能没事但长期运行LED和GPIO口都有损坏风险。按键检测这块新版教程重点讲了消抖。机械按键在按下和松开的瞬间会产生几十毫秒的抖动如果不处理一次按下可能会被识别成多次。最简单的消抖方法是延时确认检测到按键状态变化后延时20ms再读一次如果状态一致就认为有效。更优雅的方式是用定时器中断定期扫描按键配合状态机实现。我建议新手先用延时消抖把功能跑通等学到定时器的时候再回来优化。3.2 时钟树STM32的“心脏”配
置错了什么都跑不起来时钟树是STM32入门阶段最抽象、也最容易被跳过的一环。很多人用CubeMX生成代码后能跑就以为时钟配置不重要。但如果你哪天发现串口波特率不对、定时器计时不准、ADC采样值跳动十有八九是时钟树没配对。STM32的时钟源主要有四种HSI内部高速时钟通常8MHz或16MHz、HSE外部高速时钟通常接8MHz晶振、LSI内部低速时钟约32kHz、LSE外部低速时钟通常接32.768kHz晶振。系统时钟SYSCLK可以从HSI或HSE经过PLL倍频得到然后分频给AHB、APB1、APB2等总线。铁头山羊新版教程里有一个很实用的建议用CubeMX配置时钟树的时候直接在图形界面上输入你想要的最高频率比如STM32F103C8T6最高72MHzCubeMX会自动帮你算出PLL的倍频和分频系数。但你要知道它为什么这么算否则换个芯片或者换个晶振频率你就懵了。我举个例子说明时钟配置对定时器
的影响。假设你用TIM2做一个1ms的定时中断TIM2挂在APB1总线上。如果APB1的预分频系数为2那么APB1时钟为36MHz但定时器时钟会是APB1的2倍即72MHz这是STM32的一个特殊规则当APB预分频不为1时定时器时钟等于APB时钟的2倍。如果你不知道这个规则按36MHz去算预分频值定时时间就会差一倍。实操心得每次新建工程后先别急着写业务代码用串口打印一下SystemCoreClock的值确认系统时钟和你预期的一致。这个习惯能帮你省下大量排查时间。3.3 中断系统从“轮询思维”到“事件驱动思维”的跨越学完GPIO之后很多人会习惯用轮询的方式写代码在主循环里不断检查按键状态、检查串口有没有收到数据。这种方式在小程序里能用但一旦功能变多主循环就会变得又长又卡响应也不及时。中断就是解决这个问题的核心机制。STM32的中断系统涉及NVIC嵌套向量中断控制器、中断优先级、中断服务函数等
概念。铁头山羊新版教程在讲中断的时候特别强调了优先级分组的概念。STM32的中断优先级分为抢占优先级和响应优先级抢占优先级高的中断可以打断正在执行的低优先级中断响应优先级只在同时发生多个中断时决定谁先执行。新手最容易犯的错误是随便设置优先级导致中断嵌套混乱。我的建议是入门阶段先把所有中断的抢占优先级设成一样的响应优先级根据需要排个序。等你对中断机制理解更深了再考虑用抢占优先级做嵌套。串口接收中断是一个很好的练习场景。你可以配置串口在接收到一个字节时触发中断在中断服务函数里把数据存到缓冲区主循环再慢慢处理。这样即使主循环在忙其他事情也不会丢数据。新版教程里还提到了空闲中断加DMA的进阶用法那个适合在需要接收不定长数据的时候用入门阶段可以先了解思路。3.4 定时器STM32最强大的外设之一值得多花时间定时器是STM32里功能最丰富的外设没有之一。基本定时、PWM输出、输入捕获、编码器接口、触发
ADC、DMA请求这些功能都离不开定时器。铁头山羊新版教程把定时器拆成了好几节课从最简单的定时中断讲到PWM和输入捕获节奏安排得比较合理。定时器的核心概念是预分频器PSC和自动重装载寄存器ARR。定时时间 (PSC 1) × (ARR 1) / 定时器时钟频率。假设定时器时钟72MHz你想要1ms中断一次可以设PSC71ARR999这样(711)×(9991)/72000000 0.001秒 1ms。PWM输出是定时器最常用的功能之一。控制舵机需要50Hz的PWM也就是周期20ms。假设定时器时钟72MHzPSC设为71则计数频率为1MHzARR设为19999周期就是20ms。然后通过修改CCR寄存器的值来调整占空比CCR从500到2500对应舵机0度到180度。这个计算过程我在第一次做舵机控制的时候算了半天后来发现只要记住公式换任何频率都是套进去算。输入捕获可以用来测量外部信号
的频率和脉宽。新版教程里讲了测频法和测周法两种思路。测频法是在固定时间内数脉冲个数适合高频信号测周法是在一个信号周期内数定时器计数个数适合低频信号。实际项目中我通常用输入捕获的PWMI模式同时测量频率和占空比用来解码红外遥控信号或者读取霍尔传感器的转速。4. 实操过程与核心环节实现4.1 从零搭建一个STM32工程标准库与HAL库的选择铁头山羊新版教程在工程搭建这块给了两种方案标准库和HAL库。标准库是ST早期推出的直接操作寄存器代码效率高资料多但ST已经不再维护了。HAL库是现在ST主推的配合CubeMX使用非常方便跨芯片移植性好但代码体积大执行效率略低。我的建议是入门阶段用HAL库加CubeMX快速把外设跑通建立信心。等你对STM32的运作机制有了整体认识再回头看看标准库的代码理解寄存器层面的操作。如果你是为了做毕业设计或者找工作的项目HAL库足够应付大多数场景企业里用HAL库的也不少
。下面是一个用CubeMX生成HAL库工程的基本流程。首先在CubeMX里选择你的芯片型号比如STM32F103C8T6。然后配置时钟源在RCC里把HSE设为Crystal/Ceramic Resonator。接着配置时钟树在Clock Configuration标签页里把HCLK拉到72MHz。再配置GPIO比如把PC13设为GPIO_Output用于板载LED。最后在Project Manager里设置工程名称、路径、工具链为MDK-ARM点击Generate Code。生成的代码里main函数中会自动调用SystemClock_Config和MX_GPIO_Init。你只需要在while(1)循环里加上HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13)和HAL_Delay(500)编译下载就能看到LED闪烁。这个流程看起来简单但每一步都有细节。比如时钟树配置
不对HAL_Delay的延时就不准GPIO模式选错LED可能不亮或者亮度异常。4.2 串口通信实战从printf重定向到自定义协议串口是STM32调试和通信最常用的接口。铁头山羊新版教程里花了不少篇幅讲串口从最基础的发送一个字节到printf重定向再到接收中断和空闲中断。我重点说说printf重定向和自定义协议这两个实用环节。printf重定向的原理是重写C标准库的fputc函数让printf输出的字符通过串口发送出去。在Keil MDK里你需要勾选Use MicroLIB然后添加下面这段代码#include stdio.h int fputc(int ch, FILE *f) { HAL_UART_Transmit(huart1, (uint8_t *)ch, 1, 0xFFFF); return ch; }这样你就可以在代码里直接用printf(System Clock: %d\r\n
, SystemCoreClock)来打印调试信息了。注意串口助手的波特率要和代码里配置的一致通常用115200。自定义协议是实际项目中常用的做法。比如你可以定义一帧数据帧头0xAA 0x55然后是命令字、数据长度、数据内容、校验和。接收端用状态机解析收到完整帧后根据命令字执行对应操作。新版教程里有一个简单的例子用串口发送指令控制LED的开关。这个例子虽然简单但把串口收发、数据解析、命令执行的流程都串起来了非常适合作为第一个综合练习。4.3 定时器PWM输出控制舵机和呼吸灯PWM输出的实操我建议从呼吸灯开始因为LED的亮度变化肉眼可见调试起来很直观。配置TIM3的通道1为PWM输出模式PSC设为71ARR设为999这样PWM频率为72MHz/(72×1000)1kHz。然后在主循环里逐渐增加CCR值再逐渐减小就能看到呼吸灯效果。舵机控制是PWM的经典应用。舵机需要50Hz的PWM信号高电平

本文来源:http://www.lpqz.cn/news/130159
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。
1. Why "Iron-Headed Goat"'s new STM32 tutorial is worth following from start to finish. If you've recently been searching for "STM32 beginner tutorials," chances are you've already come across the name "Iron-Headed Goat." I first encountered this tutorial series on the recommendation of a junior schoolmate, who, holding a minimal system board, followed the videos step by step—blinking an LED, printing over the serial port, timer interrupts—and within two weeks had run through all the basic peripherals. Later, I went through the new version of the tutorial myself from beginning to end and found that it takes a completely different approach from the many "manual-reciting" style lessons on the market—it's more like an engineer who has actually worked on real projects sitting beside you, telling you "why we do this step this way," "where things are likely to go wrong," and "how to troubleshoot." Getting started with STM32 is neither hard nor easy. The hard part is that you're facing a 32-bit microcontroller with dozens of peripherals, hundreds of registers, multiple clock sources, and a complex interrupt system. The easy part is that once you've truly mastered GPIO, clocks, interrupts, timers, and the serial port, every other peripheral you learn later follows the same logic. The greatest value of Iron-Headed Goat's new tutorial is that it explains this logic in a very down-to-earth way, and the new version adds quite a bit of hands-on content on top of the old one, such as STM32Cu
beMX in combination with it, a comparison of the HAL library versus the Standard Peripheral Library, debugging techniques, and common fault troubleshooting. This article is not a simple retelling of the tutorial; rather, after completing the tutorial once myself, I combined the pitfalls I've stumbled into and my real-world project experience to systematically organize the core knowledge points of the STM32 beginner stage, the details most easily overlooked, and the hands-on exercises most worth practicing repeatedly. Whether you're a complete beginner with zero background, an enthusiast who has learned the 8051 and wants to advance, or a student forced to get started by a graduation project, you'll find steps you can directly copy and pitfall-avoidance guides in the content below. 2. Overall design and learning roadmap before getting started. 2.1 Why you can't "start from page one of the register manual" when learning STM32. The first misconception many people have when learning STM32 is buying a development board, opening the reference manual, and starting to chew through it from page one. The result is that after three days you still can't even blink an LED. This isn't because you're stupid—it's the wrong method. The STM32 reference manual has over a thousand pages of densely packed register descriptions; if you have no practical operating scenario to map them to, you won't remember them no matter how much you read. Iron-Headed Goat's new tutorial uses a smart approach: first let you see the result in the most intuitive way, then come back and explain the principles. For example, in the LED-blinking lesson,
it won't start off by explaining what each bit of the BSRR register means. Instead, it first has you use CubeMX to generate code, flash it in, and see the LED light up, and only then tells you "which register that HAL_GPIO_WritePin function you just used actually operated under the hood." This "get it running first, then dig deeper" path greatly reduces the mental burden on beginners and makes it easier to build confidence. My own experience is that the STM32 beginner stage should follow the principle of "peripheral driving as the main focus, register understanding as the supplement." You don't need to memorize the address of every register, but you do need to know roughly which hardware resources a library function touches when you call it. That way, when something goes wrong, you have a direction for troubleshooting instead of just staring blankly at the code. 2.2 The new tutorial's learning roadmap and stage goals. Following Iron-Headed Goat's new version, the entire beginner stage can be divided into four steps, each with clear goals and acceptance criteria. I've organized them into the table below so you can compare your own progress and see where you are. Stage | Core content | Acceptance criteria | Suggested time. Stage 1: Development environment setup, GPIO input/output, button detection — able to independently light an LED, read button states, implement button-controlled LED — 3–5 days. Stage 2: Interrupt
system, timer fundamentals, serial communication — able to use a timer for precise delays, send and receive serial data, respond to buttons via interrupts — 1–2 weeks. Stage 3: PWM output, input capture, ADC sampling — able to control a servo, measure frequency, read a potentiometer voltage — 1–2 weeks. Stage 4: DMA, I2C/SPI communication, and an integrated small project — able to drive an OLED, read/write EEPROM, and complete a small project with multiple peripherals working together — 2–3 weeks. This roadmap isn't set in stone; you can adjust it based on your own background. For example, if you've used Arduino before, you might get through Stage 1 in a day; if you're not even very familiar with C pointers, you might get stuck when learning interrupt callbacks in Stage 2 and need to go back and shore up your C basics. 2.3 Tool selection: how exactly to set up Keil, CubeMX, and VS Code. Setting up the STM32 development environment is the first big pitfall that discourages beginners. Iron-Headed Goat's new tutorial mainly uses Keil MDK, but it also mentions ways to combine CubeMX and VS Code. I've tried all three approaches, so let me share my actual impressions. The advantages of Keil MDK are a mature ecosystem, convenient debugging, and abundant tutorial materials; its drawbacks are an outdated interface, weak code completion, and a 3
2KB limit in the free version. For beginners, 32KB is actually enough—routines like LED blinking, serial, and timers typically compile to just a few KB to a dozen or so KB. But if you later add FreeRTOS or a filesystem, you might exceed it. CubeMX is a graphical configuration tool that lets you use the mouse to select pin functions, the clock tree, and peripheral parameters, then generate initialization code with one click. Its greatest value is helping you avoid error-prone areas like clock configuration and pin multiplexing. I recommend that beginners definitely learn to use CubeMX—even if you don't use the HAL library later, it's very convenient for looking up pin definitions and the clock tree. The VS Code plus PlatformIO or STM32 extension approach suits people who have some foundation and care about the development experience. Code completion, Git integration, and terminal operations are all very comfortable, but the configuration process isn't very beginner-friendly, especially debugger setup, which is prone to problems. My advice is to use the Keil plus CubeMX combination in the beginner stage and focus your main energy on understanding peripheral principles; once you have a certain foundation, then wrestle with VS Code. Note that when installing Keil 5, if you've previously installed Keil C51, be careful that the installation paths don't conflict. Also, the STM3
2 chip pack needs to be downloaded and installed separately; the new tutorial will tell you where to get it. After installing the chip pack, it's best to use ST-Link Utility or STM32CubeProgrammer to test whether the chip can be detected—this step can help you rule out many debugger/driver problems in advance. 3. Analysis of core details and hands-on key points. 3.1 GPIO: the peripheral that seems simplest but is actually the most pitfall-ridden. GPIO is the first lesson in STM32 beginners, and also a place many people feel is "too simple to talk about." But in the process of actually mentoring newcomers, I've found there are quite a few GPIO pitfalls. For example, the difference between push-pull output and open-drain output, when to use a pull-up resistor, and how to choose among floating, pull-up, and pull-down input modes—if you don't get these straight, you'll inexplicably fail when later driving certain special peripherals. When explaining GPIO, Iron-Headed Goat's new tutorial uses a very vivid analogy: push-pull output is like two people pushing and pulling a door, one responsible for pushing and one for pulling, able to actively output both high and low levels; open-drain output is like only one person pulling the door, able to actively pull the level low only, with the high level needing an external pull-up resistor to provide it. I later used this analogy again when explaining the I2C bus to a junior schoolmate,
because I2C's SDA and SCL are classic examples of open-drain output plus external pull-up. On the practical side, there's one detail in the LED-blinking example worth noting: how to choose the LED's current-limiting resistor. Suppose you're using a red LED with a forward voltage drop of about 1.8V and an operating current of 5mA to 10mA, and the STM32 GPIO outputs a high level of about 3.3V; then the current-limiting resistor R = (3.3 - 1.8) / 0.01 = 150 ohms. In practice, 220 ohms or 330 ohms both work; the brightness will be slightly dimmer but safer. If you use a 0-ohm resistor or no resistor at all, it might be fine in the short term, but over long-term operation both the LED and the GPIO pin are at risk of damage. For button detection, the new tutorial focuses on debouncing. A mechanical button produces tens of milliseconds of bounce at the instant of press and release; if not handled, a single press may be recognized as multiple presses. The simplest debouncing method is delay confirmation: after detecting a change in button state, wait 20ms and read again; if the state is consistent, consider it valid. A more elegant approach is to periodically scan the button with a timer interrupt, combined with a state machine. I recommend beginners first use delay debouncing to get the function working, then come back to optimize it when you learn about timers. 3.2 The clock tree: the "heart" of the STM32—if configured incorrectly, nothing will work. Config
uring it incorrectly means nothing runs. The clock tree is the most abstract part of the STM32 beginner stage, and also the most easily skipped. Many people generate code with CubeMX, see that it runs, and assume clock configuration doesn't matter. But if one day you find the serial baud rate is wrong, timer timing is inaccurate, or ADC sample values are jumping around, nine times out of ten the clock tree is misconfigured. STM32 has four main clock sources: HSI (internal high-speed clock, usually 8MHz or 16MHz), HSE (external high-speed clock, usually connected to an 8MHz crystal), LSI (internal low-speed clock, about 32kHz), and LSE (external low-speed clock, usually connected to a 32.768kHz crystal). The system clock SYSCLK can be obtained from HSI or HSE via PLL frequency multiplication, then divided down to buses such as AHB, APB1, and APB2. Iron-Headed Goat's new tutorial has a very practical tip: when configuring the clock tree in CubeMX, just type the maximum frequency you want into the graphical interface—for example, 72MHz max for the STM32F103C8T6—and CubeMX will automatically calculate the PLL multiplication and division factors for you. But you need to know why it calculates them that way, otherwise switching to a different chip or a different crystal frequency will leave you at a loss. Let me give an example to illustrate the effect of clock configuration on the timer
interrupts. Suppose you use TIM2 to create a 1ms periodic interrupt, with TIM2 hanging off the APB1 bus. If the APB1 prescaler is 2, then the APB1 clock is 36MHz, but the timer clock will be twice APB1, i.e., 72MHz—this is a special STM32 rule: when the APB prescaler is not 1, the timer clock equals twice the APB clock. If you don't know this rule and calculate the prescaler value based on 36MHz, your timing interval will be off by a factor of two. Practical tip: after creating each new project, don't rush to write application code; first use the serial port to print the value of SystemCoreClock and confirm that the system clock matches your expectation. This habit can save you a lot of troubleshooting time. 3.3 The interrupt system: the leap from "polling thinking" to "event-driven thinking." After learning GPIO, many people fall into the habit of writing code using polling, constantly checking button states and whether the serial port has received data inside the main loop. This works in small programs, but as features multiply, the main loop becomes long and sluggish, and the response isn't timely. Interrupts are the core mechanism for solving this problem. STM32's interrupt system involves concepts such as the NVIC (Nested Vectored Interrupt Controller), interrupt priority, and interrupt service routines,
etc. When explaining interrupts, Iron-Headed Goat's new tutorial places special emphasis on the concept of priority grouping. STM32 interrupt priorities are divided into preemption priority and response (sub) priority: an interrupt with a higher preemption priority can interrupt a lower-priority interrupt that is currently executing, while response priority only determines which one executes first when multiple interrupts occur simultaneously. The most common mistake beginners make is setting priorities arbitrarily, leading to chaotic interrupt nesting. My advice is to first set the preemption priority of all interrupts to the same level in the beginner stage and order the response priorities as needed. Once you have a deeper understanding of the interrupt mechanism, consider using preemption priority for nesting. The serial receive interrupt is a great practice scenario. You can configure the serial port to trigger an interrupt when a byte is received, store the data into a buffer inside the interrupt service routine, and let the main loop process it at its leisure. That way, even if the main loop is busy with other things, no data is lost. The new tutorial also mentions the advanced technique of idle interrupt plus DMA, which is suitable for receiving variable-length data; in the beginner stage you can just understand the concept first. 3.4 Timers: one of the most powerful STM32 peripherals, worth spending more time on. The timer is the most feature-rich peripheral in the STM32, bar none. Basic timing, PWM output, input capture, encoder interface, trigger
ing ADC and DMA requests—all of these functions rely on timers. Iron-Headed Goat's new tutorial splits timers into several lessons, going from the simplest timer interrupt to PWM and input capture, with a reasonably well-paced arrangement. The core concepts of a timer are the prescaler PSC and the auto-reload register ARR. Timer period = (PSC + 1) × (ARR + 1) / timer clock frequency. Suppose the timer clock is 72MHz and you want an interrupt every 1ms; you can set PSC = 71 and ARR = 999, giving (71+1)×(999+1)/72,000,000 = 0.001 s = 1ms. PWM output is one of the most commonly used timer functions. Controlling a servo requires 50Hz PWM, i.e., a period of 20ms. Suppose the timer clock is 72MHz and PSC is set to 71, then the counting frequency is 1MHz; set ARR to 19999 and the period is 20ms. Then adjust the duty cycle by changing the CCR register value—CCR from 500 to 2500 corresponds to the servo's 0 to 180 degrees. When I first did servo control, I spent ages on this calculation, only to realize later that as long as you memorize the formula, you just plug in the numbers for any frequency. Input capture can be used to measure external signals'
frequency and pulse width. The new tutorial explains two approaches: the frequency-counting method and the period-measuring method. The frequency-counting method counts the number of pulses within a fixed time and suits high-frequency signals; the period-measuring method counts the number of timer ticks within one signal period and suits low-frequency signals. In real projects I usually use the PWM input (PWMI) mode of input capture to measure frequency and duty cycle simultaneously, for decoding infrared remote-control signals or reading the rotation speed of a Hall sensor. 4. The hands-on process and implementation of core steps. 4.1 Building an STM32 project from scratch: choosing the Standard Library vs. the HAL Library. Iron-Headed Goat's new tutorial offers two options for project setup: the Standard Peripheral Library and the HAL Library. The Standard Library was released early on by ST; it operates registers directly, offers high code efficiency and abundant materials, but ST no longer maintains it. The HAL Library is what ST currently promotes; it works very conveniently with CubeMX, has good cross-chip portability, but has a larger code footprint and slightly lower execution efficiency. My advice is to use the HAL Library plus CubeMX in the beginner stage to quickly get peripherals running and build confidence. Once you have an overall understanding of how the STM32 works, go back and look at the Standard Library code to understand register-level operations. If you're doing a graduation project or a project for job hunting, the HAL Library is more than enough for most scenarios, and plenty of companies use it too.
. Below is the basic flow for generating a HAL Library project with CubeMX. First, select your chip model in CubeMX, e.g., STM32F103C8T6. Then configure the clock source—in RCC, set HSE to Crystal/Ceramic Resonator. Next configure the clock tree—in the Clock Configuration tab, pull HCLK up to 72MHz. Then configure GPIO—for example, set PC13 to GPIO_Output for the onboard LED. Finally, in the Project Manager set the project name, path, and toolchain to MDK-ARM, and click Generate Code. In the generated code, the main function will automatically call SystemClock_Config and MX_GPIO_Init. You just need to add HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13) and HAL_Delay(500) inside the while(1) loop, compile, and flash, and you'll see the LED blinking. This flow looks simple, but every step has its details. For example, if the clock tree configuration
is wrong, the HAL_Delay timing will be inaccurate; if the GPIO mode is chosen incorrectly, the LED may not light up or may have abnormal brightness. 4.2 Serial communication in practice: from printf redirection to custom protocols. The serial port is the most commonly used interface for STM32 debugging and communication. Iron-Headed Goat's new tutorial devotes quite a bit of space to the serial port, from the most basic task of sending a single byte to printf redirection, and then to receive interrupts and idle interrupts. I'll focus on the two practical parts: printf redirection and custom protocols. The principle of printf redirection is to override the C standard library's fputc function so that characters output by printf are sent out through the serial port. In Keil MDK, you need to check "Use MicroLIB" and then add the following code: #include stdio.h int fputc(int ch, FILE *f) { HAL_UART_Transmit(huart1, (uint8_t *)ch, 1, 0xFFFF); return ch; } Then you can directly use printf(System Clock: %d\r\n
, SystemCoreClock) to print debugging information. Note that the serial monitor's baud rate must match the one configured in the code—usually 115200. Custom protocols are a common practice in real projects. For example, you can define a data frame with a header of 0xAA 0x55, followed by a command byte, data length, data content, and checksum. The receiver uses a state machine to parse it, and once a complete frame is received, executes the corresponding operation based on the command byte. The new tutorial has a simple example that uses a serial command to control an LED's on/off state. Although simple, this example ties together the whole flow of serial transmit/receive, data parsing, and command execution, making it an ideal first comprehensive exercise. 4.3 Timer PWM output: controlling a servo and a breathing light. For hands-on PWM output, I recommend starting with the breathing light, because the LED's brightness change is visible to the naked eye and very intuitive to debug. Configure TIM3 channel 1 as PWM output mode, set PSC to 71 and ARR to 999, giving a PWM frequency of 72MHz/(72×1000) = 1kHz. Then in the main loop gradually increase and then decrease the CCR value to see the breathing-light effect. Servo control is a classic application of PWM. A servo needs a 50Hz PWM signal, with a high level