在网上找资料时找到一篇介绍在keil中使用printf()函数的文章,copy到这里,作为备忘。
在keil中printf默认是向串口中发送数据的,所以,如果应用该函数,必须先初始化串口,否则可能引起死机的情况,并且在printf之前应该先将TI置位,摘抄原因如下:
1.printf函数是调用putchar函数输入的,而putchar应该是先判断ti是否为1,不为1则等待为1。如果为1则清0,然后送出一 个字符。因此你如果直接使用printf函数,你的程序就会在putchar函数中等待ti为1。这时你的程序就相当于直接死掉了。你可以通过改写 putchar函数实现自己的目的的。
2.Keil的串口处理比较巧妙的,我的分析如下:
putchar.c里面,是先检测TI再发送。这样做的目的是把尽可能多的时间留给2次串口操作之间的程序,而不是把等待字节发送的时间白白空等待浪费掉。所以,在系统初始化的时候,一定要令TI=1; 就可以顺畅的使用printf函数了。搂主sbuf=" "的办法,其实就是令TI=1. 另外要特别注意,printf函数执行完毕后,最后一个字节并未发送完毕,例如在485通讯中,此时如果切换为收模式,会丢失最后一字节.
3.一般串口发送都是等TI(字节发送完标志)为1就马上发送下一字节,由于不管是中断还是查询TI标志的方法,都会检测TI,因此首次发送必须置 位TI标志,使串口开始发送你的“在程序的初始化部分往串口数据寄存器SBUF里放一个字符来起用终端显示;”方法最终作用也就是把TI置1,改成 TI=1;来启动发送也是一样的(当然,不会发出那个' '字符了)。
4.<stdio.h>中定义,调用底层的putchar()来实现.底层发送数据到串口时,先查TI=1是否成立,死等直到TI=1时将新数据写入SBUF,函数返回,所以要先将TI置1,启动第一次传输操作.可查看反汇编相关代码理解其工作机理!
下面举一个简单的例子:
//===========================
#include <reg51.h>
#include <stdio.h>
//-------------------------------
int main()
{
Uart_init(); //初始化串口,这里就不写具体代码了。
TI = 1; //keil 调用stdio.h中printf函数前要置位。
while(1)
{
printf("Hello world!\n");
delay_ms(800); //延时程序,这里也不写具体代码了。
}
return 0;
}
printf
Summary | #include <stdio.h> int printf ( const char *fmtstr /* 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 theputchar function. The fmtstrargument 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 additionalarguments are included in the |