DS1302 自用代码 STC32G12K128 测没有问题
#define SCLK P22 //DS-S
#define DSIO P21 //DS-I
#define RST P20 //DS-R
unsigned char READ_RTC_ADDR[7] = {0x81, 0x83, 0x85, 0x87, 0x89, 0x8b, 0x8d}; //读取地址
unsigned char WRITE_RTC_ADDR[7] = {0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c}; //写入地址
unsigned char TIME[7] = {0, 0, 0, 0, 0, 0, 0};
unsigned char Year=0, Month=0,day=0, Week=0, Hour=0, Minute=0, Second=0;//年月日周时分秒
unsigned char Ds1302Read(unsigned char addr)
{
unsigned char n,dat,dat1;
RST = 1;
_nop_();
for(n=0; n<8; n++)
{
DSIO = addr & 0x01;
addr >>= 1;
SCLK = 1;
_nop_();
SCLK = 0;
_nop_();
}
_nop_();
for(n=0; n<8; n++)
{
dat1 = DSIO;
dat = (dat>>1) | (dat1<<7);
SCLK = 1;
_nop_();
SCLK = 0;
_nop_();
}
RST = 0;
_nop_();
DSIO = 0;
_nop_();
return dat;
}
void Ds1302Write(unsigned char addr, unsigned char dat)
{
unsigned char n;
RST = 1;
_nop_();
for (n=0; n<8; n++)
{
DSIO = addr & 0x01;
addr >>= 1;
SCLK = 1;
_nop_();
SCLK = 0;
_nop_();
}
for (n=0; n<8; n++)
{
DSIO = dat & 0x01;
dat >>= 1;
SCLK = 1;
_nop_();
SCLK = 0;
_nop_();
}
RST = 0;
_nop_();
}
void Ds1302Init()
{
unsigned char n;
Ds1302Write(0x8E,0X00);
for (n=0; n<7; n++)
{
Ds1302Write(WRITE_RTC_ADDR[n],TIME[n]);
}
Ds1302Write(0x8E,0x80);
}
//========================================================================
// 读取时间
// ***********************************************************************
//========================================================================
void Ds1302ReadTime()
{
unsigned char n;
unsigned char dd[10]="";
for (n=0; n<7; n++)
{
TIME[n] = Ds1302Read(READ_RTC_ADDR[n]);
}
for (n=0; n<7; n++)
{
TIME[n] = Ds1302Read(READ_RTC_ADDR[n]);
}
Year=BCD_DEC(TIME[6]);
Week=BCD_DEC(TIME[5]);
Month=BCD_DEC(TIME[4]);
day=BCD_DEC(TIME[3]);
Hour=BCD_DEC(TIME[2]);
Minute=BCD_DEC(TIME[1]);
Second=BCD_DEC(TIME[0]);
}
unsigned char *WEEK_ZH(unsigned char aa)
{
static unsigned char dd[10]="";
if(aa==1) strcpy(dd,"一") ;
if(aa==2) strcpy(dd,"二") ;
if(aa==3) strcpy(dd,"三\xfd") ;
if(aa==4) strcpy(dd,"四") ;
if(aa==5) strcpy(dd,"五") ;
if(aa==6) strcpy(dd,"六") ;
if(aa==7) strcpy(dd,"日") ;
return dd;
} |