/*
 * m41t00.c
 *
 * Created: 11/06/2018 8:48:41
 *  Author: Ledo
 */ 
#include "asf.h"

#define RTC_SLAVE_ADDRESS          0x68 //Direccion sin righ shift



m41t00_time_t decoded_time;
m41t00_time_t time;
twi_packet_t twiPacket_m41t00;
//uint8_t tw0_buffer[8];

char segundos;
char minutos;
char horas;
char dia;
uint16_t time_set_delay_counter;
uint8_t time_set_timer;
//functions
void twi0_init_m41t00(void);
void twi_write_rtc(void);
void twi_read_rtc(void);
uint8_t m41t00_bcd_to_byte(uint8_t bcd_val);
uint8_t m41t00_byte_to_bcd(uint8_t byte_val);
void  minute_adjust(uint8_t min);
void  hour_adjust(uint8_t hora);
void  day_adjust(uint8_t dia);
void  Time_adjust(uint8_t min,uint8_t hora, uint8_t dia);


//Initialize TW0 interface
void twi0_init_m41t00(void)
{
	//Create TWI Packet
	twiPacket_m41t00.buffer = (uint8_t*)&time;//tw0_buffer;//Read/write buffer
	twiPacket_m41t00.length = 8;                           //#bytes to tx/rx
	twiPacket_m41t00.chip = (uint32_t) RTC_SLAVE_ADDRESS;  //Slave address
	twiPacket_m41t00.addr[0] = 0;                          //Unused
	twiPacket_m41t00.addr_length = 1;

	//Allow TWI to control PA3 and PA4
	pio_set_peripheral(PIOA, PIO_PERIPH_A, PIO_PA3A_TWD0 | PIO_PA4A_TWCK0);

	//Enable TWI0 Clock
	sysclk_enable_peripheral_clock(ID_TWI0);

	//Configure TWI options - 100kHz bus speed
	const twi_options_t twiOpts = {sysclk_get_cpu_hz(), 100000UL, 0, 0};

	//Initialize TWI module as a master
	twi_master_init(TWI0, &twiOpts);
}


/****************************************************/
void twi_write_rtc(void)
{
	twi_master_write(TWI0,&twiPacket_m41t00);
}

/****************************************************/
void twi_read_rtc(void)
{
	twi_master_read(TWI0,&twiPacket_m41t00);
	decoded_time.sec = m41t00_bcd_to_byte(time.sec);
	decoded_time.min = m41t00_bcd_to_byte(time.min & 0x7F);
	decoded_time.hour = m41t00_bcd_to_byte(time.hour & 0x3F) ;
	decoded_time.day_of_week = m41t00_bcd_to_byte(time.day_of_week & 0x07) ;
	decoded_time.day_of_month =m41t00_bcd_to_byte(time.day_of_month);
	decoded_time.month =m41t00_bcd_to_byte(time.month);
	decoded_time.year =m41t00_bcd_to_byte(time.year);
}

uint8_t m41t00_bcd_to_byte(uint8_t bcd_val)
{
	return (bcd_val&0xf) + ((bcd_val&0xf0) >> 4)*10;
}

uint8_t m41t00_byte_to_bcd(uint8_t byte_val)
{
	return (byte_val%10) + ((byte_val/10) << 4);
}





void  minute_adjust(uint8_t minutos)
{
	time.min = m41t00_byte_to_bcd(minutos);
	twi_write_rtc();
	
}

void  hour_adjust(uint8_t hora)
{
	time.hour = m41t00_byte_to_bcd(hora);
	twi_write_rtc();
	
}


void  day_adjust(uint8_t dia)
{
	time.day_of_week = m41t00_byte_to_bcd(dia);
	twi_write_rtc();
}

void  Time_adjust(uint8_t min,uint8_t hora, uint8_t dia)
{
	time.min = m41t00_byte_to_bcd(min);
	time.hour = m41t00_byte_to_bcd(hora);
	time.day_of_week = m41t00_byte_to_bcd(dia);
	twi_write_rtc();
}



