六、蓝桥杯练习之DS1302编程

 根据DS1302的芯片手册,我们可以看出来写入时,分,秒的地址分别是:0x84,0x82,0x80;读取时分秒的地址分别是:0x85,0x83,0x81;其他的可参考下图。

*值得注意的是,进行写错操作时,应该当将0x8e的BIT7(第七位)置0,写入完毕时,置1。

 

根据官方提供的底层代码进行编程:

/*
  程序说明: DS1302驱动程序
  软件环境: Keil uVision 4.10 
  硬件环境: CT107单片机综合实训平台 8051,12MHz
  日    期: 2011-8-9
*/

#include <STC15F2K60S2.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);
	dat = dat / 10 * 16 + dat % 10;	    //需自己添加此段代码
 	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_();
 	SCK=0;	_nop_();
	SCK=1;	_nop_();
	SDA=0;	_nop_();
	SDA=1;	_nop_();
	temp = temp / 16 * 10 + temp % 16;	//需自己添加此段代码
	return (temp);			
}

//*******以下是比赛时需自己编写的部分*********
void Set_Time_SFM(unsigned char S,unsigned char F,unsigned char M)
{
	Write_Ds1302_Byte(0X8E,0X00);
	Write_Ds1302_Byte(0X84,S);
	Write_Ds1302_Byte(0X82,F);
	Write_Ds1302_Byte(0X80,M);
	Write_Ds1302_Byte(0X8E,0X80);
}

由于写入时,我们写入的是十进制数,需要进行转码。

在ds1302.c中的“Write_Ds1302_Byte()”函数中增加BCD转码在“Write_Ds1302(dat);”

前添加 (dat = dat / 10 * 16 + dat % 10)即可。

相同,读取时间时,也要相应的进行转码。

在ds1302.c中的“Read_Ds1302_Byte()“函数中增加BCD转码在“return (temp); “前添加

(temp = temp  / 16 * 10 + temp % 16)即可。

读取时间,对应相对地址即可。读取时分秒的地址分别是:0x85,0x83,0x81;

unsigned char S,F,M;
void Read_Time()
{
    S = Read_Ds1302_Byte(0X85);
	F = Read_Ds1302_Byte(0X83);
	M = Read_Ds1302_Byte(0X81);
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值