因为在ds1302.c文件中包含了写ds1302(51向ds1302写数据)和读ds1302(51从ds1302读数据)的两个函数,我们根据文件中提供的函数来写读取时间和设置时间的函数即可
ds1302.c文件源码如下,需要的同学可以参考一下:
#include <reg52.h>
#include <intrins.h>
#define DecToBCD(dec) (dec/10*16)+(dec%10)
#define BCDToDec(bcd) (bcd/16*10)+(bcd%16)
sbit SCK=P1^7;
sbit SDA=P2^3;
sbit RST = P1^3; 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); 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_();return (temp);
}
程序解释:
1.ds1302的写保护操作:当WP位(寄存器的第七位)为1时,写保护功能开启,禁止对任何寄存器进行写操作,防止误改寄存器中的时间,日期或者其他数据。如果要对时钟进行写操作,需要将WP位设置为0,关闭写保护功能
2.BCD码:用4位二进制数来表示1位十进制数中的0~9的这10个数码
十进制转换为BCD码宏定义:
#define DecToBCD(dec) (dec/10 *16) +(dec%10)
BCD码转换为十进制宏定义:
#define BCDToDec(bcd) (bcd/16* 10)+(bcd % 16)
用处:1.我们在读取时间的时候,因为Read_DS1302_Byte()函数返回的是BCD码,所以在读取时需要转换为十进制
2.同样的,在设置时间时,我们也需要将十进制转换为BCD码
读取时间的流程:
直接调用读取ds1302的函数
ds1302读取函数如下:
可以看到,读到时间数据后,需要用BCDToDec宏定义转换为十进制
unsigned char hour,minute,second;
void DS1302_process()
{second=BCDToDec(Read_Ds1302_Byte(0x81));minute=BCDToDec(Read_Ds1302_Byte(0x83));hour=BCDToDec(Read_Ds1302_Byte(0x85));
}
设置时间的流程:
1.关闭写保护
2.写入时钟数据
3.打开写保护
时钟设置函数如下:
注意:函数需要使用的话,初始化一次就可以了,不需要一直执行。同样将时间数据传给Write_Ds1302_Byte()函数需要使用宏定义进行转换,否则程序不能正常运行
void Clock_Set(unsigned char hour, unsigned char minute,unsigned char second)
{Write_Ds1302_Byte(0x8e,0x00); //关闭写保护Write_Ds1302_Byte(0x80,DecToBCD(second));Write_Ds1302_Byte(0x82,DecToBCD(minute));Write_Ds1302_Byte(0x84,DecToBCD(hour));Write_Ds1302_Byte(0x8e,0x80); //打开写保护
}
程序示例:(如将初始时间设置为23时59分55秒)
void Clock_Set(unsigned char hour, unsigned char minute,unsigned char second)
{Write_Ds1302_Byte(0x8e,0x00); //关闭写保护Write_Ds1302_Byte(0x80,DecToBCD(second));Write_Ds1302_Byte(0x82,DecToBCD(minute));Write_Ds1302_Byte(0x84,DecToBCD(hour));Write_Ds1302_Byte(0x8e,0x80); //打开写保护
}
int main()
{Clock_Set(23,59,55);
}
直接将函数放到main()函数即可,非常简单。