keil C51使用printf函数

在使用printf函数之前需要注意亮点,一是调用头文件stdio.h,二是重定义putchar发送单个字符函数。这一点和MDK中开发AMR处理器不太一样,后者重定义的函数名fputc。

写个测试程序,不断通过串口发送一个字符串:

#include <STC15F2K60S2.H>
#include "stdio.h"
#include "intrins.h"

void Delay1000ms(void);
void UartInit(void);

void main(void)
{
    UartInit();
    for(;;)
    {
        printf("Hello, STC!\r\n");
        Delay1000ms();
    }
}

void UartInit(void)        //9600bps@11.0592MHz
{
    SCON = 0x50;        //8位数据,可变波特率
    AUXR |= 0x01;        //串口1选择定时器2为波特率发生器
    AUXR |= 0x04;        //定时器2时钟为Fosc,即1T
    T2L = 0xE0;        //设定定时初值
    T2H = 0xFE;        //设定定时初值
    AUXR |= 0x10;        //启动定时器2
}

char putchar(char ch)
{
    SBUF = ch;
    while(TI == 0);
    TI = 0;
    return ch;
}

void Delay1000ms(void)        //@11.0592MHz
{
    unsigned char i, j, k;

    _nop_();
    _nop_();
    i = 43;
    j = 6;
    k = 203;
    do
    {
        do
        {
            while (--k);
        } while (--j);
    } while (--i);
}

效果如下,可以看到实现预期功能:

以输出int型变量为例:

格式含义针对类型
%bd单字节变量char
%d两字节变量int
%ld四字节变量long int

其他变量类型输出格式含义

Type ArgumentType InputFormat
dintSigned decimal number.
uunsigned intUnsigned decimal number.
ounsigned intUnsigned octal number.
xunsigned intUnsigned hexadecimal number using “0123456789abcedf”.
Xunsigned intUnsigned hexadecimal number using “0123456789ABCDEF”.
ffloat

Floating-point number formatted as<[>-<]>dddd.dddd.

%.1f(输出保留1位小数)

efloatFloating-point number formatted as<[>-<]>d.dddde<[>-<]>dd.
EfloatFloating-point number formatted as<[>-<]>d.ddddE<[>-<]>dd.
gfloatFloating-point number using either the e or f format, whichever is more compact for the specified value and precision.
GfloatFloating-point number using either the E or f format, whichever is more compact for the specified value and precision.
ccharA single character.
s*A string of characters terminated by a null character (‘\0’).
p*A generic pointer formatted as t:aaaa where t is the memory type and aaaa is the hexadecimal address.

以输出浮点数举例

printf("tempX=%f\r\n",tempX);

输出效果如下:

  • 1
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值