CN / EN
文档反馈
感谢关注汇顶文档,期待您的宝贵建议!
感谢您的反馈,祝您愉快!

UART Interrupt

UART Interrupt的示例工程实现了UART的中断方式收发数据。

UART Interrupt示例的源代码和工程文件位于SDK_Folder\projects\peripheral\uart\uart_interrupt,其中工程文件在文件夹Keil_5下。

代码理解

示例工程流程图如图 33所示:

图 33 UART Interrupt工程流程图
  1. 配置UART模块。
    g_uart_handle.p_instance = SERIAL_PORT_GRP;
    g_uart_handle.init.baud_rate = 115200;
    g_uart_handle.init.data_bits = UART_DATABITS_8;
    g_uart_handle.init.stop_bits  = UART_STOPBITS_1;
    g_uart_handle.init.parity = UART_PARITY_NONE;
    g_uart_handle.init.hw_flow_ctrl = UART_HWCONTROL_NONE;
    g_uart_handle.init.rx_timeout_mode = UART_RECEIVER_TIMEOUT_ENABLE;
    hal_uart_deinit(&g_uart_handle);
    hal_uart_init(&g_uart_handle);
    

    UART详细配置参数请参考 UART DMA 章节。

  2. 调用hal_uart_transmit_it()接口发送数据,接收结果与状态通过回调函数hal_uart_rx_cplt_callback()返回,用户可在此函数自定义可执行操作。因采用非阻塞方式的接口,需在后续步骤中用while判断是否收发完成。
    hal_uart_transmit_it(&g_uart_handle, (uint8_t *)"\r\nPlease input characters(<126) 
                         and end with newline.\r\n", 55);
    while (!g_tx_done);
    g_tx_done = 0;
    hal_uart_transmit_it(&g_uart_handle, (uint8_t *)"Input:\r\n", 8);
    while (!g_tx_done);
    
  3. 调用hal_uart_receive_it()接口接收数据,接收结果与状态通过回调函数hal_uart_rx_cplt_callback()返回,在接收完成的回调里调用hal_uart_receive_it()继续接收,同时通过hal_uart_transmit_it()发送接收到的数据,发送结果与状态通过回调函数hal_uart_tx_cplt_callback()返回,直到收到的数据为‘0’时,测试结束。代码如下:
    void hal_uart_tx_cplt_callback(uart_handle_t *huart)
    {
        g_tx_done = 1;
    }
    
    void hal_uart_rx_cplt_callback(uart_handle_t *huart)
    {
        g_rx_done = 1;
        g_rx_len  = g_uart_handle.rx_xfer_size - g_uart_handle.rx_xfer_count;
        hal_uart_receive_it(&g_uart_handle, rx_data, 128);
    }
    
    do {
        while (!g_rx_done);
        g_rx_done = 0;
        g_tx_done = 0;
        hal_uart_transmit_it(&g_uart_handle, rx_data, g_rx_len);
        while (!g_tx_done);
    } while (rx_data[0] != '0');
    

测试验证

  1. 用GProgrammer下载uart_interrupt.bin至开发板。
  2. 将开发板串口连接至PC端,打开并配置GRUart。
  3. 在GRUart的Receive Data窗口中将会显示通过UART接收与发送的数据信息。

扫描关注

打开微信,使用“扫一扫”即可关注。