27,374
社区成员
发帖
与我相关
我的任务
分享
/*
* DS1302 test
*
*/
#include <reg52.h>
#include <intrins.h>
sbit SCK = P3^5; //时钟
sbit SDA = P3^4; //数据
sbit RST = P1^7; //DS1302复位(片选)
unsigned char timedata[7]={50,59,23,15,8,7,10};//秒分时日月周年10-08-15 12:00:00
unsigned char write_rtc_address[7]={0x80,0x82,0x84,0x86,0x88,0x8a,0x8c}; //秒分时日月周年 最低位读写位
unsigned char read_rtc_address[7]={0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};
/**
* 写一个字节
*/
void Write_Ds1302_Byte(unsigned char temp)
{
unsigned char i;
for (i=0;i<8;i++)
{
SCK = 0;
SDA = temp & 0x01;
temp >>= 1;
SCK = 1;
}
}
/**
* 写入DS1302
*/
void Write_Ds1302(unsigned char address, unsigned char dat)
{
RST=0;
_nop_();
SCK=0;
_nop_();
RST=1;
_nop_();
Write_Ds1302_Byte(address);
Write_Ds1302_Byte(dat);
RST=0;
}
/**
* 读出DS1302数据
*/
unsigned char Read_Ds1302 ( unsigned char address )
{
unsigned char i,temp=0;
RST=0;
_nop_();
_nop_();
SCK=0;
_nop_();
_nop_();
RST=1;
_nop_();
_nop_();
Write_Ds1302_Byte(address);
for (i=0;i<8;i++) //循环8次 读取数据
{
if (SDA)
temp |= 0x80; //每次传输低字节
SCK=0;
temp>>=1; //右移一位
_nop_();
_nop_();
_nop_();
SCK=1;
}
RST=0;
_nop_(); //以下为DS1302复位的稳定时间
_nop_();
_nop_();
SCK=0;
_nop_();
_nop_();
_nop_();
_nop_();
SCK=1;
_nop_();
_nop_();
SDA=0;
_nop_();
_nop_();
SDA=1;
_nop_();
_nop_();
return (temp); //返回
}
/**
* 读时钟数据
*/
void Read_RTC(void)
{
unsigned char i, *p;
p = read_rtc_address;
for (i=0; i<7; i++) //分7次读取 秒分时日月周年
{
timedata[i] = Read_Ds1302(*p);
p++;
}
}
/**
* 设定时钟数据
*/
void Set_RTC(void)
{
unsigned char i,*p,tmp;
for (i=0; i<7; i++) // 转化为BCD格式
{
tmp = timedata[i] / 10;
timedata[i] = timedata[i] % 10;
timedata[i] = timedata[i] + tmp*16;
}
Write_Ds1302(0x8E,0x00);
p = write_rtc_address; //传地址
for (i=0; i<7; i++) //7次写入 秒分时日月周年
{
Write_Ds1302(*p,timedata[i]);
p++;
}
Write_Ds1302(0x8E,0x80);
}