本文从论坛评论里看到,亲测有效,非常感谢楼主,记录在此,仅供学习,帮助更多遇到此问题的朋友。若有侵权,请及时联系,谢谢。
1、初始化千万不要初始化就打开IDLE中断
2、在串口接收中断中打开IDLE中断
3、正确清楚IDLE中断。
void USART1_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStruct;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); //使能GPIOA的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);//使能USART的时钟
/* USART1的端口配置 */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);//配置PA9成第二功能引脚 TX
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);//配置PA10成第二功能引脚 RX
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* USART1的基本配置 */
USART_InitStructure.USART_BaudRate = 115200; //波特率
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* USART1的NVIC中断配置 */
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPriority = 0x02;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
USART_Init(USART, &USART_InitStructure);
USART_ITConfig(USART, USART_IT_RXNE, ENABLE); //使能接收中断
// USART_ITConfig(USART,USART_IT_IDLE,ENABLE); //初始化的时候千万不要打开IDLE中断
USART_Cmd(USART, ENABLE); //使能USART1
}
void USART1_IRQHandler(void)
{
uint8_t Res;
if(USART_GetITStatus(USART, USART_IT_RXNE) != RESET) { //接收中断
if(!(USART->CR1 & USART_CR1_IDLEIE)) {
USART_ITConfig(USART,USART_IT_IDLE,ENABLE);//当没有开启IDLE中断的时候再开,不然上电会进去一次
USART_ClearFlag(USART, USART_FLAG_IDLE);
}
Res = USART_ReceiveData(USART); //读取接收到的数据
}
if(USART_GetFlagStatus(USART,USART_FLAG_IDLE) == SET) //空闲中断
{
USART_ClearFlag(USART, USART_FLAG_IDLE);
USART->RDR;
USART_ITConfig(USART,USART_IT_IDLE,DISABLE);//不用的时候关闭串口空闲中断,防止意外进入
}
}