在51单片机中,printf()函数是最常用的函数。
#include <REG51.h> //包含头文件REG51.h,使能51内部寄存器;
#include <stdio.h> //包含头文件stdio.h
//_getkey();从串口读入一个字符;
signed char Char_Value;
signed int Int_Value;
signed long Long_Value;
float Float_Value;
unsigned char Char_type_value;
char Buffer[]="7890";
//函数功能:初始化串口,设置波特率为1200bps@16MHz,使能接收,使用8位UART;
void Serial_Port_Initialization()
{ SCON = 0x50; //串行控制寄存器: SM0,SM1,SM2,REN,TB8,RB8,TI,RI
//SM1:SM0=01,选择方式1,SM2=0,表示非多机通讯,8-bit UART;
//REN=1,使能接收;
TMOD |= 0x20; //定时器方式控制寄存器:GATE1,C/T1,M11,M10,GATE0,C/T0,M01,M00
//GATE=0,TR置1便可以启动Timer;GATE=1,TR置1,且INT脚输入高电
//平,才可以启动Timer;
//M11:M10=10,选择方式2,8位自动重装载;
TH1 = 221; //TH1: reload value for 1200 baud @ 16MHz
TR1 = 1; //启动Timer1;
TI = 1; //发送UART的第一个字节,为下次发送做准备;
}
void main(void)
{
Serial_Port_Initialization();
//初始化串口,设置波特率为1200bps@16MHz,使能接收,使用8位UART;
for(;;)
{ Char_Value=-100;
printf("Char_Value=%bd\n",Char_Value);
//将字节型的值转换为有符号十进制数输出,"Char_Value=-100";
Char_Value=100;
printf("Char_Value=%bu\n",Char_Value);
//将字节型的值转换为无符号十进制数输出,"Char_Value=100";
Char_Value=100;
printf("Char_Value=%#bX\n",Char_Value);
//将字节型的值转换为无符号16进制ASCII码输出,"Char_Value=0X64"
printf("Char_Value=%bX\n",Char_Value);
//将字节型的值转换为无符号16进制ASCII码输出,"Char_Value=64"
Int_Value=-1000;
printf("Int_Value=%d\n",Int_Value);
//将双字节型的值转换为有符号十进制数输出,"Int_Value=-1000";
Int_Value=1000;
printf("Int_Value=%u\n",Int_Value);
//将双字节型的值转换为无符号十进制数输出,"Int_Value=1000";
Long_Value=1000000000;
printf("Long_Value=%Ld\n",Long_Value);
//将4字节型的值转换为无符号十进制数输出,"Long_Value=1000000000";
printf("Long_Value=%LX\n",Long_Value);
//将4字节型的值转换为无符号16进制ASCII码输出,"Long_Value=3B9ACA00";
Long_Value=-1000000000;
printf("Long_Value=%Ld\n",Long_Value);
//将4字节型的值转换为有符号十进制数输出,"Long_Value=-1000000000";
printf("Long_Value=%LX\n",Long_Value);
//将4字节型的值转换为有符号十进制数输出,"Long_Value=C4653600";
Float_Value=100.991;
printf("Float_Value=%8.3f\n",Float_Value);
//将浮点数转换为十进制ASCII码输出,"Float_Value=100.991";
printf("Float_Value=%e\n",Float_Value);
//将浮点数转换为ASCII码输出,"Float_Value=1.00991e+02";
Char_type_value=0x30;
printf("Char_type_value=%c\n",Char_type_value);
//将字节型的值转换为字符输出,"Char_type_value=0";
Char_type_value=0x31;
printf("Char_type_value=%c\n",Char_type_value);
//将字节型的值转换为字符输出,"Char_type_value=1";
Char_type_value=0x32;
printf("Char_type_value=%c\n",Char_type_value);
//将字节型的值转换为字符输出,"Char_type_value=2";
printf("Buffer[]=%s\n",Buffer);
//将Buffer[]中的字符串通过串口发送出去,"Buffer[]=7890";
printf("The first address of Buffer array=%p\n",Buffer);
//"The first address of Buffer array=i:000f";
}