串口中断
-
使用
__HAL_UART_ENABLE_IT(&huart3, UART_IT_RXNE);
开启中断,中断处理函数HAL_UART_IRQHandler
会自动更新开启中断,回显代码例程如下:__HAL_UART_ENABLE_IT(&huart3, UART_IT_RXNE);
/** * @brief This function handles USART3 global interrupt. */ void USART3_IRQHandler(void) { /* USER CODE BEGIN USART3_IRQn 0 */ if(__HAL_UART_GET_FLAG(&huart3, UART_FLAG_RXNE)) { // Read the received byte uint8_t received_byte = (uint8_t)(huart3.Instance->DR & 0xFF); //HAL_UART_Receive(&huart3, reuart, 1, 10); // Echo the received data HAL_UART_Transmit(&huart3, &received_byte, 1, 10); // Transmit the received byte with a timeout of 10ms } /* USER CODE END USART3_IRQn 0 */ HAL_UART_IRQHandler(&huart3); /* USER CODE END USART3_IRQn 1 */ }
使用寄存器读取接收值和
HAL_UART_Transmit
都可以,推荐寄存器读取。 -
使用
HAL_UART_Receive_IT(&huart3, reuart, 1);
开启中断,中断处理函数HAL_UART_IRQHandler
不会自动更新开启中断,记得在中断中再次开启接收中断。uint8_t reuart[1]="\0" HAL_UART_Receive_IT(&huart3, reuart, 1);
/** * @brief This function handles USART3 global interrupt. */ void USART3_IRQHandler(void) { /* USER CODE BEGIN USART3_IRQn 0 */ /* USER CODE END USART3_IRQn 0 */ HAL_UART_IRQHandler(&huart3); /* USER CODE BEGIN USART3_IRQn 1 */ HAL_UART_Transmit(&huart3, reuart, 1, 10); HAL_UART_Receive_IT(&huart3, reuart, 1); /* USER CODE END USART3_IRQn 1 */ }
或者在
HAL_UART_RxCpltCallback
中编写回调函数:void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART3) { HAL_UART_Transmit(&huart1,reuart,1,100); } } void USART3_IRQHandler(void) { /* USER CODE BEGIN USART3_IRQn 0 */ /* USER CODE END USART3_IRQn 0 */ HAL_UART_IRQHandler(&huart3); /* USER CODE BEGIN USART3_IRQn 1 */ HAL_UART_Receive_IT(&huart3, reuart, 1); /* USER CODE END USART3_IRQn 1 */ }
大家可自行选择使用方法。