Blue Bridge Cup microcontroller training [4] --- DS1302 clock chip


DS1302 is launched by the United States DALLAS low-power real time clock chip having a fine trickle current charge capacity. It may be for the year, month, day, week, hours, minutes, seconds chronograph, and has a leap year compensation and other features.

SCM and DS1302 via SPI protocol communication, LSB first, because the organizers will provide SPI driver, there are very clear to read and write timing, not specifically about the SPI protocol here, we only focus below on how to use this chip.

RTC registers as follows:

image


Note:
the BCD code (1) DS1302 employed, the conversion is required when writing and reading!
(2) CH clock pause flag is set to 0 clock starts
(3) WP write protect bit, set to 0 when the data can be written


We need to implement a simple function is on two

   1. initialization time

   2. Reading Time


1. We want to configure the initial time, first of all to write protect (WP) switch off, about to address the highest position 8Eh zero, then you can have fun when minutes and seconds to register the appropriate time to write it, then pay close attention to the above RTC register BCD code data is stored, so our number must be converted to BCD code.

For chestnut, we usually contact the decimal number 23, is equivalent to 20 + 3, and which is directly 0x23 BCD code, is to put ten, respectively, and to the high and lower nibbles.

Initialization code is as follows:

void Ds1302_write(u8 h,u8 m,u8 s)
{
	Write_Ds1302_Byte (0x8e, 0x00);      // Close write protection 
	Write_Ds1302_Byte (0x84, H / H 10 * 16 + 10%); // time 
	Write_Ds1302_Byte (0x82, m / m% 10 * 16 + 10); // sub 
	Write_Ds1302_Byte ( 0x80, S / S 10 * 16 + 10%); // second 
	Write_Ds1302_Byte (0x8e, 0x80);     // open the write protection 
}

BCD code to write data probably also perform the above time, and we have time to read from the register back has always been BCD, very inconvenient, once had the entire function:

bcd_to_dat U8 (n-U8) // Returns incoming BCD code decimal
{
	u8 t1,t2;
	t1=n/16,t2=n%16;
	t1 + t2 = t1 * 10;
	return t1;
}

Well, after the initialization time on it, we can have fun reading time is it, when every minute here are saved in a global variable, aspects of call.

void read_Ds1302()
{
	H=bcd_to_dat(Read_Ds1302_Byte (0x85));
	M=bcd_to_dat(Read_Ds1302_Byte (0x83));
	S=bcd_to_dat(Read_Ds1302_Byte (0x81));

}


The above only describes a simple use of real-time clock, time enough for reading





Guess you like

Origin www.cnblogs.com/masterwayne/p/12369982.html