stm32f407-openocd/Core/Src/debug.c

171 lines
3.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include "debug.h"
/***
* 自己写的printf函数
* 函数定义void Printf(const char *format, ...)
* 目前支持%d,%c,%s,%f
* */
/**
* @brief uart输出单个字符-interface
*
* @param c 输出字符
*/
void PutChar(char c)
{
extern void putChar(char c);
putChar(c);
}
void printch(const char ch) // 输出字符
{
PutChar(ch);
}
void printint(const int dec) // 输出整型数
{
// if (dec == 0)
// {
// PutChar('0');
// return;
// }
if (dec == 0)
{
return;
}
printint(dec / 10);
PutChar((char)(dec % 10 + '0'));
}
void printstr(const char *ptr) // 输出字符串
{
while (*ptr)
{
PutChar(*ptr);
ptr++;
}
}
static void printBit(const unsigned int dec)
{
if (dec == 0)
{
return;
}
printBit(dec / 2);
PutChar((char)(dec % 2 + '0'));
}
void printfloat(const float flt) // 输出浮点数小数点第5位四舍五入
{
int tmpint = (int)flt;
int tmpflt = (int)(100000 * (flt - tmpint));
if (tmpflt % 10 >= 5)
{
tmpflt = tmpflt / 10 + 1;
}
else
{
tmpflt = tmpflt / 10;
}
printint(tmpint);
PutChar('.');
printint(tmpflt);
}
void printX(const unsigned int uint)
{
PutChar('0');
PutChar('x');
for (int i = 7; i >= 0; i--)
{
printint(uint >> (4 * i) & 0xf);
}
}
void Printf(const char *format, ...)
{
va_list ap;
va_start(ap, format); // 将ap指向第一个实际参数的地址
while (*format != '\0')
{
if (*format != '%')
{
PutChar(*format);
format++;
}
else
{
format++;
switch (*format)
{
case 'c':
{
char valch = va_arg(ap, int); // 记录当前实践参数所在地址
printch(valch);
format++;
break;
}
case 'd':
{
int valint = va_arg(ap, int);
if (valint)
printint(valint);
else
{
PutChar('0');
}
format++;
break;
}
case 's':
{
char *valstr = va_arg(ap, char *);
printstr(valstr);
format++;
break;
}
case 'f':
{
float valflt = va_arg(ap, double);
printfloat(valflt);
float dot = valflt - (int)valflt;
if(dot == 0.0){
PutChar('0');
}
format++;
break;
}
case 'b':
{
unsigned int valint = va_arg(ap, unsigned int);
if (valint)
printBit(valint);
else
{
PutChar('0');
}
format++;
break;
}
case 'x':
{
unsigned int valint = va_arg(ap, unsigned int);
printX(valint);
format++;
break;
}
default:
{
printch(*format);
format++;
}
}
}
}
va_end(ap);
}