串口接收中断的巧妙运用(基于KEA128,用于接收不定长数据帧)

//uart.c

unsigned int uart_rx_with_to(UART_Type *uart_prt, unsigned char *pbuffer)
{
    unsigned int i = 0;
    unsigned int len = 0;

    while (1)
    {
        if (uart_prt->S1 & UART_S1_RDRF_MASK)
        {
            i = 0;
            pbuffer[len] = uart_prt->D;    //get a char 
            len++;
            if (len >= 100)
            {   
				break;//防止发大量数据将程序搞崩溃
            }
        }
        else
        {
            i++;
            if (i >= 500) //lixttest 50-->500  接收数据越多,设置越大
            {
                break;    //end rx 
            }
        }
    }

    return len;
}


void UART2_IRQHandler(void)
{
    unsigned int len = 0;
	memset(uart_rx_data,0,sizeof(uart_rx_data));
    len = uart_rx_with_to(UART2, uart_rx_data);//rev data save to uart_rx_data
    NVIC_ClearPendingIRQ(UART2_IRQn);
	if (len == 6)
	{
		if (uart_rx_data[0] == 'g' && uart_rx_data[1] == 'e' && uart_rx_data[2] == 't' 
			&& uart_rx_data[3] == 'v' && uart_rx_data[4] == 'e' && uart_rx_data[5] ==    'r')
		{
			g_uart2_ver_rev_flag = 1;//getver
			uart_rx_irq_dis(uart2);//关闭串口2接收中断,待主函数中数据处理完毕后再打开中断
		}
	}
}

//main.c

if (g_uart2_ver_rev_flag == 1)
{
    uart_send(uart2,ver_cmd_send_buf,sizeof(ver_cmd_send_buf));
    uart_rx_irq_en(uart2);    //数据处理完毕后将串口2接收中断打开
    g_uart2_ver_rev_flag = 0;
}

 

你可能感兴趣的:(嵌入式)