STM32 模块化开发指南 · 第 5 篇 STM32 项目中断处理机制最佳实践:ISR、回调与事件通知

本文是《STM32 模块化开发实战指南》第 5 篇,聚焦于 STM32 裸机开发中最核心也最容易被忽视的部分——中断服务机制。我们将介绍如何正确、高效地设计中断处理函数(ISR),实现数据与事件从中断上下文传递到主逻辑的通道,并构建一个清晰、可维护、非阻塞的事件通知机制。


一、为什么裸机项目中的 ISR 会失控?

常见“错误用法”:

  • 在 ISR 中执行复杂操作(如 printf()、长循环、malloc 等)

  • 在 ISR 中调用多层函数导致栈溢出

  • 在 ISR 中修改共享变量却没有保护

  • ISR 中与主循环耦合严重,增加调试难度

中断本质上是“异步打断主流程”的机制,它应当只承担“快速收集数据、标记状态、通知主循环”的职责。


二、设计目标:让 ISR 只做最少事

中断服务函数设计三原则:

  • :执行时间必须极短,最多几微秒

  • :尽量不调用其他函数,或仅调用专用轻量函数

  • 可控:不要直接控制主流程,通过队列/标志间接通知


三、推荐结构:ISR → 缓冲区/事件队列 → 主循环处理

+-----------+        +---------------+        +-------------------+
|   中断函数   |  -->   |   缓冲区/队列    |  -->   | 主循环消费(FSM、协议) |
+-----------+        +---------------+        +-------------------+

常见中断数据通道:

  • 串口接收 → 环形缓冲区(RingBuffer)

  • 外部中断 → 事件队列通知系统状态

  • 定时器中断 → 设置标志位、计数器递增


四、实际例子 1:串口接收 ISR

// uart.c
#include "ring_buffer.
翻译一下function format = stlGetFormat(fileName) %STLGETFORMAT identifies the format of the STL file and returns 'binary' or %'ascii' fid = fopen(fileName); % Check the file size first, since binary files MUST have a size of 84+(50*n) fseek(fid,0,1); % Go to the end of the file fidSIZE = ftell(fid); % Check the size of the file if rem(fidSIZE-84,50) > 0 format = 'ascii'; else % Files with a size of 84+(50*n), might be either ascii or binary... % Read first 80 characters of the file. % For an ASCII file, the data should begin immediately (give or take a few % blank lines or spaces) and the first word must be 'solid'. % For a binary file, the first 80 characters contains the header. % It is bad practice to begin the header of a binary file with the word % 'solid', so it can be used to identify whether the file is ASCII or % binary. fseek(fid,0,-1); % go to the beginning of the file header = strtrim(char(fread(fid,80,'uchar')')); % trim leading and trailing spaces isSolid = strcmp(header(1:min(5,length(header))),'solid'); % take first 5 char fseek(fid,-80,1); % go to the end of the file minus 80 characters tail = char(fread(fid,80,'uchar')'); isEndSolid = findstr(tail,'endsolid'); % Double check by reading the last 80 characters of the file. % For an ASCII file, the data should end (give or take a few % blank lines or spaces) with 'endsolid <object_name>'. % If the last 80 characters contains the word 'endsolid' then this % confirms that the file is indeed ASCII. if isSolid & isEndSolid format = 'ascii'; else format = 'binary'; end end fclose(fid);
最新发布
05-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

damo王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值