UART Interrupt
UART Interrupt的示例工程实现了UART的中断方式收发数据。
UART Interrupt示例的源代码和工程文件位于SDK_Folder\projects\peripheral\uart\uart_interrupt,其中工程文件在文件夹Keil_5下。
代码理解
示例工程流程图如图 33所示:
- 配置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 章节。
- 调用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); - 调用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');
测试验证
- 用GProgrammer下载uart_interrupt.bin至开发板。
- 将开发板串口连接至PC端,打开并配置GRUart。
- 在GRUart的Receive Data窗口中将会显示通过UART接收与发送的数据信息。