根据DS1302的芯片手册,我们可以看出来写入时,分,秒的地址分别是:0x84,0x82,0x80;读取时分秒的地址分别是:0x85,0x83,0x81;其他的可参考下图。
*值得注意的是,进行写错操作时,应该当将0x8e的BIT7(第七位)置0,写入完毕时,置1。
根据官方提供的底层代码进行编程:
/*
程序说明: DS1302驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台 8051,12MHz
日 期: 2011-8-9
*/
#include <STC15F2K60S2.H>
#include <intrins.h>
sbit SCK=P1^7;
sbit SDA=P2^3;
sbit RST = P1^3; // DS1302复位
void Write_Ds1302(unsigned char temp)
{
unsigned char i;
for (i=0;i<8;i++)
{
SCK=0;
SDA=temp&0x01;
temp>>=1;
SCK=1;
}
}
void Write_Ds1302_Byte( unsigned char address,unsigned char dat )
{
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
dat = dat / 10 * 16 + dat % 10; //需自己添加此段代码
Write_Ds1302(dat);
RST=0;
}
unsigned char Read_Ds1302_Byte ( unsigned char address )
{
unsigned char i,temp=0x00;
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
for (i=0;i<8;i++)
{
SCK=0;
temp>>=1;
if(SDA)
temp|=0x80;
SCK=1;
}
RST=0; _nop_();
SCK=0; _nop_();
SCK=1; _nop_();
SDA=0; _nop_();
SDA=1; _nop_();
temp = temp / 16 * 10 + temp % 16; //需自己添加此段代码
return (temp);
}
//*******以下是比赛时需自己编写的部分*********
void Set_Time_SFM(unsigned char S,unsigned char F,unsigned char M)
{
Write_Ds1302_Byte(0X8E,0X00);
Write_Ds1302_Byte(0X84,S);
Write_Ds1302_Byte(0X82,F);
Write_Ds1302_Byte(0X80,M);
Write_Ds1302_Byte(0X8E,0X80);
}
由于写入时,我们写入的是十进制数,需要进行转码。
在ds1302.c中的“Write_Ds1302_Byte()”函数中增加BCD转码在“Write_Ds1302(dat);”
前添加 (dat = dat / 10 * 16 + dat % 10)即可。
相同,读取时间时,也要相应的进行转码。
在ds1302.c中的“Read_Ds1302_Byte()“函数中增加BCD转码在“return (temp); “前添加
(temp = temp / 16 * 10 + temp % 16)即可。
读取时间,对应相对地址即可。读取时分秒的地址分别是:0x85,0x83,0x81;
unsigned char S,F,M;
void Read_Time()
{
S = Read_Ds1302_Byte(0X85);
F = Read_Ds1302_Byte(0X83);
M = Read_Ds1302_Byte(0X81);
}