 /***********************************************************
  *   Program:    AVRGCC - I2C Test
  *   Created:    31.8.99 17:23
  *   Author:     vlado.barjer@kks.s-net.net
  *   Comments:   let see what we can do whit this stuff
  ************************************************************/
#include "rtc.h"

void SetRTC (unsigned char *p)
{   unsigned char i;

    for (i=1;i<=6;i++)
    i2c_write(RTCAddress, i, *p++);
    i2c_write(RTCAddress, ControlReg, 0x00);
}

void setRTCTimer(void) {
	i2c_write(RTCAddress, 7, 1);
    i2c_write(RTCAddress, ControlReg, 0x00);
}

int makebcd(int dec)
{
	return 16*(dec/10)+dec%10;
}

void setTime(unsigned char year, unsigned char month, unsigned char day,
			unsigned char hours, unsigned char minutes, unsigned char seconds, unsigned char hundredths)
{
    unsigned char RtcBuffer[6];
    RtcBuffer[0] = makebcd(hundredths); // hundreds
    RtcBuffer[1] = makebcd(seconds); // sec
    RtcBuffer[2] = makebcd(minutes); // min
    RtcBuffer[3] = makebcd(hours); // hour
    RtcBuffer[4] = makebcd(day); // day
    RtcBuffer[5] = makebcd(month); // month
	RtcBuffer[4] |= (year << 6);
    SetRTC (RtcBuffer);
}


void GetRTC (unsigned char *p)
{   unsigned char i;

    for (i=1;i<=6;i++)
    *p++=(i2c_read(RTCAddress, i));
    i2c_write(RTCAddress, ControlReg, 0x00);
}

void decodeTime(unsigned char *RtcBuffer, unsigned char *year, unsigned char *month, unsigned char *day,
			unsigned char *hours, unsigned char *minutes, unsigned char *seconds, unsigned char *hundredths)
{
    *hours=10*(RtcBuffer[3] >> 4 & 0x3) + (RtcBuffer[3] & 0xf);
    *minutes=10*(RtcBuffer[2] >> 4) + (RtcBuffer[2] & 0xf);
    *seconds=10*(RtcBuffer[1] >> 4) + (RtcBuffer[1] & 0xf);
    *hundredths=10*(RtcBuffer[0] >> 4) + (RtcBuffer[0] & 0xf);
    *year=RtcBuffer[4]>>6;
    *month=10*(RtcBuffer[5] >> 4 & 0x1) + (RtcBuffer[5] & 0xf);
    *day=10*(RtcBuffer[4] >> 4 & 0x3) + (RtcBuffer[4] & 0xf);
}

void getTime(unsigned char *year, unsigned char *month, unsigned char *day,
			unsigned char *hours, unsigned char *minutes, unsigned char *seconds, unsigned char *hundredths)
{
    unsigned char RtcBuffer[6];
	GetRTC(RtcBuffer);
	decodeTime(RtcBuffer,year,month,day,hours,minutes,seconds,hundredths);
}
