STM32串口清空缓存区库函数代码
时间: 2023-11-15 22:06:03 浏览: 306
以下是一个简单的示例代码,它可以清空串口缓冲区:
```c
#include "stm32f10x.h"
#include "stdio.h"
void USART_ClearBuffer(USART_TypeDef* USARTx)
{
volatile uint32_t temp;
while (USART_GetFlagStatus(USARTx, USART_FLAG_RXNE) == SET)
{
temp = USART_ReceiveData(USARTx);
}
}
int main(void)
{
// 初始化串口
USART_InitTypeDef USART_InitStruct;
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART1, &USART_InitStruct);
USART_Cmd(USART1, ENABLE);
// 清空缓冲区
USART_ClearBuffer(USART1);
while (1)
{
// 读取串口数据
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != SET);
uint16_t ch = USART_ReceiveData(USART1);
// 在这里处理串口数据
...
}
}
```
该函数使用了一个 while 循环来读取缓冲区中的所有数据,直到缓冲区为空。在主程序中,我们可以在需要清空缓冲区时调用该函数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)