串口输出封装成printf结构
使用一个va_list配合vsprintf可以实现类似printf的串口输出风格,一个简单的基于HAL库的输出方法如下:
#include <stdio.h>
#include <stdarg.h>
#include "stm32h7xx.h"
#include <string.h>
int USART1Printf(const char* format, ...)
{
static char sendBuff[1024] = { 0 };//这里明显给了很大的缓冲,可以按需要调整
int bytes = 0;
va_list list;
va_start(list, format);
bytes = vsprintf(sendBuff, format, list);
va_end(list);
FLAG_USART1BUSY=1;
HAL_UART_Transmit_IT(&huart1, (void*)sendBuff, bytes); //真正的单片机发送函数,用什么库改什么发送
return bytes;
}
USART1Printf("This is a test message, tried %d times and support float %f",count,f_num);//一个简单的使用示例
需要注意的是部分单片机没有浮点处理能力或者浮点处理需要额外配置,例如在STM32中,如果使用了精简的stdio库,那么还需要在项目设置中打开float支持,这样才能用f%
串口输出封装成printf结构
http://localhost:8090//archives/chuan-kou-shu-chu-han-shu-er-ci-feng-zhuang