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

1.创建工程函数

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

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

  extern UART_HandleTypeDef huart1;
  uint8_t ch;
  uint8_t ch_r;spa

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

 

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

3.修改main.c 文件get

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

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

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