按键检测,lcd1602,写地址,写数据
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
sbit dula=P2^6;
sbit wela=P2^7;
sbit rs=P3^5;
sbit lcden=P3^4;//位声明
sbit s1=P3^0;
sbit s2=P3^1;
sbit s3=P3^2;
sbit rd=P3^7;
uchar count,s1num;
char shi,fen,miao;
uchar code table[]=" 2007-7-30 MON";
uchar code table1[]=" 00:00:00"; //初始化
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void write_com(uchar com) //写指令
{
rs=0;
lcden=0;
P0=com;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void write_date(uchar date) //写数据
{
rs=1;
lcden=0;
P0=date;
delay(5);
lcden=1;
delay(5);
lcden=0;
}
void init()
{
uchar num;
dula=0;
wela=0;
lcden=0;
fen=59;
//miao=53;
shi=23;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
for(num=0;num<15;num++)
{
write_date(table[num]);
delay(5);
}
write_com(0x80+40);
for(num=0;num<12;num++)
{
write_date(table1[num]);
delay(5);
}
TMOD=0x01;//定时器0方式1
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
EA=1;//打开总中断
ET0=1;//打开t0中断
TR0=1;//启动t0中断
}
void write_sfm(uchar add,uchar date)
{
uchar shi,ge;
shi=date/10;
ge=date%10;
write_com(0x80+0x40+add);//写指令,第二行+add
write_date(0x30+shi);//字库
write_date(0x30+ge);//字库
}
void keyscan()//键盘扫描
{
rd=0;//矩阵键盘作为独立键盘,公共端=0
if(s1==0)
{
delay(5);
if(s1==0)
{
s1num++;
while(!s1);//松手检测
if(s1num==1)
{
TR0=0;
write_com(0x80+0x40+10);//写秒地址
write_com(0x0f);//光标闪烁
}
if(s1num==2)
{
write_com(0x80+0x40+7);//写分地址
}
if(s1num==3)
{
write_com(0x80+0x40+4);//写时地址
}
if(s1num==4)
{
s1num=0;//清零
write_com(0x0c);//开显示光标
TR0=1;//启动定时器
}
}
}
if(s1num!=0)
{
if(s2==0)
{
delay(5);
if(s2==0)
{
while(!s2);//松手检测
if(s1num==1)//秒位
{
miao++;
if(miao==60)
miao=0;
write_sfm(10,miao); //在秒的位置上写数据
write_com(0x80+0x40+10);//写数据的地址
}
if(s1num==2)
{
fen++;
if(fen==60)
fen=0;
write_sfm(7,fen);
write_com(0x80+0x40+7);
}
if(s1num==3)
{
shi++;
if(shi==24)
shi=0;
write_sfm(4,shi);
write_com(0x80+0x40+4);
}
}
}
if(s3==0)
{
delay(5);
if(s3==0)
{
while(!s3);
if(s1num==1)
{
/*if(miao==0)
{
miao=59;
write_sfm(10,miao);
write_com(0x80+0x40+10);
}*/
miao--;
if(miao==-1)//秒是char型,减到0的时候在1602显示,再减1,为-1.秒显示59
miao=59;
write_sfm(10,miao);
write_com(0x80+0x40+10);
}
if(s1num==2)
{
fen--;
if(fen==-1)
fen=59;
write_sfm(7,fen);
write_com(0x80+0x40+7);
}
if(s1num==3)
{
shi--;
if(shi==-1)
shi=23;
write_sfm(4,shi);
write_com(0x80+0x40+4);
}
}
}
}
}
void main()
{
init();//初始化
while(1)
{
keyscan();
}
}
void timer0() interrupt 1//定时器0,方式1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
count++;
if(count==20)
{
count=0;
miao++;
if(miao==60)
{
miao=0;
fen++;
if(fen==60)
{
fen=0;
shi++;
if(shi==24)
{
shi=0;
}
write_sfm(4,shi);
}
write_sfm(7,fen);
}
write_sfm(10,miao);
}
}