LCD1602顯示簡單時鐘程序
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar code table[]=" 2009/04/29 THU";
uchar code table1[]="TIME:00-00-00";
sbit lcd_rs=P3^0;
sbit lcd_rw=P3^1;
sbit lcd_en=P3^2;
sbit k1=P1^0;
sbit k2=P1^1;
sbit k3=P1^2;
sbit k4=P1^3;
uchar count,k1num;
char shi,fen,miao;
void delay(uchar z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void write_com(uchar com)
{
lcd_rs=0;
lcd_en=0;
lcd_rw=0;
P0=com;
delay(5);
lcd_en=1;
delay(5);
lcd_en=0;
}
void write_data(uchar date)
{
lcd_rs=1;
lcd_en=0;
lcd_rw=0;
P0=date;
delay(5);
lcd_en=1;
delay(5);
lcd_en=0;
}
void write_fsm(uchar add,uchar date)
{
uchar shi,ge;
shi=date/10;
ge=date%10;
write_com(0x80+0x40+add);
write_data(0x30+shi);
write_data(0x30+ge);
}
void jiaxian()
{
if(k1num!=0)
{
if(k2==0)
{
delay(5);
if(k2==0)
{
while(!k2);
if(k1num==1)
{
miao++;
if(miao==60)
miao=0;
write_fsm(11,miao);
write_com(0x80+0x40+11);
}
if(k1num==2)
{
fen++;
if(fen==60)
fen=0;
write_fsm(8,fen);
write_com(0x80+0x40+8);
}
if(k1num==3)
{
shi++;
if(shi==24)
shi=0;
write_fsm(5,shi);
write_com(0x80+0x40+5);
}
}
}
}
}
void jianxian()
{
if(k1num!=0)
{
if(k3==0)
delay(5);
if(k3==0)
{
while(!k3);
if(k1num==1)
{
miao--;
if(miao==-1)
miao=59;
write_fsm(11,miao);
write_com(0x80+0x40+11);
}
if(k1num==2)
{
fen--;
if(fen==-1)
fen=59;
write_fsm(8,fen);
write_com(0x80+0x40+8);
}
if(k1num==3)
{
shi--;
if(shi==-1)
shi=23;
write_fsm(5,shi);
write_com(0x80+0x40+5);
}
}
}
}
void kbscan()
{
if(k1==0)
{
delay(5);
if(k1==0)
{
while(!k1);
k1num++;
TR0=0;
if(k1num==1)
{
write_com(0x80+0x40+11);
write_com(0x0f);
}
if(k1num==2)
{
write_com(0x80+0x40+8);
}
if(k1num==3)
{
write_com(0x80+0x40+5);
}
if(k1num==4)
{
k1num=0;
write_com(0x0c);
TR0=1;
}
}
}
jiaxian();
jianxian();
}
void init()
{
uchar num;
lcd_rw=0;
lcd_en=0;
shi=0;
fen=0;
miao=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
write_com(0x80);
for(num=0;num<15;num++)
{
write_data(table[num]);
delay(5);
}
write_com(0x80+0x40);
for(num=0;num<13;num++)
{
write_data(table1[num]);
delay(5);
}
TMOD=0x01;
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
EA=1;
ET0=1;
TR0=1;
}
void main()
{
init();
while(1)
{
kbscan();
if(count==18)
{
count=0;
miao++;
if(miao==60)
{
miao=0;
fen++;
if(fen==60)
{
fen=0;
shi++;
if(shi==24)
{
shi=0;
}
write_fsm(5,shi);
}
write_fsm(8,fen);
}
write_fsm(11,miao);
}
}
}
void time0() interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
count++;
}