单片机软件设计——带打印级别的printf

写单片代码的时候,经常需要使用调试串口输出打印信息来观察运行状态,但是又不想把所有的信息都打印出来,所以就想封装有一个可以设置打印级别的函数,可以通过串口给单片机发送一个打印级别,然后单片机根据这个级别打印相应的内容。

printf.h

#ifndef __PRINTF_H__
#define __PRINTF_H__

#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
//只会打印比全局打印等级低的数据
enum PRINTF_LEVEL
{
	ePRINTF_LV0,//必定打印的等级
	ePRINTF_LV1,
	ePRINTF_LV2,
	ePRINTF_LV3,
	ePRINTF_LV4,
	ePRINTF_LV5,
};


extern enum PRINTF_LEVEL g_print_level;

void gk_printf(uint8_t lv, char *fmt, ...);
#endif

printf.c

#include "printf.h"

enum PRINTF_LEVEL g_print_level;

//带打印等级的串口输出函数
void gk_printf(uint8_t lv, char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	if(g_print_level >= lv)
	{
		vprintf(fmt, ap);//必须用带v的
	}
	va_end(ap);
}

测试代码:

int main(void)
{
        g_print_level = ePRINTF_LV2;//设置全局打印级别为LV2
	gk_printf(ePRINTF_LV0,"this is the level 0\n");
	gk_printf(ePRINTF_LV1,"this is the level 1\n");
	gk_printf(ePRINTF_LV2,"this is the level 2\n");
	gk_printf(ePRINTF_LV3,"this is the level 3\n");
	gk_printf(ePRINTF_LV4,"this is the level 4\n");
	gk_printf(ePRINTF_LV5,"this is the level 5\n");
	for(uint8_t i = 0; i < 5; i++)
	{
		gk_printf(i,"I AM %d\n",i);
	}
        while(1);
}

运行结果:

this is the level 0
this is the level 1
this is the level 2
I AM 0
I AM 1
I AM 2

posted @ 2021-04-01 00:25  曾经梦想少年  阅读(529)  评论(0编辑  收藏  举报