当前位置:   article > 正文

keil C51使用printf函数_keil c printf

keil c printf

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

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

  1. #include <STC15F2K60S2.H>
  2. #include "stdio.h"
  3. #include "intrins.h"
  4. void Delay1000ms(void);
  5. void UartInit(void);
  6. void main(void)
  7. {
  8. UartInit();
  9. for(;;)
  10. {
  11. printf("Hello, STC!\r\n");
  12. Delay1000ms();
  13. }
  14. }
  15. void UartInit(void) //9600bps@11.0592MHz
  16. {
  17. SCON = 0x50; //8位数据,可变波特率
  18. AUXR |= 0x01; //串口1选择定时器2为波特率发生器
  19. AUXR |= 0x04; //定时器2时钟为Fosc,即1T
  20. T2L = 0xE0; //设定定时初值
  21. T2H = 0xFE; //设定定时初值
  22. AUXR |= 0x10; //启动定时器2
  23. }
  24. char putchar(char ch)
  25. {
  26. SBUF = ch;
  27. while(TI == 0);
  28. TI = 0;
  29. return ch;
  30. }
  31. void Delay1000ms(void) //@11.0592MHz
  32. {
  33. unsigned char i, j, k;
  34. _nop_();
  35. _nop_();
  36. i = 43;
  37. j = 6;
  38. k = 203;
  39. do
  40. {
  41. do
  42. {
  43. while (--k);
  44. } while (--j);
  45. } while (--i);
  46. }

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

以输出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);

输出效果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/404218?site
推荐阅读
相关标签
  

闽ICP备14008679号