前言

DS1302作为时钟芯片,感觉是省赛的基础元件的使用的最后一个了,感觉可能比较复杂,但是其实也没多复杂,这里的代码是参考我朋友的,也没来得及仔细研究。这里就全当给大家参考了。

代码详解

其实我倒是遇见过,这个读出来全是165的,原因是因为板子的芯片没插牢,所以导致了这种现象。

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

#include <STC15F2K60S2.H>
#include <intrins.h>
#include "ds1302.h"

void Write_Ds1302(unsigned char temp)
{
	unsigned char i;
	for (i = 0; i < 8; i++)
	{
		SCK = 0;
		SDA_DS = 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_DS)
			temp |= 0x80;
		SCK = 1;
	}
	RST = 0;
	_nop_();
	SCK = 0;
	_nop_();
	SCK = 1;
	_nop_();
	SDA_DS = 0;
	_nop_();
	SDA_DS = 1;
	_nop_();
	return (temp);
}

void setsfm(unsigned char shi, unsigned char fen, unsigned char miao, unsigned char ri, unsigned char yue, unsigned char zhou, unsigned char nian)
{
	Write_Ds1302_Byte(0x8e, 0);
	Write_Ds1302_Byte(0x80, miao / 10 * 16 + miao % 10);
	Write_Ds1302_Byte(0x82, fen / 10 * 16 + fen % 10);
	Write_Ds1302_Byte(0x84, shi / 10 * 16 + shi % 10);
	Write_Ds1302_Byte(0x86, ri / 10 * 16 + ri % 10);
	Write_Ds1302_Byte(0x88, yue / 10 * 16 + yue % 10);
	Write_Ds1302_Byte(0x8a, zhou / 10 * 16 + zhou % 10);
	Write_Ds1302_Byte(0x8c, nian / 10 * 16 + nian % 10);
	Write_Ds1302_Byte(0x8e, 0x80);
}
unsigned char getshi()
{
	unsigned char a = Read_Ds1302_Byte(0x85);
	return a / 16 * 10 + a % 16;
}
unsigned char getfen()
{
	unsigned char a = Read_Ds1302_Byte(0x83);
	return a / 16 * 10 + a % 16;
}
unsigned char getmiao()
{
	unsigned char a = Read_Ds1302_Byte(0x81);
	return a / 16 * 10 + a % 16;
}
unsigned char getri()
{
	unsigned char a = Read_Ds1302_Byte(0x87);
	return a / 16 * 10 + a % 16;
}
unsigned char getyue()
{
	unsigned char a = Read_Ds1302_Byte(0x89);
	return a / 16 * 10 + a % 16;
}
unsigned char getzhou()
{
	unsigned char a = Read_Ds1302_Byte(0x8B);
	return a / 16 * 10 + a % 16;
}
unsigned char getnian()
{
	unsigned char a = Read_Ds1302_Byte(0x8D);
	return a / 16 * 10 + a % 16;
}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐