单片机八位时钟

 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 #include <reg51.h>
 9 #include <stdio.h>
10      //定义共阴数码管断码  0    1    2    3    4     5   6     7    8    9   A    B    C     D   E    F
11 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;//启动定时器0
27    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次,即1s
58     {
59        sec++;//秒就累加
60        t50ms = 0;//50ms清零
61        if(sec == 60)//秒钟为60s
62        {
63       min++;//分钟就累加
64       sec = 0;//秒清零
65       if(min ==60)//分钟为60m
66       {
67          hour++;//小时就累加
68          min = 0;//分钟清零
69          if(hour ==24)//hour为24小时
70       {
71          hour = 0;//hour清零
72       }
73       }
74        }
75     }
76  }

原文地址:https://www.cnblogs.com/liangjinjie/p/6946897.html