在德飞莱的板子上,实时时钟应用的是DS1302芯片。
时钟外接晶振,可以算出最准确的一秒钟。
WP置低,写入;置高,读出
#define ds1302_sec_add 0x80
#define ds1302_min_add 0x82
#define ds1302_hr_add 0x84
#define ds1302_date_add 0x86
#define ds1302_month_add 0x88
#define ds1302_day_add 0x8a
#define ds1302_year_add 0x8c
#define ds1302_control_add 0x8e
#define ds1302_charger_add 0x90
#define ds1302_clkburst_add 0xbe
sbit SCK = P2^2;
sbit IO = P2^3;
sbit RST = P2^4;
void ds1302_write_byte(unsigned char addr, unsigned char byte)
{
unsigned char i;
addr = addr & 0xfe;
SCK = 0;
RST = 0;
RST = 1;
for(i = 0; i < 8; i++)
{
IO = addr & 0x01;
SCK = 0;
SCK = 1;
addr >>= 1;
}
for(i = 0; i < 8; i++)
{
IO = byte & 0x01;
SCK = 0;
SCK = 1;
byte >>= 1;
}
}
unsigned char ds1302_read_byte(unsigned char addr)
{
unsigned char i;
unsigned char temp = 0;
addr = addr & 0xfe;
SCK = 0;
RST = 0;
RST = 1;
addr =addr + 1;
for(i = 0; i < 8; i++)
{
IO = addr & 0x01;
SCK = 0;
SCK = 1;
addr >>= 1;
}
for(i = 0; i < 8; i++)
{
SCK = 1;
SCK = 0;
temp >>= 1;
if(IO)
{
temp += 0x80;
}
}
RST = 0;
return temp;
}
void ds1302_write_time()
{
unsigned char temp;
unsigned char temp1;
unsigned char i;
for(i = 0; i < 7; i++)
{
temp = timebuf[i]/10;
temp1 = timebuf[i]%10;
disbuf[i] = (temp << 4) | temp1;
}
ds1302_write_byte(ds1302_control_add, 0x00);
ds1302_write_byte(ds1302_hr_add, disbuf[0]);
ds1302_write_byte(ds1302_min_add, disbuf[1]);
ds1302_write_byte(ds1302_sec_add, disbuf[2]);
ds1302_write_byte(ds1302_year_add, disbuf[3]);
ds1302_write_byte(ds1302_month_add, disbuf[4]);
ds1302_write_byte(ds1302_date_add, disbuf[5]);
ds1302_write_byte(ds1302_day_add, disbuf[6]);
ds1302_write_byte(ds1302_control_add, 0x80);
}
void ds1302_read_time()
{
unsigned char temp;
unsigned char temp1;
unsigned char i;
readbuf[0] = ds1302_read_byte(ds1302_hr_add);
readbuf[1] = ds1302_read_byte(ds1302_min_add);
readbuf[2] = ds1302_read_byte(ds1302_sec_add);
readbuf[3] = ds1302_read_byte(ds1302_year_add);
readbuf[4] = ds1302_read_byte(ds1302_month_add);
readbuf[5] = ds1302_read_byte(ds1302_date_add);
readbuf[6] = ds1302_read_byte(ds1302_day_add);
for(i = 0; i < 7; i++)
{
temp = readbuf[i]>>4;
temp1 = readbuf[i]&0x0f;
disbuf[i] = temp*10+temp1;
}
}