嵌入式开发串口printf重定向实现方法
方法一 重写fputc
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
记得添加#include "stdio.h"头文件
方法二
#include "stdarg.h"
#include "stdio.h"
int UART_printf(UART_HandleTypeDef *huart, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int length;
char buffer[128];
length = vsnprintf(buffer, 128, fmt, ap);
HAL_UART_Transmit(huart,buffer,length,HAL_MAX_DELAY);//HAL_MAX_DELAY
// CDC_Transmit_FS((uint8_t*)buffer,length);
va_end(ap);
return length;
}