#include<reg51.h> //包含单片机寄存器的头文件
#include<intrins.h> //包含_nop_()函数定义的头文件
#define uchar unsigned char
#define uint unsigned int
sbit SRT=P3^5;
sbit IO=P3^4;
sbit SCK=P3^6;
uchar code table[]={0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71};
uchar miao,fen,shi,tian,yue,zhou,nian;
uchar read_DS1302(uchar addr)//读DS1302子程序;
{
uchar dat,i,temp,j;
SRT=0;
SCK=0;
IO=0;//必须先置低,否则易出错;
SRT=1;
for(i=0;i<8;i++)//写地址(要读数据的地址);
{
SCK=0;
dat=addr&0x01;
IO=dat;
addr=addr>>1;
SCK=1;
_nop_();
}
// IO=1;//释放总线,以便接下来的读操作,
//否则读出的数据永远都是0x00,
//但因addr最高总是1,在传送最高位时,即IO=dat=1,
//所以此句可以不要;
for(j=0;j<8;j++)//读数据;
{
SCK=0;
temp>>=1;
if(IO)
temp=temp|0x80;
SCK=1;
_nop_();
}
SCK=0;//必须严格按时序拉低,不然出错;
SRT=0;
IO=1;//必须释放总线;
return temp;
}
void write_DS1302(uchar add,uchar date)//写DS1302子程序;
{
uchar dat1,i,dat2,j;
SRT=0;
SCK=0;
IO=0;
SRT=1;
_nop_();
for(i=0;i<8;i++)//先写地址;
{
SCK=0;
dat1=add&0x01;
add=add>>1;
IO=dat1;
SCK=1;
_nop_();
}
for(j=0;j<8;j++)//再写数据;
{
SCK=0;
dat2=date&0x01;
date=date>>1;
IO=dat2;
SCK=1;
_nop_();
}
SCK=0;
SRT=0;
IO=1;
}
void delay(uint n)
{
while(n--);
}
void display()
{
uchar miao1,miao2,fen1,fen2,shi1,shi2;
P0=0xff;
P1=0x00;
miao1=miao&0x0f;
miao2=miao&0xf0;
miao2=miao2>>4;
fen1=fen&0x0f;
fen2=fen&0xf0;
fen2=fen2>>4;
shi1=shi&0x0f;
shi2=shi&0xf0;
shi2=shi2>>4;
P1=table[miao1];
P0=0x7f;
delay(200);
P1=table[miao2];
P0=0xbf;
delay(200);
P1=0x40;
P0=0xdf;
delay(200);
P1=table[fen1];
P0=0xef;
delay(200);
P1=table[fen2];
P0=0xf7;
delay(200);
P1=0x40;
P0=0xfb;
delay(200);
P1=table[shi1];
P0=0xfd;
delay(200);
P1=table[shi2];
P0=0xfe;
delay(200);
}
void main()
{
//设置日期时间(2013/09/11,21:03:00,星期3);
while(1)
{
miao=read_DS1302(0x81);
fen=read_DS1302(0x83);
shi=read_DS1302(0x85);
tian=read_DS1302(0x87);
yue=read_DS1302(0x89);
zhou=read_DS1302(0x8b);
nian=read_DS1302(0x8d);//读取DS18B20数据;
P2=miao;
display();
}
}