程序:#include <reg51.h>
#include <intrins.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
sbit SCK = P3^5;
sbit SDA = P3^4;
sbit RST = P1^7;
sbit RS = P1^0;
sbit RW = P1^1;
sbit EN = P1^5;
sbit BUSY= P0^7;
#define DS1302_W_ADDR 0x80
#define DS1302_R_ADDR 0x81
uint8 time[7]={00,1,11,14,12,16,12};
void delay(uint16 n)
{
while(n--);
}
/*写一个字节*/
void w_ds1302_byte(uint8 dat)
{
uint8 i;
SCK = 0;
for(i=0;i<8;i++)
{
SDA = dat & 0x01;
SCK =1;
dat>>=1;
SCK =0;
}
}
/*读一个字节*/
uint8 r_ds1302_byte()
{
uint8 i,dat =0;
SCK =0;
for(i=0;i<8;i++)
{
dat>>=1;
if(SDA)
dat |=0x80;
SCK =1;
SCK =0;
}
return dat;
}
void reset_ds1302()
{
RST =0;
SCK =0;
RST =1;
}
void clear_ds1302_WP()
{
reset_ds1302();
RST =1;
w_ds1302_byte(0x8e);
w_ds1302_byte(0);
SDA =0;
RST =0;
}
void set_ds1302_WP()
{
reset_ds1302();
RST =1;
w_ds1302_byte(0x8e);
w_ds1302_byte(0x80);
SDA =0;
RST =0;
}
/*写入DS1302*/
void w_ds1302(uint8 addr,uint8 dat)
{
reset_ds1302();
RST =1;
w_ds1302_byte(addr);
w_ds1302_byte(dat);
SDA =0;
RST =0;
}
/*读出DS1302*/
uint8 r_ds1302(uint8 addr)
{
uint8 temp;
reset_ds1302();
RST =1;
w_ds1302_byte(addr);
temp=r_ds1302_byte();
SDA =0;
RST =0;
return temp;
}
/*设定时钟数据*/
void set_time(uint8 *timedata)
{
uint8 i,tmp;
for(i=0;i<7;i++) //BCD
{
tmp =timedata[i]/10;
timedata[i]=timedata[i]%10;
timedata[i]=timedata[i]+tmp*16;
}
clear_ds1302_WP();
tmp=DS1302_W_ADDR;
for(i=0;i<7;i++)
{
w_ds1302(tmp,timedata[i]);
tmp +=2;
}
set_ds1302_WP();
}
/*读时钟数据*/
void read_time(uint8 *timedata)
{
uint8 i,tmp;
tmp =DS1302_R_ADDR;
for(i=0;i<7;i++)
{
timedata[i] = r_ds1302(tmp);
tmp +=2;
}
}
void wait()
{
P0 =0xff;
do
{
RS =0;
RW =1;
EN =0;
EN =1;
}while(BUSY == 1);
EN =0;
}
void w_dat(uint8 dat)
{
wait();
RS = 1;
RW = 0;
EN = 0;
P0 = dat;
EN = 1;
EN = 0;
}
void w_cmd(uint8 dat)
{
wait();
RS = 0;
RW = 0;
EN = 0;
P0 = dat;
EN = 1;
EN = 0;
}
void Init_LCD1602(void)
{
w_cmd(0x38); // 16*2显示,5*7点阵,8位数据接口
w_cmd(0x0C); // 显示器开、光标开、光标允许闪烁
w_cmd(0x06); // 文字不动,光标自动右移
w_cmd(0x01); // 清屏
}
main()
{
set_time(&time);
Init_LCD1602();
while(1)
{
read_time(&time);
w_cmd(0x80);w_dat(time[6]+'0');
w_cmd(0x82);w_dat('-');
w_cmd(0x83);w_dat(time[4]+'0');
w_cmd(0x85);w_dat('-');
w_cmd(0x86);w_dat(time[3]+'0');
w_cmd(0xc0);w_dat(time[2]+'0');
w_cmd(0xc2);w_dat(':');
w_cmd(0xc3);w_dat(time[1]+'0');
w_cmd(0xc5);w_dat(':');
w_cmd(0xc6);w_dat(time[0]+'0');
delay(10000);
}
}
出来的结果列如:
B-B-D
A:B:E |