#include <REGX52.h>
#include "Delay.h"
#include "ds1302.h"

sbit SCLK = P3^6;
sbit CE = P3^5;
sbit IO = P3^4;

const unsigned char time_address[] = {0x8C, 0x88, 0x86, 0x8A, 0x84, 0x82, 0x80};

void DS1302_Write_Byte(unsigned char command)
{
	unsigned char i = 0;
	
	for(i = 0; i < 8; i++)
	{
		IO = command & 0x01;
		Delay_Microsecond(2);
		SCLK = 0;
		Delay_Microsecond(2);
		SCLK = 1;

		command >>= 1;
	}
}

void DS1302_Write(unsigned char address, unsigned char control)
{
	
	CE = 0;
	Delay_Microsecond(2);
	SCLK = 0;
	Delay_Microsecond(2);
	CE = 1;
	Delay_Microsecond(2);
	
	DS1302_Write_Byte(address);
	DS1302_Write_Byte(control);
	
	CE = 0;
}


unsigned char DS1302_Read_Byte()
{
	unsigned char i = 0;
	unsigned char time = 0x00;
	
	//IO = 0;
	IO = 1;

	for(i = 0; i < 8; i++)
	{
		SCLK = 1;
		Delay_Microsecond(2);
		SCLK = 0;
		Delay_Microsecond(2);

		if(IO == 1)
			time |= (0x01 << i);
	}


	return time;
}


unsigned char DS1302_Read(unsigned char address)
{	
	unsigned char time = 0x00;
	address |= 0x01;

	CE = 0;
	Delay_Microsecond(2);
	SCLK = 0;
	Delay_Microsecond(2);
	CE = 1;
	Delay_Microsecond(2);
	
	DS1302_Write_Byte(address);
	time = DS1302_Read_Byte();
	
	CE = 0;
	return time;
}