#include "ds1302.h"
#include "stcdelay.h"
#define CLOCK_HALT_MASK 0x80 //1000 0000
#define HALF_FULL_MODE_MASK 0x80 //1000 0000 12/24小时模式
#define AM_PM_MASK 0x20 //0010 0000
#define DISABLE_WRITE_PROTECT 0x00 //允许写入
#define ENABLE_WRITE_PROTECT 0x80 //禁止写入
void InitDS1302()
{
BYTE temp = 0;
/*********************************************************
At power-up, RST must be a logic 0 until VCC > 2.0V.
Also SCLK must be at a logic 0 when RST is driven to
a logic 1 state.
*******************************************************/
RST_PIN = 0;
DelayMS(10);
RST_PIN = 1;
SCLK_PIN = 0;
WriteSingleCmdByte(CONTROL, DISABLE_WRITE_PROTECT); //允许写
/********************************************************************************
In order to prevent accidental enabling, only a pattern of 1010 will enable
the trickle charger(TCS),
有备用电池,涓流充电用处不大
*********************************************************************************/
WriteSingleCmdByte(TRICKLE_CHARGE, 0x00); //不使用充电功能
temp = ReadSingleCmdByte(SECOND_READ);//读出,然后再写入
RESET_STATE_FLAG(temp, CLOCK_HALT_MASK);//清CLOCK HALT FLAG,以便可以正常启动
WriteSingleCmdByte(SECOND_WRITE, temp);
}
static void WriteSingleCmdByte(COMMANDBYTE cmd, BYTE Data)
{
RST_PIN = 0;
SCLK_PIN = 0;
RST_PIN = 1;
WriteOneByte(cmd);
WriteOneByte(Data);
RST_PIN = 0;
}
static BYTE ReadSingleCmdByte(COMMANDBYTE cmd)
{
BYTE Ret = 0;
RST_PIN = 0;
SCLK_PIN = 0;
RST_PIN = 1;
WriteOneByte(cmd);
Ret = ReadOneByte();
RST_PIN = 0;
return Ret;
}
static void WriteOneByte(BYTE byte)
{
BYTE i = 0;
for(i = 0; i < 8; i++)
{
IO_PIN = TEST_BIT(byte, i);
SCLK_PIN = 1;
NOP();
NOP();
NOP();
SCLK_PIN = 0;
}
}
static BYTE ReadOneByte()
{
BYTE i = 0;
BYTE Ret = 0;
/*******************************************************************
Note that the first data bit to be transmitted occurs on the first falling
edge after the last bit of the command byte is written.
所以进入循环后马上读取IO数据
*******************************************************************/
for(i = 0; i < 8; i++)
{
if(IO_PIN)
{
SET_BIT(Ret, i);
}
SCLK_PIN = 1;
NOP();
NOP();
NOP();
SCLK_PIN = 0;
}
return Ret;
}
void SetDateTime(const BCDDATETIME* pBCDDateTime)
{
BYTE i = 0;
const BYTE* p = (BYTE*)pBCDDateTime;
RST_PIN = 0;
SCLK_PIN = 0;
RST_PIN = 1;
WriteOneByte(CLOCK_BURST_WRITE);
for(i = 0; i < 8; i++)
{
WriteOneByte(*p);
p++;
}
RST_PIN = 0;
}
void GetDateTime(BCDDATETIME* pBCDDateTime)
{
BYTE i = 0;
BYTE* p = (BYTE*)pBCDDateTime;
RST_PIN = 0;
SCLK_PIN = 0;
RST_PIN = 1;
WriteOneByte(CLOCK_BURST_READ);
/*******************************************************************
Note that the first data bit to be transmitted occurs on the first falling
edge after the last bit of the command byte is written.
所以进入循环后马上读取IO数据
*******************************************************************/
for(i = 0; i < 7; i++) //最后一个字节是写保护字节,不需要读取
{
*p = ReadOneByte();
p++;
}
RST_PIN = 0;
}
复制代码