#include<reg52.h>
#include<LCD.h>
#include<key_scan.h>
#include<ds1302.h>
#include <intrins.h>
sbit speaker=P3^4;
unsigned char time[6]={0x00,0x20,0x10,0x0f,0x04,0x0a};//读时间的续冲,初始值是写入的时间,
unsigned char time_read[6]={0x00,0x00,0x00,0x00,0x00,0x00};
code unsigned char addr_write[6]={0x80,0x82,0x84,0x86,0x88,0x8c};
code unsigned char addr_read[6]={0x81,0x83,0x85,0x87,0x89,0x8d};
unsigned char display[12]={0,0,0,0,0,0,0,0,0,0,0,0};
unsigned char flag=0,buffer,j,addr=5,erro=0,cnt=0,clk_00=0;
void LCD_display();
void read_time();
void clock_init();
void bcd_to_hex();
void ser_init();
void clock_come();
void timer_init();
unsigned char hex_to_bcd(unsigned char kk);
main()
{ timer_init();
ser_init();
LCD_init();
clock_init();
while(1)
{
if(flag)
{
ES=0;
SBUF=buffer;
while(TI==0);
TI=0;
ES=1;
flag=0;
}
LCD_write(1,0,addr+0x30);
read_time();
clock_come();
bcd_to_hex();
LCD_display();
}
}
void clk_isr() interrupt 1
{
speaker=~speaker;
TH1=(65536-10000)/256;
TL1=(65536-10000)%256;
cnt++;
if(cnt==10)
{ clk_00=0; TR0=0;}
}
void ser_isr() interrupt 4
{ RI=0;
buffer=SBUF;
buffer=hex_to_bcd(buffer);
write_DS1302_reg(addr_write[addr],buffer);
addr--;
if(addr==0)
addr=5;
P0=buffer;
flag=1;
}
void timer_init()
{ TMOD=0x01;
TH1=(65536-10000)/256;
TL1=(65536-10000)%256;
ET0=1;
}
void clock_come()
{
if(clk_00==1)
{
TR0=1;
}
}
unsigned char hex_to_bcd(unsigned char kk)
{ unsigned char jj;
jj=kk/10;
kk=kk%10;
kk=kk+jj*16;
return kk;
}
void ser_init()
{
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
TR1=1;
SM0=0;
SM1=1;
REN=1;
EA=1;
ES=1;
}
void clock_init()
{
unsigned char i=0,tmp;
for(i=0;i<6;i++)
{
tmp=time[i]/10;
time[i]=time[i]%10;
time[i]=time[i]+tmp*16;
}
write_DS1302_reg(0x8e,0x00);
for(i=0;i<6;i++)
{
write_DS1302_reg(addr_write[i],time[i]);
}
//write_DS1302_reg(0x8E,0x80);
}
void read_time()
{
unsigned char i=0;
for(i=0;i<6;i++)
{
time_read[i]=Read_Ds1302(addr_read[i]);
}
if(time_read[0]==0&&time_read[1]==0)
clk_00=1;
}
void bcd_to_hex()
{
display[11]=time_read[0]&0x0f;
display[10]=time_read[0]/16;
display[9]=time_read[1]&0x0f;
display[8]=time_read[1]/16;
display[7]=time_read[2]&0x0f;
display[6]=time_read[2]/16;
display[5]=time_read[3]&0x0f;
display[4]=time_read[3]/16;
display[3]=time_read[4]&0x0f;
display[2]=time_read[4]/16;
display[1]=time_read[5]&0x0f;
display[0]=time_read[5]/16;
}
void LCD_display()
{
LCD_write(2,9,display[11]+0x30);//秒个位
LCD_write(2,8,display[10]+0x30);
LCD_write(2,7,0x3a); //显示:
LCD_write(2,6,display[9]+0x30);//分个位
LCD_write(2,5,display[8]+0x30);
LCD_write(2,4,0x3a); //显示:
LCD_write(2,3,display[7]+0x30);//时个位
LCD_write(2,2,display[6]+0x30);
LCD_write(1,9,display[5]+0x30);//日个位
LCD_write(1,8,display[4]+0x30);
LCD_write(1,7,0x2d); //显示-
LCD_write(1,6,display[3]+0x30);//月个位
LCD_write(1,5,display[2]+0x30);
LCD_write(1,4,0x2d); //显示-
LCD_write(1,3,display[1]+0x30);//年个位
LCD_write(1,2,display[0]+0x30);
}