STM32CubeMX系列教程5:串行通信(USART)
在usart.c文件后面添加如下代码,代码中添加了#ifdef宏定义进行条件编译,如果使用GUNC编译,则PUTCHAR_PROTOTYPE 定义为int __io_putchar(int ch)函数,否则定义为int fputc(int ch, FILE *f)函数。
/* USER CODE BEGIN 1 */
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
/* USER CODE END 1 */其中HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);这个语句表示通过串口1发个一个字符。ch为字符的存储地址,0xFFFF为超时时间。在stm32f7xx_hal_uart.c文件中可以找到HAL_UART_Transmit函数。在main.c文件中添加应用函数。
/* USER CODE BEGIN 2 */
printf("\n\r UART Printf Example: retarget the C library printf function to the UART\n\r");
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
printf("\n\r welcome to www.waveshere.com !!!\n\r");
HAL_Delay(1000);
}
/* USER CODE END 3 */编译程序并下载到开发板。用USB线连接开发板到电脑,在电脑上打开串口调试助手。选择对应的串口号,设置波特率为115200。按下复位按键会接收到如图信息。
生成报告以及代码,编译程序。在main函数前面添加两个数组变量。
/* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ uint8_t aTxStartMessage[] = "\r\n****UART-Hyperterminal communication based on IT ****\r\nEnter 10 characters using keyboard :\r\n"; /* Buffer used for reception */ uint8_t aRxBuffer[20]; /* USER CODE END PV */
在main函数中添加两个语句通过串口中断发送aTxStartMessage数组的数据和接收数据10个字符,保存在数组aRxBuffer中。
/* USER CODE BEGIN 2 */ HAL_UART_Transmit_IT(&huart1, (uint8_t *)aTxStartMessage, sizeof(aTxStartMessage)); HAL_UART_Receive_IT(&huart1, (uint8_t *)aRxBuffer, 10); /* USER CODE END 2 */
在main.c文件后面添加中断接收完成回调函数。中断回调函数中将接收到的数据又通过串口发送回去。
/* USER CODE BEGIN 4 */
/**
* @brief Rx Transfer completed callbacks
* @param huart: uart handle
* @retval None
*/
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(huart);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_UART_RxCpltCallback can be implemented in the user file
*/
HAL_UART_Transmit(&huart1, (uint8_t *)aRxBuffer, 10,0xFFFF);
}
/* USER CODE END 4 */编译程序并下载到开发板。用USB线连接开发板到电脑,在电脑上打开串口调试助手。选择对应的串口号,设置波特率为115200。按下复位按键会接收到aTxStartMessage数组的数据。通过串口助手发送10个字符,串口助手回显示发送的数据。注意:串口要发够10个字符串,才会触发中断。少于10个字符则不会触发中断,串口不会显示发送的数据。超过10个字符,串口只会发送10个字符回来显示。












支付宝打赏
微信打赏 



