这是一个计时器
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit lcden=P0^5;//1602的使能端
sbit lcdrs=P0^7;
sbit lcdrw=P0^6;
sbit k1=P3^5;//功能按键
sbit k2=P3^4;//加按键
sbit k3=P3^3;//减按键
sbit bz=P0^4;//蜂鸣器
uchar code table[]="countdown...";
uchar code table1[]="00:00:00";
uchar num,aa,k1num,k2num,k3num;
char shi,fen,miao,qian,bai,beepz;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void beep() //控制无源蜂鸣器响函
{
bz=1;
delay(2);
bz=0;
delay(2);
}
void write_com(uchar com)//1602写命令函数
{
lcdrs=0;
lcdrw=0;
P2=com;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void write_date(uchar date)//1602写数据函数
{
lcdrs=1;
lcdrw=0;
P2=date;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void write_sfm(uchar add,uchar date)//写时分秒函数
{
uchar shi,ge;
shi=date/10;
ge=date%10;
write_com(0x80+0x40+add);
write_date(0x30+shi);
write_date(0x30+ge);
}
void init()//初始化函数
{
miao=59;
fen=59;
shi=23;
lcden=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
write_com(0x80);
for(num=0;num<12;num++)
{
write_date(table[num]);
delay(5);
}
write_com(0x80+0x40);
for(num=0;num<8;num++)
{
write_date(table1[num]);
delay(5);
}
TMOD=0x01;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
EA=1;
ET0=1;
TR0=1;
write_sfm(6,miao);
write_sfm(3,fen);
write_sfm(0,shi);
}
void keyscan()//按键函数
{
if(k1==0) //检测K1按键按下
{
delay(5); //延时
if(k1==0) //再次检测K1按键按下
{
k1num++;
while(!k1);
if(k1num==1) //第一次按K1
{
TR0=0;//关闭定时器
write_com(0x80+0x40+7);//光标闪烁的位置
write_com(0x0f);//开启光标闪烁
}
if(k1num==2)//第二次按K1
{
write_com(0x80+0x40+4);//光标闪烁的位置
}
if(k1num==3)//第三次按K1
{
write_com(0x80+0x40+1);//光标闪烁的位置
}
if(k1num==4)//第四次按K1
{
TR0=1;//开定时器
k1num=0;//按清零键次数
write_com(0x0c);//关闭光标闪烁
}
}
}
if(k1num!=0)//K1没有按下的时候
{
if(k2==0)
{
delay(5);
if(k2==0)
{
while(!k2);
if(k1num==1)
{
miao++;
if(miao==60)
{
miao=0;
}
//s1=0;
write_sfm(6,miao);
write_com(0x80+0x40+7);
}
if(k1num==2)
{
fen++;
if(fen==60)
{
fen=0;
}
//s1=0;
write_sfm(3,fen);
write_com(0x80+0x40+4);
}
if(k1num==3)
{
shi++;
if(shi==24)
{
shi=0;
}
//s1=0;
write_sfm(0,shi);
write_com(0x80+0x40+1);
}
}
}
if(k3==0)
{
delay(5);
if(k3==0)
{
while(!k3);
if(k1num==1)
{
miao--;
if(miao==-1)
{
miao=59;
}
write_sfm(6,miao);
write_com(0x80+0x40+7);
}
if(k1num==2)
{
fen--;
if(fen==-1)
{
fen=59;
}
write_sfm(3,fen);
write_com(0x80+0x40+4);
}
if(k1num==3)
{
shi--;
if(shi==-1)
{
shi=23;
}
write_sfm(0,shi);
write_com(0x80+0x40+1);
}
}
}
}
}
void main() //主函数
{
init();//初始化
while(1)
{
keyscan();//等待检测是否有按键按下
}
}
void timer0() interrupt 1 //中断函数
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
aa++;
if(aa==18)
{
aa=0;
miao--;
if((miao==-1)&&(fen==1)&&(shi==0)) //判断到计时一分钟一秒钟报警
{
for(beepz=0;beepz<110;beepz++) //一秒钟报警
{
beep();
}
}
if((miao==-1)&&(fen==0)&&(shi==0)) //判断倒计时到时长响报警
{
TR0=0;
miao=0;
fen=0;
shi=0;
while(1) //长报警
{
beep();
}
}
if(miao==-1)
{
miao=59;
fen--;
if(fen==-1)
{
fen=59;
shi--;
write_sfm(0,shi);
}
write_sfm(3,fen);
}
write_sfm(6,miao);
}
}
|