- #include<reg51.h>
- #define uchar unsigned char
- #define uint unsigned int
- uchar min,sec,count,sec1,sec2,min0,min1,min2,keystopc,temp;
- sbit keystop=P3^0;
- sbit keyh=P3^1;
- sbit keym=P3^2;
- sbit keys=P3^3;
- sbit lcden=P3^4;
- sbit lcdrw=P3^6;
- sbit lcdrs=P3^5;
- uchar code table[]={'0','1','2','3','4','5','6','7','8','9',':'};
- void init() //定时器初始化
- {
- count=0;
- min=0;
- sec=59;
- TMOD=0x01;
- TH0=(65536-50000)/256;
- TL0=(65536-50000)%256;
- TR0=0;
- ET0=1;
- EA=1;
- }
- void delay(uint z) //延时程序
- {
- uint x,y;
- for(x=z;x>0;x--)
- for(y=110;y>0;y--);
- }
- /**************************************************************
- ------LCD1602显示函数------
- *************************************************************/
- void write_com(uchar com)
- {
- lcdrs=0;
- P0=com;
- delay(5);
- lcden=1;
- delay(5);
- lcden=0;
- }
- void write_data(uchar date)
- {
- lcdrs=1;
- P0=date;
- delay(5);
- lcden=1;
- delay(5);
- lcden=0;
- }
- void init_1602() //初始化1602
- {
- lcden=0;
- lcdrw=0;
- write_com(0x38);
- write_com(0x0c);
- write_com(0x06);
- write_com(0x01);
- write_com(0x80);
- }
- void write_Char(unsigned char x,unsigned char y,unsigned char date)
- {
- if (y == 0)
- {
- write_com(0x80 + x);
- }
- else
- {
- write_com(0xC0 + x);
- }
- write_data(date);
- }
- void display(uchar min0,uchar min1,uchar min2,uchar sec1,uchar sec2) //显示程序
- {
- write_Char(3,0,table[min0]);
- write_Char(4,0,table[min1]);
- write_Char(5,0,table[min2]);
- write_Char(6,0,table[0x0a]);
- write_Char(7,0,table[sec1]);
- write_Char(8,0,table[sec2]);
- }
- /************************************************************
- ------计时器/定时器0-----
- *************************************************************/
- void count0() interrupt 1
- {
- TH0=(65536-50000)/256;
- TL0=(65536-50000)%256;
- count++;
- if(count==20)
- {
- count=0;
- if(sec==0)
- {
- if (min!=0)
- {
- sec=59;
- min--;
- }
- }
- else sec--;
- }
- }
- /************************************************************
- ------主函数------
- *************************************************************/
- void main()
- {
- init();
- init_1602();
- while(1)
- {
- if(keystop==0) //检测是否停止键按下
- {
- delay(10);
- if(keystop==0)
- {
- if(keystopc!=1) keystopc++; //按停止键的次数
- else keystopc=0;
- while(keystop==0); //松手检测
- delay(5);
- while(keystop==0);
- }
- switch(keystopc)
- {
- case 1:TR0=0;break; // 按键一次就停止计数
- case 0:TR0=1;break;
- default:break;
- }
- }
- if(keyh==0) //实现小时加一
- {
- delay(50);
- if(keyh==0)
- {
- if(min!=110)
- {
- min++;
- }
- }
- while(!keym); //松手检测
- delay(5);
- while(!keym);
- }
- if(keym==0) //实现分钟加一
- {
- delay(100);
- if(keym==0)
- {
- if(min!=0)
- {
- min--;
- }
- }
- while(!keyh); //松手检测
- delay(5);
- while(!keyh);
- }
- min0=min/100;
- min1=min%100/10;
- min2=min%10;
- sec1=sec/10;
- sec2=sec%10;
- display(min0,min1,min2,sec1,sec2); //一直显示时钟
- }
- }
复制代码 |