基于消息事件实现结合状态机实现事件触发通用单片机逻裸机框架处理
1. 框架结构
-
ISR:生成消息(事件)并提交到消息缓冲区。
-
消息缓冲区:存储待处理的消息。
-
主状态机:从消息缓冲区中取出消息并处理,驱动状态迁移。
2. 代码实现
(1) 消息定义
#include "stm32f10x.h"
#include <stdbool.h>// 消息类型定义
typedef enum {
MSG_NONE,
MSG_BUTTON_PRESS,
MSG_TIMER_TIMEOUT,
MSG_UART_RX
} MessageType;// 消息结构体
typedef struct {
MessageType type; // 消息类型
uint8_t data; // 消息数据
} Message;
(2) 消息缓冲区
#define MSG_QUEUE_SIZE 32
static Message msgQueue[MSG_QUEUE_SIZE]; // 消息队列
static uint8_t msgQueueHead = 0; // 队列头
static uint8_t msgQueueTail = 0; // 队列尾