DS1302讀寫程序詳解
void Write1302(unsigned char dat)
{
unsigned char i;
SCLK=0; //拉低SCLK,為脈沖上升沿寫入數(shù)據(jù)做好準(zhǔn)備
delaynus(2); //稍微等待,使硬件做好準(zhǔn)備
for(i=0;i<8;i++) //連續(xù)寫8個(gè)二進(jìn)制位數(shù)據(jù)
{
DATA=dat&0x01; //取出dat的第0位數(shù)據(jù)寫入1302
delaynus(2); //稍微等待,使硬件做好準(zhǔn)備
SCLK=1; //上升沿寫入數(shù)據(jù)
delaynus(2); //稍微等待,使硬件做好準(zhǔn)備
SCLK=0; //重新拉低SCLK,形成脈沖
dat>>=1; //將dat的各數(shù)據(jù)位右移1位,準(zhǔn)備寫入下一個(gè)數(shù)據(jù)位
}
}
void WriteSet1302(unsigned char Cmd,unsigned char dat)
{
RST=0; //禁止數(shù)據(jù)傳遞
SCLK=0; //確保寫數(shù)據(jù)前SCLK被拉低
RST=1; //啟動(dòng)數(shù)據(jù)傳輸
delaynus(2); //稍微等待,使硬件做好準(zhǔn)備
Write1302(Cmd); //寫入命令字
Write1302(dat); //寫數(shù)據(jù)
SCLK=1; //將時(shí)鐘電平置于已知狀態(tài)
RST=0; //禁止數(shù)據(jù)傳遞
}
unsigned char Read1302(void)
{
unsigned char i,dat;
delaynus(2); //稍微等待,使硬件做好準(zhǔn)備
for(i=0;i<8;i++) //連續(xù)讀8個(gè)二進(jìn)制位數(shù)據(jù)
{
dat>>=1; //將dat的各數(shù)據(jù)位右移1位,因?yàn)橄茸x出的是字節(jié)的最低位
if(DATA==1) //如果讀出的數(shù)據(jù)是1
dat|=0x80; //將1取出,寫在dat的最高位
SCLK=1; //將SCLK置于高電平,為下降沿讀出
delaynus(2); //稍微等待
SCLK=0; //拉低SCLK,形成脈沖下降沿
delaynus(2); //稍微等待
}
return dat; //將讀出的數(shù)據(jù)返回
}
unsigned char ReadSet1302(unsigned char Cmd)
{
unsigned char dat;
RST=0; //拉低RST
SCLK=0; //確保寫數(shù)居前SCLK被拉低
RST=1; //啟動(dòng)數(shù)據(jù)傳輸
Write1302(Cmd); //寫入命令字
dat=Read1302(); //讀出數(shù)據(jù)
SCLK=1; //將時(shí)鐘電平置于已知狀態(tài)
RST=0; //禁止數(shù)據(jù)傳遞
return dat; //將讀出的數(shù)據(jù)返回
}