.H文件
#ifndef __DS1302_H #define __DS1302_H #include "STC15F2K60S2.h" #include <intrins.h> extern unsigned char timeStart[7]; extern unsigned char timeTemp[7]; 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[7]={55, 55, 23, 31, 12, 7, 2018}; unsigned char timeTemp[7]={00, 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<7; 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<7; i++) { timeTemp[i]=Read_Ds1302(addr); addr+=2; } Write_Ds1302(0x8e,0x80); }