初始化DS1302模块的时间为23:59:55,并实时读取时间
main.c
#include"STC15F2K60S2.h"
#include"ds1302.h"
typedef unsigned char uchar;
typedef unsigned int uint;
uchar dsp_code[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar dsp_Time[8]={0xff,0xff,0xbf,0xff,0xff,0xbf};
uchar hour,min,sec;
void Timer0Init(void) //1毫秒@11.0592MHz
{
AUXR |= 0x80; //定时器时钟1T模式
TMOD &= 0xF0; //设置定时器模式
TL0 = 0xCD; //设置定时初值
TH0 = 0xD4; //设置定时初值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
}
void serviceTimer() interrupt 1
{
static uchar dsp_com=0;
P0=0;P2=0xc0;P2=0;
P0=dsp_Time[dsp_com];P2=0xe0;P2=0;
P0=1<<dsp_com;P2=0xc0;P2=0;
if(++dsp_com==8)dsp_com=0;
}
void Initsystem()
{
P0=0xff;P2=0x80;P2=0;
P0=0x00;P2=0xa0;P2=0;
}
void main()
{
Initsystem();
Set_Time(23,59,55);
Timer0Init();
while(1)
{
if(TH0<0xf0)
{
hour=Read_Ds1302_Byte(0x85);
min=Read_Ds1302_Byte(0x83);
sec=Read_Ds1302_Byte(0x81);
dsp_Time[0]=dsp_code[hour/16];
dsp_Time[1]=dsp_code[hour%16];
dsp_Time[3]=dsp_code[min/16];
dsp_Time[4]=dsp_code[min%16];
dsp_Time[6]=dsp_code[sec/16];
dsp_Time[7]=dsp_code[sec%16];
}
}
}
ds1302.c
/*
程序说明: DS1302驱动程序
软件环境: Keil uVision 4.10
硬件环境: CT107单片机综合实训平台 8051,12MHz
日 期: 2011-8-9
*/
#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);
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_();
RST=0;
SCK=0;
_nop_();
SCK=1;
_nop_();
SDA=0;
_nop_();
SDA=1;
_nop_();
return (temp);
}
void Set_Time(char hour,char min,char sec)
{
Write_Ds1302_Byte(0x8e,0x00);
Write_Ds1302_Byte(0x84,(hour/10)*16+hour%10);
Write_Ds1302_Byte(0x82,(min/10)*16+min%10);
Write_Ds1302_Byte(0x80,(sec/10)*16+sec%10);
Write_Ds1302_Byte(0x8e,0x80);
}
ds1302.h
#ifndef __DS1302_H
#define __DS1302_H
void Write_Ds1302_Byte(unsigned char temp);
void Write_Ds1302( unsigned char address,unsigned char dat );
unsigned char Read_Ds1302_Byte ( unsigned char address );
void Set_Time(char hour,char min,char sec);
#endif
|