因為在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()函數即可,非常簡單。