DS1302的整理与使用(笔记篇)
模块及引脚说明
寄存器
时序图
代码篇
- 头文件
#ifndef _DS1302_H_
/*宏定义*/
#define uchar unsigned char
#define Write_Second 0x80 //写秒
#define Read_Second 0X81 //读秒
#define Write_Minute 0X82 //写分
#define Read_Minute 0X83 //读分
#define Write_Hour 0X84 //写时
#define Read_Hour 0X85 //读时
#define Write_Day 0X86 //写日
#define Read_Day 0X87 //读日
#define Write_Month 0X88 //写月
#define Read_Month 0X89 //读月
#define Write_Week 0X8A //写星期
#define Read_Week 0X8B //读星期
#define Write_Year 0X8C //写年
#define Read_Year 0X8D //读年
#define Write_Protect 0X8E //写保护
/*自定义结构体数组*/
typedef struct __SYSTEMTIME__
{
uchar Second;
uchar Minute;
uchar Hour;
uchar Week;
uchar Day;
uchar Month;
uchar Year;
}SYSTEMTIME;
/*声明*/
void DS1302Write(uchar reg, uchar dat);
uchar DS1302Read(uchar addr);
void DS1302_Init();
void DS1302_GetTime(SYSTEMTIME *Time);
#endif
-
子函数
-
单字节写操作
void DS1302Write(uchar reg, uchar dat) //单字节写操作 reg 寄存器 dat 要写的数据
{
uchar detect;
DS1302RST = 1;
for(detect = 0x01; detect != 0; detect <<= 1)
{
if(reg & detect != 0)
{
DS1302DAT = 1;
}
else
{
DS1302DAT = 0;
}
DS1302CK = 1;
DS1302CK = 0;
}
for(detect = 0x01; detect != 0; detect <<= 1)
{
if(reg & dat != 0)
{
DS1302DAT = 1;
}
else
{
DS1302DAT = 0;
}
DS1302CK = 1;
DS1302CK = 0;
}
DS1302RST = 0;
}
- 单字节读操作
uchar DS1302Read(uchar addr) //单字节读操作 addr 要读的地址
{
uchar detect;
uchar dat = 0;
DS1302RST = 1;
for(detect = 0x01; detect != 0; detect <<= 1)
{
if(addr & detect != 0)
{
DS1302DAT = 1;
}
else
{
DS1302DAT = 0;
}
DS1302CK = 1;
DS1302CK = 0;
}
for(detect = 0x01; detect != 0; detect <<= 1)
{
if(DS1302DAT != 0)
{
dat |= detect;
}
DS1302CK = 1;
DS1302CK = 0;
}
DS1302RST = 0;
return dat;
}
- 从DS1302中获取时间
void DS1302_GetTime(SYSTEMTIME *Time) //获取DS1302时间存放在自定义结构体
{
uchar ReadValue;
ReadValue = DS1302Read(Read_Year);
Time -> Year = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Month);
Time -> Month = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Day);
Time -> Day = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Week);
Time -> Week = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Hour);
Time -> Hour = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Minute);
Time -> Minute = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
ReadValue = DS1302Read(Read_Second);
Time -> Second = ((ReadValue & 0x70) >> 4) * 10 + (ReadValue & 0x0f);
}
- 初始化
void DS1302_Init() //初始化写入20年5月20日13时14分0秒星期三
{
DS1302Write(Write_Protect,0x00); //关保护位
DS1302Write(Write_Year,0x20); //年
DS1302Write(Write_Month,0x05); //月
DS1302Write(Write_Day,0x00); //日
DS1302Write(Write_Week,0x03); //星期
DS1302Write(Write_Hour,0x13); //时
DS1302Write(Write_Minute,0x14); //分
DS1302Write(Write_Second,0x00); //秒
DS1302Write(Write_Protect,0x80); //开保护位
}
声明:仅供参考,如有不足,还请指正。