生成代码
1.配置串口1
2.选择模式
3.开中断
4.其他的RCC、调试都一样,弄完直接生成代码。
串口发送
1.定义一个用来测试的数组并初始化
/* USER CODE BEGIN 0 */
uint8_t aTxBuffer[]="123";
/* USER CODE END 0 */
2.主函数while循环发送
while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ HAL_Delay(1000); HAL_UART_Transmit(&huart1,aTxBuffer,sizeof(aTxBuffer),0xffff); }
串口中断接受
1.定义接受数组
/* USER CODE BEGIN 0 */ uint8_t aRxBuffer[1]; /* USER CODE END 0 */
2.先开启中断,只起一次作用
/* USER CODE BEGIN 2 */ HAL_UART_Receive_IT(&huart1,(uint8_t *)aRxBuffer,1); /* USER CODE END 2 */
3.每次中断触发都要在中断回调函数再此开启串口接收中断
/* USER CODE BEGIN 4 */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART1)//判断串口号 { HAL_UART_Transmit(&huart1,aRxBuffer,1,100); HAL_UART_Receive_IT(&huart1, (uint8_t *)aRxBuffer, 1); //再开启接收中断 } } /* USER CODE END 4 */