STM32串口环形缓冲接收机制

//接收数据缓存区 	
u8 USART2RX_BUF[USART2_RX_BUFFER_SIZE];  	//接收缓冲,最大64个字节.
u8 buffer_msg[256] = {0};
u8 len_handleUsart = 0;

u16 USART2_RxHead;
u16 USART2_RxTail;

void USART2_IRQHandler(void)                	//串口1中断服务程序
{
	u8 Res;
	u16 tmphead;

	if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)  //接收中断(接收到的数据必须是0x0d 0x0a结尾)
	{
		Res =USART_ReceiveData(USART2);	//读取接收到的数据
		
		tmphead = (USART2_RxHead + 1) & USART2_RX_BUFFER_MASK;
		USART2_RxHead = tmphead;      /* Store new index */
		if(tmphead == USART2_RxTail)
		{
			// Receive buffer overflow
		}
		USART2RX_BUF[tmphead] = Res;	 
	} 
} 


/*----------------------------------------------------------------------------
  Read character from Serial Port, But it through buffer
 *----------------------------------------------------------------------------*/
u8 IT_GetChar (void) 
{
	u16 tmptail;
	
	while( USART2_RxHead == USART2_RxTail );
			//return NO_DATA_COM;  /* Wait for incomming data */
		
	tmptail = ( USART2_RxTail + 1 ) & USART2_RX_BUFFER_MASK;/* Calculate buffer index */
	
	USART2_RxTail = tmptail;                /* Store new index */
	
	return USART2RX_BUF[tmptail];  /* Return data */

}

u8 DataInReceiveBuffer( void )
{
	return ( USART2_RxHead != USART2_RxTail ); /* Return 0 (FALSE) if the receive buffer is empty */
}
//处理BLE命令字
u8 handle_cmd_data(void)
{
	u8 str[256]={0},i;
	u8 sum=0;
	float Roll=0,Pitch=0,Yaw=0;
	while(DataInReceiveBuffer()!= 0)
	{  				
		buffer_msg[len_handleUsart] = IT_GetChar();
		printf("%x ",buffer_msg[len_handleUsart]);
		len_handleUsart++;
		if(len_handleUsart >= 255)
			break;
	}
	return 0;
}

你可能感兴趣的:(STM32)