#include
#include
static void _itoa(uint16 num, uint8 *buf, uint8 radix)
{
char c,i;
uint8 *p, rst[5];
p = rst;
for ( i=0; i<5; i++,p++ )
{
c = num % radix; // Isolate a digit
*p = c + (( c < 10 ) ? '0' : '7'); // Convert to Ascii
num /= radix;
if ( !num )
break;
}
for ( c=0 ; c<=i; c++ )
*buf++ = *p--; // Reverse character order
*buf = '\0';
}
static int vsprintf(char *buf, const char *fmt, va_list args)
{
char* p;
uint8 radix = 0;
int num = 0;
for (p = buf; *fmt; fmt++)
{
if (*fmt != '%')
{
if (*fmt == '\n')
{
*p++ = '\r';
}
*p++ = *fmt;
continue;
}
fmt++;
radix = 0;
switch (*fmt)
{
case 'x':
radix += 6;
case 'd':
radix += 2;
case 'o':
{
char tmp[10];
radix += 8;
num = va_arg(args, int);
_itoa(num, (uint8 *)tmp, radix);
num = strlen(tmp);
strncpy(p, tmp, num);
p += num;
}
break;
case 's':
{
char *s = va_arg(args, char *);
num = strlen(s);
strncpy(p, s, num);
p += num;
}
break;
default:
///unsupport
va_arg(args, char *);
num = strlen(" unknow type % ");
strncpy(p, " unknow type % ", num);
p += num;
*(p - 2) = *fmt;
break;
}
}
return (p - buf);
}
void printf(char*fmt, ...)
{
char buf[256];
va_list arg;
int len = 0;
int wr = 0;
int off = 0;
va_start(arg, fmt);
len = vsprintf(buf, fmt, arg);
va_end(arg);
while (len)
{
#if (HAL_UART_DMA)
if (len >= 128)
{
wr = HalUARTWrite(0, (uint8 *)buf + off, 64);
}
else
#endif
{
wr = HalUARTWrite(0, (uint8 *)buf + off, len);
}
len -= wr;
off += wr;
if (!wr)
{
HalUARTPoll();
}
}
}
使用:
void osal_start_system( void )
{
#if !defined ( ZBIT ) && !defined ( UBIT )
for(;;) // Forever Loop
#endif
{
osal_run_system();
static int i = 0;
if ((i++ % 2000) == 0)
{
printf("my printf: %p, %d, 0x%x, %s\n", &i, 123, 0xABC, "test");
}
}
}
效果:
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test
my printf: unknow type %p , 123, 0xABC, test