.H文件
#ifndef __DS1302_H
#define __DS1302_H
#include "STC15F2K60S2.h"
#include <intrins.h>
extern unsigned char timeStart[6];
extern unsigned char timeTemp[6];
void Write_Ds1302_Byte(unsigned char temp);
void Write_Ds1302( unsigned char address,unsigned char dat );
unsigned char Read_Ds1302 ( unsigned char address );
void write_time();
void read_time();
#endif
.C文件
#include <ds1302.h>
sbit SCK=P1^7;
sbit SDA=P2^3;
sbit RST = P1^3; // DS1302复位
unsigned char timeStart[6]={55, 55, 23, 31, 12, 7}; //年份不可用CHAR 类型
unsigned char timeTemp[6]={00, 00, 00, 00, 00, 00};
void Write_Ds1302_Byte(unsigned char temp)
{
unsigned char i;
for (i=0;i<8;i++)
{
SCK=0;
SDA=temp&0x01;
temp>>=1;
SCK=1;
}
}
void Write_Ds1302( unsigned char address,unsigned char dat )
{
unsigned char temp;
RST=0;
_nop_();
SCK=0;
_nop_();
RST=1;
_nop_();
temp=(dat/10<<4)|(dat%10); //数值转换
Write_Ds1302_Byte(address);
Write_Ds1302_Byte(temp);
RST=0;
}
unsigned char Read_Ds1302 ( unsigned char address )
{
unsigned char i,t,temp=0x00;
RST=0;
_nop_();
SCK=0;
_nop_();
RST=1;
_nop_();
Write_Ds1302_Byte(address);
for (i=0;i<8;i++)
{
SCK=0;
temp>>=1;
if(SDA)
temp|=0x80;
SCK=1;
}
RST=0;
_nop_();
RST=0;
SCK=0;
_nop_();
SCK=1;
_nop_();
SDA=0;
_nop_();
SDA=1;
_nop_();
t=temp/16*10+temp%16; //十六进制的数转换成十进制
return t;
}
void write_time()
{
unsigned char i, addr=0x80;
Write_Ds1302(0x8e,0x00);
for(i=0; i<6; i++)
{
Write_Ds1302(addr, timeStart[i]);
addr+=2;
}
Write_Ds1302(0x8e,0x80);
}
void read_time()
{
unsigned char i, addr=0x81;
Write_Ds1302(0x8e,0x00);
for(i=0; i<6; i++)
{
timeTemp[i]=Read_Ds1302(addr);
addr+=2;
}
Write_Ds1302(0x8e,0x80);
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/82557.html