1、硬件电路图:
DS1302与单片机之间能简单地采用同步串行的方式进行通信,仅需要用到3个口线:RES复位(P1^3)、I/O数据(P2^3)和SCLK串行时钟(P1^7)。
2、数据传输
(1)控制字格式
一个命令字节启动一次数据传输:(命令字节总是从最低位开始输入)
- 7: 最高位必须是逻辑1;
- 6: 如果为0,选择时钟/日历相关寄存器,否则选择RAM相关寄存器;(选择大类)
- 5-1:第1位到第5位指定输入或输出寄存器;(选择具体寄存器)
- 0 : 为0(奇数)时写,为1(偶数)时读,
(2)寄存器(读/写)地址及定义
(3)时序
数据在SCLK的上升沿入,下降沿串行出!!!
- 单字节操作:每次对DS1302的写入或读出都由命令字节引导,每次只传送1字节数据。
- 单字节读操作:单字节读操作每次需15个时钟,地址字节在前8个时钟周期的上升沿输入,而数据字节在后8个时钟周期的下降沿输出。DS1302输出的第一位数据是在命令字节最后一位的第一个下降沿处。
- 单字节写操作:单片机通过8个sclk上升沿传送写命令字节后,在接下来的8个sclk时钟的下降沿传送一字节数据。
3、代码实现
(1)ds1302.c
/*底层驱动代码*/
#include "ds1302.h"
sbit SCK = P1^7;
sbit SDA = P2^3;
sbit RST = P1^3;
//
void Write_Ds1302(unsigned char temp)
{
unsigned char i;
for (i=0;i<8;i++)
{
SCK = 0;
SDA = temp&0x01;
temp>>=1;
SCK=1;
}
}
//
void Write_Ds1302_Byte( unsigned char address,unsigned char dat )
{
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
Write_Ds1302(dat);
RST=0;
}
//
unsigned char Read_Ds1302_Byte ( unsigned char address )
{
unsigned char i,temp=0x00;
RST=0; _nop_();
SCK=0; _nop_();
RST=1; _nop_();
Write_Ds1302(address);
for (i=0;i<8;i++)
{
SCK=0;
temp>>=1;
if(SDA)
temp|=0x80;
SCK=1;
}
RST=0; _nop_();
SCK=0; _nop_();
SCK=1; _nop_();
SDA=0; _nop_();
SDA=1; _nop_();
return (temp);
}
/*RTC读写代码*/
/*设置时钟*/
void Set_Rtc(unsigned char *pucRtc)
{
Write_Ds1302_Byte(0x8e,0x00); //WP=0,允许写操作
Write_Ds1302_Byte(0x84,pucRTC[0]); //设置时
Write_Ds1302_Byte(0x82,pucRTC[1]); //设置分
Write_Ds1302_Byte(0x80,pucRTC[2]); //设置秒
Write_Ds1302_Byte(0x8e,0x80); //WP=1,禁止写操作
}
/*读取时钟*/
void Get_RTC(unsigned char *pucRTC)
{
pucRTC[0] = Read_Ds1302_Byte(0x85); //读取时
pucRTC[1] = Read_Ds1302_Byte(0x83); //读取分
pucRTC[2] = Read_Ds1302_Byte(0x81); //读取秒
}
//需要加减按键控制时钟时 要将其转为10进制进行加减
// 设置时钟
void Set_RTC(unsigned char* pucRtc)
{
unsigned char temp;
Write_Ds1302_Byte(0x8E, 0); // WP=0:允许写操作
temp = ((pucRtc[0]/10)<<4)+pucRtc[0]%10;
Write_Ds1302_Byte(0x84, temp); // 设置时
temp = ((pucRtc[1]/10)<<4)+pucRtc[1]%10;
Write_Ds1302_Byte(0x82, temp); // 设置分
temp = ((pucRtc[2]/10)<<4)+pucRtc[2]%10;
Write_Ds1302_Byte(0x80, temp); // 设置秒
Write_Ds1302_Byte(0x8E, 0x80); // WP=1:禁止写操作
}
// 读取时钟
void Get_RTC(unsigned char* pucRtc)
{
unsigned char temp;
temp = Read_Ds1302_Byte(0x85); // 读取时
pucRtc[0] = (temp>>4)*10+(temp&0xf);
temp = Read_Ds1302_Byte(0x83); // 读取分
pucRtc[1] = (temp>>4)*10+(temp&0xf);
temp = Read_Ds1302_Byte(0x81); // 读取秒
pucRtc[2] = (temp>>4)*10+(temp&0xf);
}
(2)ds1302.h
#ifndef __DS1302_H
#define __DS1302_H
#include <STC15F2K60S2.H>
#include "intrins.h"
void Set_RTC(unsigned char *pucRTC);
void Get_RTC(unsigned char *pucRTC);
#endif
(3)主函数调用
unsigned char pucRTC[3] = {0x23,0x59,0x50};
Set_RTC(pucRTC); //初始化RTC
Get_RTC(pucRTC); //读取RTC