51单片机对DS1302(实时时钟芯片)的仿真
-
仿真效果 -
源代码
#include <reg51.h>
#include <intrins.h>
sbit RS=P3^0;
sbit RW=P3^1;
sbit E=P3^2;
sbit T_RST=P3^3;
sbit T_CLK=P3^4;
sbit T_IO=P3^5;
unsigned char datechar[]={"DATE:"};
unsigned char timechar[]={"TIME:"};
unsigned char datebuffer[10]={0x32,0x30,0,0,0x2d,0,0,0x2d,0,0};
unsigned char timebuffer[8]={0,0,0x3a,0,0,0x3a,0,0};
unsigned char weekbuffer={0x30};
void WriteB(unsigned char dat)
{
unsigned char i;
for(i=8; i>0; i--)
{
T_IO=dat&0x01;
T_CLK = 1;
T_CLK = 0;
dat = dat >> 1;
}
}
unsigned char ReadB(void)
{
unsigned char i,readdat=0;
for(i=8; i>0; i--)
{
readdat=readdat>>1;
if(T_IO)
{
readdat|=0x80;
}
T_CLK = 1;
T_CLK = 0;
}
return(readdat);
}
void W1302(unsigned char address,unsigned char dat)
{
T_RST = 0;
T_CLK = 0;
_nop_();
_nop_();
T_RST = 1;
_nop_();
_nop_();
WriteB(address);
WriteB(dat);
T_CLK = 1;
T_RST =0;
}
unsigned char R1302(unsigned char address)
{
unsigned char dat=0;
T_RST = 0;
T_CLK = 0;
T_RST = 1;
WriteB(address);
dat = ReadB();
T_CLK = 1;
T_RST =0;
return(dat);
}
void delay(unsigned int n)
{
unsigned i=0,j=0;
for(i=0;i<n;i++)
{
for(j=0;j<120;j++);
}
}
void writedat(unsigned char dat)
{
RS=1;
RW=0;
E=0;
P2=dat;
delay(5);
E=1;
E=0;
}
void writecom(unsigned char com)
{
RS=0;
RW=0;
E=0;
P2=com;
delay(5);
E=1;
E=0;
}
void initlcd()
{
writecom(0x38);
writecom(0x0c);
writecom(0x06);
writecom(0x01);
}
void display()
{
int i=0,temp=0;
temp=R1302(0x8d);
datebuffer[2]=0x30+temp/16;
datebuffer[3]=0x30+temp%16;
temp=R1302(0x8b);
weekbuffer=0x30+temp;
temp=R1302(0x89);
datebuffer[5]=0x30+temp/16;
datebuffer[6]=0x30+temp%16;
temp=R1302(0x87);
datebuffer[8]=0x30+temp/16;
datebuffer[9]=0x30+temp%16;
temp=R1302(0x85);
temp=temp&0x7f;
timebuffer[0]=0x30+temp/16;
timebuffer[1]=0x30+temp%16;
temp=R1302(0x83);
timebuffer[3]=0x30+temp/16;
timebuffer[4]=0x30+temp%16;
temp=R1302(0x81);
temp=temp&0x7f;
timebuffer[6]=0x30+temp/16;
timebuffer[7]=0x30+temp%16;
writecom(0x80);
for(i=0;i<5;i++)
{
writedat(datechar[i]);
}
writecom(0xc0);
for(i=0;i<5;i++)
{
writedat(timechar[i]);
}
writecom(0x86);
for(i=0;i<10;i++)
{
writedat(datebuffer[i]);
}
writecom(0xc6);
for(i=0;i<8;i++)
{
writedat(timebuffer[i]);
}
writedat(' ');
writedat(weekbuffer);
}
void main()
{
initlcd();
W1302(0x8e,0);
W1302(0x8c,0x21);
W1302(0x8a,0x04);
W1302(0x88,0x07);
W1302(0x86,0x15);
W1302(0x84,0x22);
W1302(0x82,0x42);
W1302(0x80,0x30);
W1302(0x8e,0x80);
while(1)
{
display();
}
}
|