【蓝桥杯-单片机设计与开发】5.时钟DS1302

1.官方底层驱动代码

/*
  程序说明: 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_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 )     
{
 	RST=0;
	_nop_();
 	SCK=0;
	_nop_();
 	RST=1;	
   	_nop_();  
 	Write_Ds1302_Byte(address);	
 	Write_Ds1302_Byte(dat);		
 	RST=0; 
}

unsigned char Read_Ds1302 ( unsigned char address )
{
 	unsigned char i,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_();
	return (temp);			
}


2.原理图

DS1302原理图
单独接一个32.768K晶振,通过3个IO口进行数据传递。

3.芯片手册

实时时钟计数秒、分钟、小时、月份的日期、月份、日期、周和带闰年的年,补偿有效期至 2100。

(1)读写实现


初始化时,写入时间初始值,后续读取数值,即可得到时间。
有写保护WP=0,写保护关闭,WP=1,写保护打开。
值得注意的是,不论写入数据还是读取数据都是BCD码。
BCD码就是用4位二进制数表示0~9,这里要注意一下,4位二进制的BCD码是没有办法表示10的,如果需要表示10,那么就是0001 0000.
比如BCD码 0x10->10(十进制),0x89->89.

4.代码实现

RTC.c

#include "stc15f2k60s2.h"
#include "ds1302.h"

unsigned char time[6]={0x55,0x59,0x23};


void Timer_init()
{
	unsigned char i,add;
   	Write_Ds1302_Byte(0x8e,0x00);
	add=0x80;
	for(i=0;i<7;i++)
	{
		Write_Ds1302_Byte(add,time[i]);
		add+=2;

	}
	Write_Ds1302_Byte(0x8e,0x80);
}
void time_get()
{
	unsigned char i,add,tim1,tim2;
	
	add=0x81;
	for(i=0;i<7;i++)
	{
		time[i]=Read_Ds1302_Byte(add);
		tim1=time[i]/16;
		tim2=time[i]%16;
		time[i]=tim1*10+tim2;
		add+=2;		


	}
	

}

main.c


#include "stc15f2k60s2.h"
#include "display.h"
#include "hc138.h"
#include "rtc.h"


void main(void)
{
	init0();
	Timer2Init();
	Timer_init();
	while(1)
	{
		time_get();
		smgdat[0]=time[2]/10;
		smgdat[1]=time[2]%10;
		smgdat[2]=20;
		smgdat[3]=time[1]/10;
		smgdat[4]=time[1]%10;
		smgdat[5]=20;
		smgdat[6]=time[0]/10;
		smgdat[7]=time[0]%10;		
			
	}


}





posted @ 2022-01-07 10:42  寥若辰星  阅读(306)  评论(0编辑  收藏  举报