1 /* Main.c file generated by New Project wizard 2 * 3 * Created: 周一 六月 5 2017 4 * Processor: 80C51 5 * Compiler: Keil for 8051 6 */ 7 8 #include9 #include 10 //定义共阴数码管断码 0 1 2 3 4 5 6 7 8 9 A B C D E F11 unsigned char duan[]= { 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};12 unsigned char wei[]={ 0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};//定义共阴数码管位码13 unsigned char t50ms = 0,sec =0, min = 0,hour = 0;//定义50ms,秒,分、时的变量14 unsigned char j;//定义循环变量15 //延时函数16 void delay(unsigned int i)17 {18 while(i--);19 }20 //定时器0的初始化21 void init(){22 TMOD = 0X01;//选择工作方式1,16位寄存器存储初值23 ET0 = 1;//打开定时器0的分开关24 TH0 = (65535-50000)/256;//给定时器0高八位赋初值25 TH0 = (65535-50000)%256;//给定时器0低八位赋初值26 TR0 = 1;//启动定时器027 EA = 1;//打开总闸28 }29 //主函数30 void main(void)31 { 32 init();//调用初始化函数33 while(1)//死循环34 {35 for(j=0;j<8;j++)36 {37 P1 = wei[j];//给P1端口送位码38 switch(j)//分别给八位数码管赋相应的值39 {40 case 0:P2=duan[hour/10];break;//hour/10:取到小时的十位41 case 1:P2=duan[hour%10];break;//hour%10:取到小时的个位42 case 2:P2=0X40;break;//显示小时和分钟之间的-(横杠)43 case 3:P2=duan[min/10];break;44 case 4:P2=duan[min%10];break;45 case 5:P2=0X40;break;46 case 6:P2=duan[sec/10];break;47 case 7:P2=duan[sec%10];break;48 default:break;49 }50 delay(500);//小延时51 }52 }53 }54 //中断服务子函数55 void dingshi() interrupt 1{56 t50ms++;//50ms累加57 if(t50ms == 20)//加到20次,即1s58 {59 sec++;//秒就累加60 t50ms = 0;//50ms清零61 if(sec == 60)//秒钟为60s62 {63 min++;//分钟就累加64 sec = 0;//秒清零65 if(min ==60)//分钟为60m66 {67 hour++;//小时就累加68 min = 0;//分钟清零69 if(hour ==24)//hour为24小时70 {71 hour = 0;//hour清零72 }73 }74 }75 }76 }