//打開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寫保護
}





