#include "reg52.h"
#include "intrins.h"
sbit CE=P1^3;
sbit IO=P1^2;
sbit SCLK=P1^4;
sbit wela=P1^1;
sbit dula=P1^0;
typedef unsigned char uint8;
typedef unsigned int uint16;
uint8 code duan[11]={0x3F,0x06,0x5B,0x4F,0x66,0x6D, 0x7D,0x07,0x7F,0x6F,0x40};
uint8 code wei[8]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
uint8 init[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // 秒 分 时 日 月 星期 年
uint8 ReadedTime[7] = {0};
uint8 TimeData[14] = {0};
uint8 i,j;
void WriteByte_DS1302(uint8 dat)
{
uint8 i;
for (i=0; i<8; i++) //8位计数器
{
SCLK = 0; //时钟线拉低
_nop_(); //延时等待
_nop_();
dat >>= 1; //移出数据
IO = CY; //送出到端口
SCLK = 1; //时钟线拉高
_nop_(); //延时等待
_nop_();
}
}
uint8 ReadByte_DS1302()
{
uint8 i;
uint8 dat = 0;
for (i=0; i<8; i++)
{
SCLK = 0; //时钟线拉低
_nop_(); //延时等待
_nop_();
dat >>= 1; //数据右移一位
if (IO) dat |= 0x80; //读取数据
SCLK = 1; //时钟线拉高
_nop_();
_nop_();
}
return dat;
}
uint8 ReadData_DS1302(uint8 addr)
{
uint8 dat;
CE = 0;
_nop_(); //延时等待
_nop_();
SCLK = 0;
_nop_(); //延时等待
_nop_();
CE = 1;
_nop_(); //延时等待
_nop_();
WriteByte_DS1302(addr); //写地址
dat = ReadByte_DS1302(); //读数据
SCLK = 1;
CE = 0;
return dat;
}
void WriteData_DS1302(uint8 addr, uint8 dat)
{
CE = 0;
_nop_(); //延时等待
_nop_();
SCLK = 0;
_nop_(); //延时等待
_nop_();
CE = 1;
_nop_(); //延时等待
_nop_();
WriteByte_DS1302(addr); //写地址
WriteByte_DS1302(dat); //写数据
SCLK = 1;
CE = 0;
}
void SetTime_DS1302(uint8 *Pointer)
{
uint8 addr = 0x80;
uint8 n = 7;
WriteData_DS1302(0x8e, 0x00); //允许写操作
while (n--)
{
WriteData_DS1302(addr, *Pointer++);
addr += 2;
}
WriteData_DS1302(0x8e, 0x80); //写保护
}
void GetTime_DS1302(uint8 *Pointer)
{
uint8 addr = 0x81;
uint8 n = 7;
while (n--)
{
*Pointer++ = ReadData_DS1302(addr);
addr += 2;
}
}
void Initial_DS1302()
{
CE = 0;
SCLK = 0;
WriteData_DS1302(0x8e, 0x00); //允许写操作
WriteData_DS1302(0x80, 0x00); //时钟启动
//WriteData_DS1302(0x90, 0xa6); //一个二极管+4K电阻充电,在有备用电源的情况下使用
WriteData_DS1302(0x84, 0x80);
WriteData_DS1302(0x8e, 0x80); //写保护
}
void DataProcess_DS1302()
{
volatile uint8 Value=0;
Value=((ReadedTime[0]&0x70)>>4)*10 +(ReadedTime[0]&0x0f); // 秒 数据处理
TimeData[0]=Value%10;
TimeData[1]=Value/10;
TimeData[2]=10;
Value=((ReadedTime[1]&0x70)>>4)*10 +(ReadedTime[1]&0x0f); // 分 数据处理
TimeData[3]=Value%10;
TimeData[4]=Value/10;
TimeData[5]=10;
Value=((ReadedTime[2]&0x70)>>4)*10 +(ReadedTime[2]&0x0f); // 时 数据处理
TimeData[6]=Value/10;
TimeData[7]=Value%10;
}
void delay(uint16 m)
{ uint16 n;
for(;m>0;m--)
for(n=110;n>0;n--);
}
void display()
{ j=7;
for(i=0;i<8;i++)
{
wela=1;
P2=wei[i];
wela=0;
dula=1;
P2=duan[TimeData[j--]];
dula=0;
delay(1);
dula=1;
P2=0x00;
dula=0;
}
}
void main()
{ Initial_DS1302(); //初始化DS1302
SetTime_DS1302(init);
while(1)
{
GetTime_DS1302(ReadedTime); //读取当前时间
DataProcess_DS1302(); //设置初始时间
display();
} }
|