STM32CubeMX HAL库工程printf串口打印重定向

转载于:https://www.bilibili.com/video/av64690830?p=12

1. 引入头文件 stdio.h

#include "stdio.h"

2.添加重定向代码

  • 此处我是将printf函数重定向到串口1
// 重定向printf函数
int fputc(int ch,FILE *f)
{
    uint8_t temp[1]={ch};
    HAL_UART_Transmit(&huart1,temp,1,2);
	return 0;
}

3.添加DEBUG宏定义

  • 使用以下宏定义,debug结果会按照格式化输出,非常方便
#define USER_MAIN_DEBUG

#ifdef USER_MAIN_DEBUG
#define user_main_printf(format, ...) printf( format "\r\n",##__VA_ARGS__)
#define user_main_info(format, ...) printf("【main】info:" format "\r\n",##__VA_ARGS__)
#define user_main_debug(format, ...) printf("【main】debug:" format "\r\n",##__VA_ARGS__)
#define user_main_error(format, ...) printf("【main】error:" format "\r\n",##__VA_ARGS__)
#else
#define user_main_printf(format, ...)
#define user_main_info(format, ...)
#define user_main_debug(format, ...)
#define user_main_error(format, ...)
#endif

猜你喜欢

转载自blog.csdn.net/u014779536/article/details/104369364