//打开DS1302
void TimeSpiOpen(void)
{
TIMECLK = 0;
TIMERST = 0;//禁止DS1302
TIMEIO = 1;//释放数据总线
TIMERST = 1;//使能DS1302
}
//关闭DS1302
void TimeSpiClose(void)
{
TIMERST = 0;//禁止DS1302
TIMEIO = 1;//释放数据总线
TIMECLK = 1;
}
//读写DS1302
unsigned char TimeSpiReadWrite(unsigned char val)
{
unsigned char i;
ACC = val;//取8位数据
for (i = 8;i > 0; i--)
{
TIMECLK = 0;//时钟下降沿输入数据(DS1302读)
_nop_();//延时
CY = TIMEIO;//接收串行数据到CY
_rrca_();//右移一位数据到CY(先存后取)
TIMEIO = CY;//发送串行数据
TIMECLK = 1;//时钟上升沿打入数据(DS1302写)
TIMEIO = 1;//释放数据总线
}
val = ACC;
return val;
}
//读DS1302字节
unsigned char TimeByteRead(unsigned char address)
{
TimeSpiOpen();//打开DS1302
TimeSpiReadWrite(address);//写入DS1302命令
address = TimeSpiReadWrite(0xff);//读入DS1302数据
TimeSpiClose();//关闭DS1302
return address;//返回数据
}
//读DS1302RAM字节
unsigned char TimeRamByteRead(unsigned char address)
{
TimeSpiOpen();//打开DS1302
TimeSpiReadWrite((address << 1) | 0xc1);//写入DS1302命令
address = TimeSpiReadWrite(0xff);//读入DS1302数据
TimeSpiClose();//关闭DS1302
return address;//返回数据
}
//写DS1302字节
void TimeByteWrite(unsigned char address, unsigned char val)
{
TimeSpiOpen();//打开DS1302
TimeSpiReadWrite(address);//写地址
TimeSpiReadWrite(val);//写数据
TimeSpiClose();//关闭DS1302
}
//写DS1302字节
void TimeRamByteWrite(unsigned char address, unsigned char val)
{
TimeSpiOpen();//打开DS1302
TimeSpiReadWrite((address << 1) | 0xc0);//写地址
TimeSpiReadWrite(val);//写数据
TimeSpiClose();//关闭DS1302
}
//使能DS1302写保护
void TimeWriteEnable(void)
{
TimeByteWrite(timewriteregall, timewriteseg);//使能DS1302写保护
}
//开放DS1302写保护
void TimeWrieDisbale(void)
{
TimeByteWrite(timewriteregall, 0);//开放DS1302写保护
}
//DS1302工作开始
void TimeWorkStart(void)
{
unsigned char val;
val = TimeByteRead(timereadseg);//读秒数据
val &= 0x7f;//打开晶振
TimeWrieDisbale();//开放DS1302写保护
TimeByteWrite(timewriteseg, val);//打开晶振
TimeByteWrite(tricklewrite, 0xa5);//打开充电二极管
TimeWriteEnable();//使能DS1302写保护
}