要达到的效果:
- #include <reg52.h>
- #include <string.h>
- #include <intrins.h>
- typedef unsigned char u8;
- u8 time[]="time:--:--:--";
- u8 dates[]="date:--------(-)";
- sbit RS=P0^7;
- sbit RW=P0^6;
- sbit EN=P0^5;
- sbit RST=P0^0;
- sbit IO=P0^1;
- sbit SCLK=P0^2;
- void delay(u8 t)
- {
- while(t--);
- }
- bit lcd1602_read_status()
- {
- u8 k;
- RW=1;
- delay(2);
- RS=0;
- delay(2);
- EN=1;
- delay(2);
- k=P2;
- delay(2);
- EN=0;
- delay(2);
- return (bit)(k&0x80);
- }
- void lcd1602_write_cmd(u8 cmd)
- {
- while(lcd1602_read_status()!=0);
- RW=0;
- delay(2);
- RS=0;
- delay(2);
- EN=1;
- delay(2);
- P2=cmd;
- delay(2);
- EN=0;
- delay(2);
- }
- void lcd1602_write_dat(u8 dat)
- {
- while(lcd1602_read_status()!=0);
- RW=0;
- delay(2);
- RS=1;
- delay(2);
- EN=1;
- delay(2);
- P2=dat;
- delay(2);
- EN=0;
- delay(2);
- }
- void lcd1602_init()
- {
- lcd1602_write_cmd(0x38);
- lcd1602_write_cmd(0x0c);
- lcd1602_write_cmd(0x01);
- lcd1602_write_cmd(0x04);
- delay(200);
- }
- u8 ds1302_read_data(u8 cmd)
- {
- u8 i,tempbit,tempdata;
- RST=0;
- SCLK=0;
- RST=1;
- for(i=0;i<8;i++)
- {
- if(cmd&0x01)
- IO=1;
- else
- IO=0;
- cmd=cmd>>1;
- SCLK=0;
- }
- for(i=0;i<8;i++)
- {
- if(IO==1)
- tempbit=0x80;
- else
- tempbit=0;
- tempdata=tempdata>>1|tempbit;
- SCLK=1;
- _nop_();
- SCLK=0;
- }
- RST=0;
- return tempdata;
- }
- void ds1302_write_data(u8 cmd,u8 dat)
- {
- u8 i;
- RST=0;
- SCLK=0;
- RST=1;
- for(i=0;i<8;i++)
- {
- if(cmd&0x01)
- IO=1;
- else
- IO=0;
- cmd=cmd>>1;
- SCLK=1;
- _nop_();
- SCLK=0;
- }
- for(i=0;i<8;i++)
- {
- if(dat&0x01)
- IO=1;
- else
- IO=0;
- dat=dat>>1;
- SCLK=1;
- _nop_();
- SCLK=0;
- }
- RST=0;
- }
- void ds1302_init()
- {
- ds1302_write_data(0x8e,0x00);
- ds1302_write_data(0x80,0x24);
- ds1302_write_data(0x82,0x57);
- ds1302_write_data(0x84,0x18);
-
- ds1302_write_data(0x86,0x01);
- ds1302_write_data(0x88,0x12);
- ds1302_write_data(0x8a,0x01);
- ds1302_write_data(0x8c,0x15);
-
- ds1302_write_data(0x8e,0x80);
- }
- void ds1302_read_time()
- {
- u8 s,m,h;
-
- u8 year,month,date,week;
- s=ds1302_read_data(0x81);
- m=ds1302_read_data(0x83);
- h=ds1302_read_data(0x85);
- date=ds1302_read_data(0x87);
- month=ds1302_read_data(0x89);
- week=ds1302_read_data(0x8b);
- year=ds1302_read_data(0x8d);
-
- time[11]=(s>>4)+'0';
- time[12]=(s&0x0f)+'0';
- time[8]=(m>>4)+'0';
- time[9]=(m&0x0f)+'0';
- time[5]=(h>>4)+'0';
- time[6]=(h&0x0f)+'0';
-
- dates[11]=(date>>4)+'0';
- dates[12]=(date&0x0f)+'0';
- dates[8]=(month>>4)+'0';
- dates[9]=(month&0x0f)+'0';
- dates[5]=(year>>4)+'0';
- dates[6]=(year&0x0f)+'0';
- dates[14]=(week&0x0f)+'0';
- }
- void main()
- {
- u8 i;
- delay(200);
- lcd1602_init();
- ds1302_init();
- while(1)
- {
- ds1302_read_time();
- lcd1602_write_cmd(0x80);
- for(i=0;i<strlen(time);i++)
- lcd1602_write_dat(time[i]);
- lcd1602_write_cmd(0xc0);
- for(i=0;i<strlen(dates);i++)
- lcd1602_write_dat(dates[i]);
- }
- }
复制代码 |