stm32f407串口中断接收
时间: 2024-12-29 21:22:46 浏览: 12
### STM32F407 UART 中断接收实现
对于STM32F407单片机而言,利用中断方式来处理UART数据接收是一种常见且高效的方法。通过配置NVIC (Nested Vectored Interrupt Controller),可以确保当有新字符到达时触发相应的中断服务程序(ISR)[^1]。
下面是一个简单的例子展示如何设置并启用UART接收中断:
#### 配置USART初始化结构体
```c
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX; // Enable both transmit and receive modes.
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK){
Error_Handler();
}
}
```
#### 启用全局中断以及特定外设的中断线
为了使能UART接收完成中断,在`MX_NVIC_Config()`函数里添加如下代码片段:
```c
void MX_NVIC_Config(void)
{
/* Configure one bit for preemption priority */
NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
/* Enable the USART1 global interrupt */
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* Set the USART1 IRQ channel priority level to medium-low */
HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);
}
```
#### 编写ISR处理接收到的数据
定义一个用于存储接收到字节缓冲区,并编写对应的中断服务子程序来填充此缓冲区:
```c
uint8_t rxBuffer[RECEIVE_BUFFER_SIZE];
volatile uint16_t rxIndex = 0;
void USART1_IRQHandler(void)
{
/* Check whether the received data register not empty flag is set */
if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_RXNE)){
/* Read a single byte from the hardware buffer into our software buffer */
rxBuffer[rxIndex++] = (uint8_t)(huart1.Instance->DR & (uint8_t)0xFF);
/* If we've filled up the entire buffer then reset index back to start */
if(rxIndex >= RECEIVE_BUFFER_SIZE){
rxIndex = 0;
}
__HAL_UART_CLEAR_IT(&huart1,UART_CLEAR_IDLEF); // Clear IDLE Flag
/* Optionally call another function here that processes incoming bytes */
}else {
/* Handle other possible interrupts like overrun error etc.*/
}
}
```
上述代码展示了基本框架下的UART接收中断机制。值得注意的是,实际应用中可能还需要考虑更多细节问题,比如错误检测与恢复、多字节消息解析等逻辑。
阅读全文