- 目的:
-
1.搞懂调用底层驱动和读写的时序
-
2.写/读时的数据处理
-
3.显示的数据处理
- 程序说明:
-
1.通过写入初始时间(怎么写入?)
-
2.获取实时时间(怎么获取?)
-
3.数据处理(怎么显示出来?)
-
4.在数码管上显示(自由发挥)
main.c
#include <STC15F2K60S2.H>
#include <ds1302.h>
#include <display.h>
#include <stdio.h>
unsigned char Dis_Buf[] = {" "}; //定义数码缓冲
unsigned char shijian[3] = {0x50,0x59,0x23}; //预设时间
unsigned char shi[3]; //返回的时间
unsigned char flag,flag2;
void init(); //DS1302的初始化
void time0(); //定时器的初始化
void job2(); //数据处理函数
void get(); //时间获取
void main()
{
init();
time0();
while(1)
{
get(); //get时间
job2(); //数据处理
Display(Dis_Buf); //刷新函数
}
}
void init()
{
unsigned char i,add;
add=0x80;
Write_Ds1302_Byte(0x8e,0x00); //解除保护
for(i=0;i<3;i++)
{
Write_Ds1302_Byte(add,shijian[i]); //依次写入初始时间
add=add+2;
}
Write_Ds1302_Byte(0x8e,0x80); //加上保护
}
void get()
{
unsigned char i,add;
add=0x81;
Write_Ds1302_Byte(0x8e,0x00);
for(i = 0;i<3;i++)
{
shi[i]=Read_Ds1302_Byte(add); //读出数据
add=add+2;
}
Write_Ds1302_Byte(0x8e,0x80);
}
void job2()
{
//相差0x30 数字和字符串相差0x30(48)
Dis_Buf[0]=shi[2]/10+0x30;
Dis_Buf[1]=shi[2]%10+0x30; //对每个数组进行赋值
Dis_Buf[2]='-';
Dis_Buf[3]=shi[1]/10+0x30;
Dis_Buf[4]=shi[1]%10+0x30;
Dis_Buf[5]='-';
Dis_Buf[6]=shi[0]/10+0x30;
Dis_Buf[7]=shi[0]%10+0x30;
}
void time0()
{
TMOD = 0x01;
TL0 = (65536-1000)%256; //定义为1ms
TH0 = (65536-1000)/256;
TF0 = 0;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void time0_0() interrupt 1
{
unsigned char num;
if(num<1200)
{
num++;
}else
{
num = 0;
}
if(num%1==0) flag = 1;
if(num%100==0) flag2 = 1;
TL0 = (65536-1000)%256;
TH0 = (65536-1000)/256;
}
iic.c 底层代码
#include <reg52.h>
#include <intrins.h>
sbit SCK=P1^7;
sbit SDA=P2^3;
sbit RST = P1^3; // DS1302复位
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);
// Write_Ds1302(((dat/10)<<4)|dat%10); //将数据转换成BCD码
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_();
temp = (temp/16)*10+temp%16; //将数据转换成整数
return (temp);
}