以下为源程序:
——————————————————————————————————————————————————————
#include<reg52.h>
#include<intrins.h>
sbit SCK=P1^7;
sbit SDA=P2^3;
sbit RST=P1^3;
unsigned char we[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
unsigned char duan[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
/*单字节写入一字节数据*/
void Write_Ds1302_Byte(unsigned char dat)
{
unsigned char i;
SCK = 0;
for (i=0;i<8;i++)
{
if (dat & 0x01) // 等价于if((addr & 0x01) ==1)
{
SDA=1;
}
else
{
SDA=0;
}
SCK=1;
SCK=0;
dat = dat >> 1;
}
}
/********************************************************************/
/*单字节读出一字节数据*/
unsigned char Read_Ds1302_Byte(void)
{
unsigned char i, dat=0;
for (i=0;i<8;i++)
{
dat = dat >> 1;
if (SDA)
{
dat |= 0x80;
}
else
{
dat &= 0x7F;
}
SCK=1;
SCK=0;
}
return dat;
}
/********************************************************************/
/*向DS1302 单字节写入一字节数据*/
void Ds1302_Single_Byte_Write(unsigned char addr, unsigned char dat)
{
RST=0; /*RST脚置低,实现DS1302的初始化*/
SCK=0; /*SCK脚置低,实现DS1302的初始化*/
RST=1; /*启动DS1302总线,RST=1电平置高 */
Write_Ds1302_Byte(addr); /*写入目标地址:addr,保证是写操作,写之前将最低位置零*/
Write_Ds1302_Byte(dat); /*写入数据:dat*/
RST=0; /*停止DS1302总线*/
}
/********************************************************************/
/*从DS1302单字节读出一字节数据*/
unsigned char Ds1302_Single_Byte_Read(unsigned char addr)
{
unsigned char temp;
RST=0; /*RST脚置低,实现DS1302的初始化*/
SCK=0; /*SCK脚置低,实现DS1302的初始化*/
RST=1; /*启动DS1302总线,RST=1电平置高 */
Write_Ds1302_Byte(addr); /*写入目标地址:addr,保证是读操作,写之前将最低位置高*/
temp=Read_Ds1302_Byte(); /*从DS1302中读出一个字节的数据*/
RST=0; /*停止DS1302总线*/
return temp;
}
unsigned char dat_bcd(date)
{
unsigned char dat1,dat2;
dat1=date/10;
dat2=date%10;
dat2=dat2+dat1*16;
return dat2;
}
unsigned char bcd_dat(date)
{
unsigned char dat1,dat2;
dat1=date/16;
dat2=date%16;
dat2=dat2+dat1*10;
return dat2;
}
void Delay1ms() //@11.0592MHz
{
unsigned char i, j;
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
}
void display(unsigned char sec,unsigned char min,unsigned char hour)
{
P2=0xc0;P0=we[0];P2=0x00;P2=0xe0;P0=~duan[hour/10];P2=0x00;Delay1ms();
P2=0xc0;P0=we[1];P2=0x00;P2=0xe0;P0=~duan[hour%10];P2=0x00;Delay1ms();
P2=0xc0;P0=we[2];P2=0x00;P2=0xe0;P0=0xff;P2=0x00;Delay1ms();
P2=0xc0;P0=we[3];P2=0x00;P0 = 0xff;P2=0xe0;P0=~duan[min/10];P2=0x00;Delay1ms();
P2=0xc0;P0=we[4];P2=0x00;P0 = 0xff;P2=0xe0;P0=~duan[min%10];P2=0x00;Delay1ms();
P2=0xc0;P0=we[5];P2=0x00;P2=0xe0;P0=0xff;P2=0x00;Delay1ms();
P2=0xc0;P0=we[6];P2=0x00;P0 = 0xff;P2=0xe0;P0=~duan[sec/10];P2=0x00;Delay1ms();
P2=0xc0;P0=we[7];P2=0x00;P0 = 0xff;P2=0xe0;P0=~duan[sec%10];P2=0x00;Delay1ms();
}
void main()
{
unsigned char sec,min,hour;
Ds1302_Single_Byte_Write(0x8e,0x00);
Ds1302_Single_Byte_Write(0x80,dat_bcd(45));//秒
Ds1302_Single_Byte_Write(0x82,dat_bcd(49));//分
Ds1302_Single_Byte_Write(0x84,dat_bcd(16));//时
Ds1302_Single_Byte_Write(0x8e,0x80);
while(1)
{
sec=bcd_dat(Ds1302_Single_Byte_Read(0x81));
min=bcd_dat(Ds1302_Single_Byte_Read(0x83));
hour=bcd_dat(Ds1302_Single_Byte_Read(0x85));
display(sec,min,hour);
}
}
|