CH32V103c8t6 在寻找解决接收完数据后,怎么即时判断数据已经完成了接收。发现串口有一个IDLE空闲中断。如下图描述:
意思是在串口接收完一帧数据 会产生一个中断,此时程序可判断为数据已接收完毕。
测试例程如下:
一、串口初始化:
void User_USART_Init(uint32_t baudrate) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); /* USART2 TX-->A.2 RX-->A.3 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = baudrate; 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_Tx | USART_Mode_Rx; USART_Init(USART2, &USART_InitStructure); /*打开串口中断*/ USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); /*打开IDLE数据检测中断*/ USART_ITConfig(USART2, USART_IT_IDLE, ENABLE); NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); USART_Cmd(USART2, ENABLE); USART_SetAddress(USART2, 0x1); }
二、串口中断程序
/*idle 数据检测中断测试*/ void USART2_IRQHandler(void) { uint16_t Clear = Clear; /*如果接收到一个字节*/ if(USART_GetITStatus(USART2,USART_IT_RXNE)!= RESET) { USART_RX_BUF[RxCounter++]= USART_ReceiveData(USART2); } /*如果接收到一帧数据*/ else if(USART_GetITStatus(USART2, USART_IT_IDLE)!= RESET) { Clear = USART2->STATR; Clear = USART2->DATAR; strcpy(UsartData,USART_RX_BUF); /*清空串口接收数组*/ memset(USART_RX_BUF, 0, sizeof (USART_RX_BUF));
/*重置接收数组指针*/ RxCounter = 0; USART_RX_STA = 1; } }
三、测试接收效果:将收到数据原路发回
if(USART_RX_STA == 1) { USART_Send_String(USART2,UsartData); memset(UsartData, 0, sizeof (UsartData)); USART_RX_STA = 0; }