新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設計應用 > avr單片機 串口實現(xiàn)printf(使用變參函數(shù))

avr單片機 串口實現(xiàn)printf(使用變參函數(shù))

作者: 時間:2018-09-14 來源:網(wǎng)絡 收藏

#include

本文引用地址:http://2s4d.com/article/201809/389165.htm

#include

#include

typedef unsigned char uint8;

static void usart_init(void)

{

UCSRA = 0x02;

UCSRB = 0x18;

UCSRC = 0x06;

UBRRH = 0x00;

UBRRL = 103;

}

static void put_char(uint8 data)

{

if (data == '/r')

put_char(0x09);

while ( !(UCSRA (1

;

UDR = data;

}

static void my(const char* fmt,...)

{

const char* s;

int d;

char buf[16];

va_list ap;

va_start(ap,fmt); // 將ap指向fmt(即可變參數(shù)的第一個?下一個?)

while (*fmt)

{

if (*fmt != '%')

{

put_char(*fmt++); // 正常發(fā)送

continue;

}

switch (*++fmt) // next %

{

case 's':

s = va_arg(ap,const char*); // 將ap指向者轉成char*型,并返回之

for (; *s; s++)

put_char(*s);

break;

case 'x':

d = va_arg(ap,int); // 將ap指向者轉成int型,并返回之

itoa(d,buf,16); // 將整型d以16進制轉到buf中

for (s = buf; *s; s++)

put_char(*s);

break;

case 'd':

d = va_arg(ap,int);

itoa(d,buf,10); // 將整型d以10進制轉到buf中

for (s = buf; *s; s++)

put_char(*s);

break;

default:

put_char(*fmt);

break;

}

fmt++;

}

va_end(ap);

}

int main(void)

{

usart_init(); // 初始化

uint8 i = 100;

uint8* s = Word!;

while(1)

{

my(/n/rHello %s/n/r0x%x = %d/n,s,i,i);

}

return 0;

}



評論


相關推薦

技術專區(qū)

關閉