STM32 的 printf() 函数串口重定向(HAL库标准库都适用)

1.建立工程

2.核心:添加新文件usar_fputc.c (名字随便自己命名),把文件添加到项目中去 

  #include "stdio.h"
  #include "stm32f1xx_hal.h"

  extern UART_HandleTypeDef huart1;
  uint8_t ch;
  uint8_t ch_r;

  //重写这个函数,重定向printf函数到串口
  /*fputc*/
  int fputc(int c, FILE * f)
  {
    ch=c;
    HAL_UART_Transmit(&huart1,&ch,1,1000);//发送串口
    return c;
  }

 

  //重定向scanf函数到串口 意思就是说接受串口发过来的数据
  /*fgetc*/
  int fgetc(FILE * F)
  {
    HAL_UART_Receive (&huart1,&ch_r,1,0xffff);//接收
    return ch_r;
  }

3.修改main.c 文件

  #include "stdio.h" /*添加头文件 */

  在main()函数里添加测试代码:printf("\n===函数Printf函数发送数据===\n");  //测试内容

4.打开串口助手测试最终效果如图:

  

原文地址:https://www.cnblogs.com/xingboy/p/9522940.html