写基于STM32的串口中断进行接收数据并保存到缓存区的可移植性强的代码
时间: 2023-05-26 17:06:14 浏览: 77
#include "stm32f4xx.h"
#define BUFFER_SIZE 50 // 缓存区大小
volatile uint8_t buffer[BUFFER_SIZE]; // 缓存区
volatile uint8_t buffer_index = 0; // 缓存区索引
void USART2_IRQHandler(void)
{
// 检查是否接收中断
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
// 保存接收到的数据
buffer[buffer_index++] = USART_ReceiveData(USART2);
// 如果缓存区满了,重置缓存区索引
if (buffer_index == BUFFER_SIZE)
{
buffer_index = 0;
}
}
}
int main(void)
{
// 初始化 USART2
USART_InitTypeDef USART_InitStruct;
USART_InitStruct.USART_BaudRate = 115200;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx;
USART_Init(USART2, &USART_InitStruct);
// 使能 USART2 的接收中断
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
// 使能 USART2
USART_Cmd(USART2, ENABLE);
// 循环
while (1)
{
// 处理接收到的数据
for (int i = 0; i < BUFFER_SIZE; i++)
{
// 假设处理数据的函数为 processData
processData(buffer[i]);
}
// 清空缓存区
memset(buffer, 0, BUFFER_SIZE);
}
}
阅读全文
相关推荐

















