完善资料让更多小伙伴认识你,还能领取20积分哦, 立即完善>
|
|
相关推荐
1个回答
|
|
一、基础配置 模式选择 : 配置为异步模式Asynchronous
二、printf 重定向 在 Private includes 中引入头文件: #include 在 USER CODE BEGIN PD 添加下面代码: #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *F) #endif PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY); return ch; } 使用printf输出浮点数: Project–>Properties–>C/C++ Build–>Settings–>MCU settings,如下图所示,勾选上即可。 实验一:通过串口发送数据
/* USER CODE BEGIN Includes */ #include /* USER CODE END Includes */ /* USER CODE BEGIN PD */ #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *F) #endif PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY); return ch; } /* USER CODE END PD */ /* USER CODE BEGIN 3 */ HAL_Delay(500); printf("Hello World!rn"); } /* USER CODE END 3 */
/* USER CODE BEGIN Includes */ #include /* USER CODE END Includes */ /* USER CODE BEGIN PD */ #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *F) #endif PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY); return ch; } /* USER CODE END PD */ /* USER CODE BEGIN PV */ uint8_t RxBuff[1]; // 用来接收串口2发送的数据 /* USER CODE END PV */ /* USER CODE BEGIN 2 */ HAL_UART_Receive_IT(&huart2, RxBuff, 1); /* USER CODE END 2 */ /* USER CODE BEGIN 4 */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(huart->Instance == USART2) // 判断是由哪个串口触发的中断 { HAL_UART_Transmit(&huart2,RxBuff,1,100); // 接收到数据马上使用串口2发送出去 HAL_UART_Receive_IT(&huart2,RxBuff,1); // 重新使能串口2接收中断 } } /* USER CODE END 4 */ 4 */ 实验现象: 将串口接收到的数据,又通过该串口发送回去 实验三:串口接收不定长数据(定时器方式实现)
/* USER CODE BEGIN Includes */ #include #include /* USER CODE END Includes */ /* USER CODE BEGIN PD */ #ifdef __GNUC__ #define PUTCHAR_PROTOTYPE int __io_putchar(int ch) #else #define PUTCHAR_PROTOTYPE int fputc(int ch,FILE *F) #endif PUTCHAR_PROTOTYPE { HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, HAL_MAX_DELAY); return ch; } /* USER CODE END PD */ /* USER CODE BEGIN PV */ uint8_t RxBuff[1]; //进入中断接收数据的数组 uint8_t DataBuff[100]; //保存接收到的数据的数组 int RxLine=0; //接收到的数据长度 int Rx_flag=0; //接受到数据标志 /* USER CODE END PV */ /* USER CODE BEGIN 0 */ void printf_usart(void) { printf("length=%drn",RxLine); DataBuff[RxLine] = ' |