移植了C语言的printf()函数到51单片机上,实现了在51单片机的串口类pc端的printf()输出。
使用方法:
在项目工程中添加xxprintf.h和xxprintf.c文件
在项目中需要使用xxprintf()函数的地方引入头文件xxprintf.h,在xxprintf.h中引入单片机相关头文件
在xxprintf.h中的MaxSize 可根据需要调整最大输出字符数量,例如修改为一下:
#define MaxSize 40 //确定最长的输出字符数量
意为输出最大字符数量为40
使用格式示例(注意在51系列单片机串口输出中使用’\r\n’ 作为换行符):
xxprintf(“1234”);
xxprintf(“1234\r\n”);
xxprintf(“aaa %d bbb\r\n”,num);
xxprintf(“aaa %c bbb\r\n”,ch);
xxprintf.h
#ifndef __XXPRINTF_H
#define__XXPRINTF_H
#include #include #include #include #define MaxSize 50//确定最长的输出字符数量
//向串口发送一个字符
void send_char_com( char ch);
void send_string_com(char *p_str);
int xxprintf(const char *fmt, ...);
#endif
xxprintf.c
#include "xxprintf.h"
//***************************************** 自定义模拟printf()函数实现*******
void send_char_com( char ch)
{
SBUF=ch;
while(TI==0);
TI=0;
}
//向串口发送一个字符串
void send_string_com(char *p_str)
{
while((*p_str)!= '\0')
{
send_char_com(*p_str);
p_str++;
}
}
//模拟printf()函数的输出
int xxprintf(const char *fmt, ...)
{
int printed;
va_list args;
char send_buff[MaxSize];
memset(send_buff,'\0',MaxSize);
va_start(args, fmt);
printed = vsprintf(send_buff, fmt, args);
va_end(args);
send_string_com(send_buff);
return printed;
}
//-----------------------------------