/*============================================================================*/
/*
 Copyright (c) 2005-2018, Isaac Marino Bavaresco
 All rights reserved
 isaacbavaresco@yahoo.com.br
*/
/*============================================================================*/
//#include 
#include "RTC.h"
#include "I2C.h"
/*============================================================================*/
void RTCInit( void )
	{
	vI2CInit( I2C2 );
	}
/*============================================================================*/
#define	RTC_BUS_ADDRESS	0xde
#define	I2C_WRITE		0x00
#define	I2C_READ		0x01
/*============================================================================*/
unsigned short RTCRead( unsigned char *Buffer, unsigned char Address, unsigned char Length )
	{
	vI2CSendStart( I2C2 );
	if( uI2CSendByte( I2C2, RTC_BUS_ADDRESS | I2C_WRITE ))
		goto Error;
	if( uI2CSendByte( I2C2, Address ))
		goto Error;
	vI2CSendStop( I2C2 );
	vI2CSendStart( I2C2 );
	if( uI2CSendByte( I2C2, RTC_BUS_ADDRESS | I2C_READ ))
		goto Error;

	for( ; Length; Buffer++, Length-- )
		*Buffer = uI2CReadByte( I2C2, Length == 1 );

	vI2CSendStop( I2C2 );
	return 1;

Error:
	vI2CSendStop( I2C2 );
	return 0;
	}
/*============================================================================*/
unsigned short RTCWrite( unsigned char *Buffer, unsigned char Address, unsigned char Length )
	{
	vI2CSendStart( I2C2 );
	if( uI2CSendByte( I2C2, RTC_BUS_ADDRESS | I2C_WRITE ))
		goto Error;
	if( uI2CSendByte( I2C2, Address ))
		goto Error;

	for( ; Length; Buffer++, Length-- )
		if( uI2CSendByte( I2C2, *Buffer ))
			goto Error;

	vI2CSendStop( I2C2 );
	return 1;

Error:
	vI2CSendStop( I2C2 );
	return 0;
	}
/*============================================================================*/
unsigned short ReadClock( unsigned char *p )
	{
	unsigned char	h[8];

	if( !RTCRead( h, 0, 8 ))
		return 0;

	p[0]	= ( h[6] & 0x0f ) + ((( h[6] >> 4 ) & 0x0f ) * 10 );
	p[1]	= ( h[5] & 0x0f ) + ((( h[5] >> 4 ) & 0x01 ) * 10 );
	p[2]	= ( h[4] & 0x0f ) + ((( h[4] >> 4 ) & 0x03 ) * 10 );;
	p[3]	= ( h[2] & 0x0f ) + ((( h[2] >> 4 ) & 0x03 ) * 10 );
	p[4]	= ( h[1] & 0x0f ) + ((( h[1] >> 4 ) & 0x0f ) * 10 );
	p[5]	= ( h[0] & 0x0f ) + ((( h[0] >> 4 ) & 0x07 ) * 10 );

	return 1;
	}
/*============================================================================*/
unsigned short AdjustClock( unsigned char *p )
	{
	unsigned char	h[8];		

	h[0]	= (( p[5] / 10 ) << 4 ) | ( p[5] % 10 ) | 0x80;
	h[1]	= (( p[4] / 10 ) << 4 ) | ( p[4] % 10 );
	h[2]	= ((( p[3] / 10 ) << 4 ) | ( p[3] % 10 )) & 0x3f;
	h[3]	= 0x08;
	h[4]	= (( p[2] / 10 ) << 4 ) | ( p[2] % 10 );
	h[5]	= (( p[1] / 10 ) << 4 ) | ( p[1] % 10 );
	h[6]	= (( p[0] / 10 ) << 4 ) | ( p[0] % 10 );
	h[7]	= 0x00;

	return RTCWrite( h, 0, 8 );
	}
/*============================================================================*/