在调试基于STC15芯片的单片机时,使用printf能灵活的显示信息,方便调试。
关于如何在STC系列的单片机中使用,这里简单提一下
- 包含头文件 stdio.h
- 重写 putchar函数
回到正题:
当我如下编写代码时
char chr = 100;
printf("%d",chr);
显示的并不是100,而是随机的16位数据。
随后找C51的帮助文档发现这么两句话:
The optional characters l or L may immediately precede the type
character to respectively specify long types for d, i, u, o, x, and
X. The optional characters b or B may immediately precede the type
character to respectively specify char types for d, i, u, o, x, and X.
也就是说要
显示long类型 %d ===> %ld
显示char类型 %d ===> %bd
上面的代码要改成如下
char chr = 100;
printf("%bd",chr);
问题到这里就解决了,补充点参考内容:
char 1byte
int 2byte
long 4byte
Example
#include <stdio.h>
void tst_printf (void) {
char a = 1;
int b = 12365;
long c = 0x7FFFFFFF;
unsigned char x = 'A';
unsigned int y = 54321;
unsigned long z = 0x4A6F6E00;
float f = 10.0;
float g = 22.95;
char buf [] = "Test String";
char *p = buf;
printf ("char %bd int %d long %ld\n",a,b,c);
printf ("Uchar %bu Uint %u Ulong %lu\n",x,y,z);
printf ("xchar %bx xint %x xlong %lx\n",x,y,z);
printf ("String %s is at address %p\n",buf,p);
printf ("%f != %g\n", f, g);
printf ("%*f != %*g\n", (int)8, f, (int)8, g);
}