资源描述
简单的51单片机时钟程序,可以通过按键来设置时间,按键可以自己更改。
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
#define tt 46080 //设置时间间隔,对应11.0592MHZ的晶振
uchar code table[]="Happy every day!";
uchar code table1[]="00:00:00";
uchar num,hh,mm,ss,t,s1num=0;
sbit en=P3^4;
sbit rs=P3^5;
sbit rw=P3^6;
sbit s1=P3^0;
sbit s2=P3^1;
sbit s3=P3^2;//按键所用的端口
sbit s4=P3^3;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--); //大约是1ms,因为单片机的时钟周期为11.0592mhz。
}
void write_com(uchar com)
{
rs=0; //指令
P0=com; //写指令函数
delay(1);
en=1;
delay(1);
en=0;
}
void write_data(uchar dat)
{
rs=1; //数据
P0=dat; //写指令函数
delay(1);
en=1;
delay(1);
en=0;
}
void init()
{
en=0; //初始时使能为0
rw=0;
write_com(0x38); //显示屏模式设置为1602方案
write_com(0x0c);
write_com(0x06); //显示开关/光标设置
write_com(0x01); //清屏
write_com(0x80); //指针置零
for(num=0;num<16;num++)
write_data(table[num]);
write_com(0xc3);
for(num=0;num<8;num++)
write_data(table1[num]);
}
void dingshi()
{
TMOD=0x01; //确定定时器工作模式(定时模式)
TH0=(65536-tt)/256; //赋初值为tt微秒
TL0=(65536-tt)%256; //不赋值时默认其值是0
EA=1; //开总中断
ET0=1; //开定时器0中断
// IE=0x82; //总线写法
TR0=1; //启动定时器0 总线TCON=0x10;
}
void shuanxin(uchar add,uchar date)
{
uchar shi,ge;
write_com(0xc3+add); //指针指向
shi=date/10;
ge=date%10;
write_data(0x30+shi);
write_data(0x30+ge); //指针自动后移,故不必再写指针位置
}
/***************借助蜂鸣器接地起作用***************/
void keyscan()
{
if(s1==0)
{
delay(5);
if(s1==0)
{
s1num++;
while(!s1);
if(s1num==1)
{
TR0=0; //时钟停止运行
write_com(0xca); //指针指向ss
write_com(0x0f); //光标闪烁
}
if(s1num==2)
{
write_com(0xc7); //指针指向mm
write_com(0x0f);
}
if(s1num==3)
{
write_com(0xc4); //指针指向hh
write_com(0x0f);
}
if(s1num==4)
{
s1num=0;
TR0=1; //时钟运行
write_com(0x0c); //取消闪烁
}
}
}
/***************调节时间****************/
if(s1num!=0) //目的是使s1按下的前提才起作用
{
if(s2==0)
{
delay(5);
if(s2==0)
{
while(!s2); //松手检测,松手后方可向下执行
if(s1num==1)
{
ss++;
if(ss==60)
ss=0;
shuanxin(6,ss);
write_com(0xca);
}
if(s1num==2)
{
mm++;
if(mm==60)
mm=0;
shuanxin(3,mm);
write_com(0xc7);
}
if(s1num==3)
{
hh++;
if(hh==24)
hh=0;
shuanxin(0,hh);
write_com(0xc4);
}
}
}
}
if(s1num!=0) //s1按下的前提才起作用
{
if(s3==0)
{
delay(5);
if(s3==0)
{
while(!s3);
if(s1num==1)
{
ss--;
if(ss==-1)
ss=59;
shuanxin(6,ss);
write_com(0xca);
}
if(s1num==2)
{
mm--;
if(mm==-1)
mm=59;
shuanxin(3,mm);
write_com(0xc7);
}
if(s1num==3)
{
hh--;
if(hh==-1)
hh=23;
shuanxin(0,hh);
write_com(0xc4);
}
}
}
}
if(s1num!=0) //s1按下的前提才起作用
{
if(s4==0)
{
delay(5);
if(s4==0)
{
while(!s4);
if(s1num==1)
{
ss=0;
shuanxin(6,ss);
write_com(0xca);
}
if(s1num==2)
{
mm=0;
shuanxin(3,mm);
write_com(0xc7);
}
if(s1num==3)
{
hh=0;
shuanxin(0,hh);
write_com(0xc4);
}
}
}
}
}
void main()
{
init();
dingshi();
while(1)
{
keyscan();
if(t==20)
{
P1=P1-1;
t=0;
ss++;
if(ss==60)
{
ss=0;
mm++;
if(mm==60)
{
mm=0;
hh++;
if(hh==24)
{
hh=0;
}
shuanxin(0,hh);
}
shuanxin(3,mm);
}
shuanxin(6,ss);
}
}
}
void time0() interrupt 1
{
TH0=(65536-tt)/256; //不赋值时默认其值是0
TL0=(65536-tt)%256;
t++;
}
展开阅读全文