LCD1602时钟程序,带有闪烁指示位置的。
#include
#define uchar unsigned char
#define uint unsigned int
sbit LCD_EN=P2^2;
sbit LCD_RW=P2^1;
sbit LCD_RS=P2^0;
sbit s1 =P2^5;
sbit s2 =P2^6;
sbit s3 =P2^7;
uchar t0n; //定时器T0中断计数,定时50ms,中断20次为1秒
uchar hour,minute,second; //声明小时,分,秒变量
void delay()
{
uint y;
for(y=0;y<100;y++);
}
void write_com(uchar cmd)
{
LCD_RS=0;
LCD_RW=0;
P0=cmd;
delay();
LCD_EN=1;
LCD_EN=0;
}
void write_dat(uchar dat)
{
LCD_RS=1;
LCD_RW=0;
P0=dat;
delay();
LCD_EN=1;
LCD_EN=0;
}
//初始化先不开闪烁
void init_1602(void)
{
LCD_RW=0;
LCD_RS=0;
LCD_EN=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
write_com(0x80);
delay();
}
//显示时间子程序
void write_time(uchar x,uchar time)
{
write_com(0xc0+x);
write_dat(time/10+48);
write_dat(time%10+48);
write_com(0xc0+x+1);//恢复闪烁位置在个位
}
//显示字符串子程序
void write_str(uchar code *sp)
{
while(*sp!=0)
{
write_dat(*sp);
sp++;
}
}
void main()
{
uchar work; //计时标志位,0:计时,1:调小时,2:调分,3:调秒
hour=10,minute=50;
init_1602();
write_com(0x80+2);
write_str("2018-05-19");
write_com(0xc0+4);
write_str("10:50:00");
TMOD=0x01;
TH0 =0x3C; //单片机晶振频率=12M,定时50ms,时间常数=3CB0
TL0 =0xB0;
IE =0x82; //开中断
TR0 =1; //启动定时器T0
while(1)
{
if(work==0&&t0n>=20) //计时状态
{
t0n=0; //中断20次,1秒到
second++; //秒加1
if(second==60) //到60秒
{
second=0;
minute++; //分加1
if(minute==60) //到60分
{
minute=0;
hour++; //小时加1
if(hour==24)
hour=0;
}
}
write_time(4,hour);
write_time(7,minute);
write_time(10,second);
}
if(s1==0)
{
work++;
if(work>3)
{
work=0;
TR0=1;
t0n=0;
write_com(0x0c);//恢复计时,关光标,关闪烁
}
else
{
TR0=0;
write_com(0x0d); //关光标,开闪烁
write_com(0xc0+2+work*3);//指定闪烁位置
}
while(s1==0);
}
else if(work==1)
{
if(s2==0)
{
hour++;
if(hour>23)
hour=0;
write_time(4,hour);//按键后才显示,闪烁就不会漂移,以下同
while(s2==0);
}
if(s3==0)
{
hour--;
if(hour==0xff)
hour=23;
write_time(4,hour);
while(s3==0);
}
}
else if(work==2)
{
if(s2==0)
{
minute++;
if(minute>59)
minute=0;
write_time(7,minute);
while(s2==0);
}
if(s3==0)
{
minute--;
if(minute==0xff)
minute=59;
write_time(7,minute);
while(s3==0);
}
}
else if(work==3)
{
if(s2==0)
{
second++;
if(second>59)
second=0;
write_time(10,second);
while(s2==0);
}
if(s3==0)
{
second--;
if(second==0xff)
second=59;
write_time(10,second);
while(s3==0);
}
}
}
}
//定时器T0中断服务子程序
void T0_isr() interrupt 1
{
TH0=0x3C; //重写时间常数
TL0=0xB0;
t0n++; //中断次加1
}
仿真图如下,闪烁效果。
效果是啥也不动,光标一直再闪,按键不管用