sbit sck=P3^6; sbit sda=P3^4; sbit rst=P3^5;unsigned char cycle=0x7f; unsigned int flag;
unsigned char temprary[8];
unsigned char tim[7]={55,59,23,2,2,2,2};
unsigned char code write_add[7]={0x80,0x82,0x84,0x86,0x88,0x8a,0x8c}; unsigned char code read_add[7]={0x81,0x83,0x85,0x87,0x,0x8b,0x8d};
unsigned char code table[11]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x40};
void delay() //延时函数 { _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); }
void write_byte(unsigned char temp) //写入字节 {
unsigned char i;
for (i=0;i<8;i++) //循环8次 写入数据 {
sck=0; _nop_(); sda=temp&0x01; //每次传输低字节 temp=temp>>1; //右移一位 _nop_(); sck=1; delay(); } }
void write_1302 (unsigned char address,unsigned char dat) //写入ds1302 { rst=0; //只有在rst为零的前提下,sck为零才不是数据,否则会勿操作 _nop_(); sck=0; delay(); rst=1; delay(); write_byte(address); write_byte(dat); rst=0; }
unsigned char read_1302(unsigned char address) //读出ds1302 { unsigned char i,temp=0; rst=0; delay(); sck=0; delay(); rst=1; delay(); write_byte(address); delay(); for(i=0;i<8;i++) { sck=1; if(sda) temp=temp|0x80;//最高位为秒,变成最低位 temp=temp>>1; delay(); sck=0; } delay(); rst=0; delay(); delay(); delay(); return temp; }
void set_rtc() //设定日历 { unsigned char *p,temp,i; for(i=0;i<7;i++) { temp=tim[i]/10; tim[i]=tim[i]%10; tim[i]=temp*16+tim[i]; }
write_1302(0x8e,0x00); p=write_add; for(i=0;i<7;i++) { write_1302(*p,tim[i]); p++; } write_1302(0x8e,0x80); }
void read_rtc() { unsigned char *p,i; p=read_add; for(i=0;i<7;i++) { tim[i]=read_1302(*p); p++; } }
void main() { unsigned char i; TMOD=0x01; TH0=0XFC; TL0=24; EA=1; ET0=1; TR0=1; set_rtc();
//读取日历 while(1) { if(flag==500) { flag=0; read_rtc(); temprary[0]=tim[2]/16; temprary[1]=tim[2]&0x0f; temprary[2]= 10; temprary[3]=tim[1]/16; temprary[4]=tim[1]&0x0f; temprary[5]= 10; temprary[6]=tim[0]/16; temprary[7]=tim[0]&0x0f; } P0=table[temprary[i]]; P2=cycle; delay(); delay(); P2=0xff; cycle=_cror_(cycle,1); i++; if(i==8) i=0; } }
void timer() interrupt 1 { TH0=0XFC; TL0=0x24; flag++; }