兩天速成藍橋杯之時鐘晶片DS1302(6)

沉睡的小灰發表於2020-10-22

前言

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;
}