📄 ds1302.c
字号:
///////////////////////////////系统时钟////////////////////////////////
#include <at89x52.h>
#define uchar unsigned char
#define uint unsigned int
sbit RST = P1^6;
sbit SCL = P1^4;
sbit SDA = P1^5;
#define READ 1
#define WRITE 0
unsigned char SetTimeBuf[7] = {0x0,0x18,0x17,0x31,0x1,0x3,0x7};
//2007年1月18日20:30:00,当前时间格式为: 秒 分 时 日 月 星期 年
unsigned char TimeBuf[7];
void DS1302_SendByte(unsigned char Data)
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA = (bit)(Data & 0x01);
SCL = 1;
SCL = 0;
Data >>= 1;
}
return;
}
unsigned char DS1302_ReadByte(void)
{
unsigned char i,Data;
for(i=0;i<8;i++)
{
SDA=0;
Data >>= 1;
if(SDA==1) Data |= 0x80;
SCL = 1;
SCL = 0;
}
return(Data);
}
void DS1302WriteByte(unsigned char Addr, unsigned char Data)
{
SCL = 0;
RST = 1;
DS1302_SendByte(Addr);
DS1302_SendByte(Data);
RST = 0;
}
unsigned char DS1302ReadByte(unsigned char Addr)
{
unsigned char Data;
SCL = 0;
RST = 1;
DS1302_SendByte(Addr | READ);
Data = DS1302_ReadByte();
RST = 0;
return Data;
}
void SetTime(void)
{
uchar i,temp=0x80;
DS1302WriteByte(0x8e,0x00); //允许读写WP=0
for(i=0;i<7;i++)
{
DS1302WriteByte(temp,SetTimeBuf[i]);
temp+=2;
}
DS1302WriteByte(0x90,0xa5); //充电器设置,禁止充电
//DS1302WriteByte(0x8e,0x80); //禁止写WP=1,write protect
}
unsigned char BCDConvert(unsigned char ucBCD)//ucBCD为待转换的BCD码;
{
unsigned char TempH,TempL;
TempH = (ucBCD&0xF0)>>4; //TempH保存十进制数的高位
TempL = ucBCD&0x0f; //TempL保存十进制数的低位
return TempH*10+TempL;
}
void ReadTime(void)
{
uchar i,temp,adderss=0x81;
for(i=0;i<7;i++)
{
temp=DS1302ReadByte(adderss);
TimeBuf[i]=BCDConvert(temp);
adderss+=2;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -