在Keil C51 中使用printf ,首先需要重新實(shí)現(xiàn) putchar(char c)函數(shù)。此函數(shù)在
charputchar(charc){ES=0;SBUF=c;while(TI==0);TI=0;ES=1;return0;}
我們先分析一下上面這個程序哈,
關(guān)閉串口中斷
發(fā)送單字節(jié)數(shù)據(jù)
等待發(fā)送完畢
清除TI標(biāo)志
開啟串口中斷
在main函數(shù)里可以直接使用printf函數(shù)進(jìn)行輸出了。
但是,我一直存在這樣一個疑惑:
voidmain(){unsignedchartest1=55;printf("thetestis%drn",test1);}
使用串口輸出的數(shù)值一直不對,我后來自己理解,%d是整型,而在Keil C51整型占用2個byte,所以我一般的解決辦法是做一次強(qiáng)制類型轉(zhuǎn)換:
voidmain(){unsignedchartest1=55;printf("thetestis%drn",(int)test1);}
后來閱讀Keil C51的幫助手冊:
得到這樣一條信息:
所以上面的問題的另一個解決方案是:
voidmain(){unsignedchartest1=55;printf("thetestis%bdrn",test1);}
下面附上Keil C51手冊內(nèi)容。
int printf (
const charfmtstr /format string */
<[>, arguments … <]>); /* additional arguments */
Description The printf function formats a series of strings and numeric values and builds a string to write to the output stream using the putchar function. The fmtstr argument is a format string that may be composed of characters, escape sequences, and format specifications.
Ordinary characters and escape sequences are copied to the stream in the order in which they are interpreted. Format specifications always begin with a percent sign (‘%’) and require that additional arguments are included in the printf function call.
The format string is read from left to right. The first format specification encountered references the first argument after fmtstr and converts and outputs it using the format specification. The second format specification accesses the second argument after fmtstr, and so on. If there are more arguments than format specifications, extra arguments are ignored. Results are unpredictable if there are not enough arguments for the format specifications or if the argument types do not match those specified by fmtstr.
Format specifications have the following general format:
% <[>flags<]> <[>width<]> <[>.precision<]> <[>{b|B|l|L}<]> type
Each field in the format specification may be a single character or a number which specifies a particular format option.
The type field is a single character that specifies whether the argument is interpreted as a character, string, number, or pointer, as shown in the following table.