/**
 * \file
 *
 * \brief Empty user application template
 *
 */


#include <asf.h>
#include "main.h"
static volatile bool main_b_cdc_enable = false;
uint8_t usb_rx_Buffer[64];
int dac_value;

int main (void)
{
	irq_initialize_vectors();
	cpu_irq_enable();
	wdt_disable(WDT);
	sysclk_init();
	save_params_to_flash();
	ioport_init();
	read_params_from_flash();
	board_init();
	udc_start();
	tc0_0_init();
	SetupPeripherals();
	Pwm_init();
	twi0_init_m41t00();
	Adc_init(); 
	configure_usart0();
	//SPI_init();
	soft_spi_init();
	Time_adjust(25,10,2);
	//save_params_to_flash();
	soft_spi_init();
	//read_params_from_flash();
    //encoder_pulse_counter = SevenSegNumFont[0];
	/* Insert application code here, after the board has been initialized. */
	while(1)
	{
		/*
		if(udi_cdc_is_rx_ready())
		{
			udi_cdc_getc();
		}
	
		if(udi_cdc_is_tx_ready())
		{
			char_to_bcd(cfont.numchars);
			udi_cdc_putc(digitos.decenas);
			while(!udi_cdc_is_tx_ready());
			udi_cdc_putc(digitos.unidades);
			while(!udi_cdc_is_tx_ready());
			udi_cdc_putc(';');
			while(!udi_cdc_is_tx_ready());
		}
		*/
	
		twi_read_rtc();
		
		if(rs4_datos_listos)
		{
			rs4_datos_listos = false;
			dac_value += 20;
			if(dac_value>4095)
			  dac_value = 0;
			ltc1448_dac_update(dac_value,dac_value);

		}

	 }
}



bool my_callback_cdc_enable(void)
{
	main_b_cdc_enable = true;
	// Open communication
	///uart_open(port);
	return true;
}

void my_callback_cdc_disable(void)
{
	main_b_cdc_enable = false;
	// Close communication
	///uart_close(port);
}


void usb_data_received(uint8_t port)
{
   iram_size_t Number_of_Rcvd_Bytes;
   Number_of_Rcvd_Bytes = udi_cdc_get_nb_received_data();
   udi_cdc_read_buf(usb_rx_Buffer, Number_of_Rcvd_Bytes);

}

//Initialize MCU Peripherals
void SetupPeripherals(void)
{
	/* Initialize IOPORTs */
	ioport_init();
	//System Led
	pio_set_output(PIOD,SYS_LED_MASK,0,0,0);
	//Blue Led
	pio_set_output(PIOD,BLUE_LED_MASK,0,0,0);
	
	/* Salidas transistor */
	pio_set_output(PIOD,OUT0_PIN_MASK,0,0,0);
	pio_set_output(PIOD,OUT1_PIN_MASK,0,0,0);
	pio_set_output(PIOD,OUT2_PIN_MASK,0,0,0);
	
	/** Rotary Encoder. */
	//CanalA
	pio_set_input(PIOD,PIO_PD26,PIO_INPUT);
	//CanalB
	pio_set_input(PIOD,PIO_PD27,PIO_INPUT);
	//Push Button
	pio_set_input(PIOD,PIO_PD28,PIO_PULLUP|PIO_DEBOUNCE);
	//Configure debounce filter at 25Hz
	pio_set_debounce_filter(PIOD, PIO_PD28, 25);
	//Configure External Interrupt on fall edge of PIO_PD26
	pio_handler_set(PIOD, ID_PIOD, PIO_PD26, PIO_IT_FALL_EDGE, pioHandler);
	//Enable external interrupt
	pio_enable_pin_interrupt(PIO_PD26_IDX);
	//Configure Ext Interrupt in NVIC
	irq_register_handler(PIOD_IRQn,0);
	
	//VBUS Pin
	ioport_set_pin_peripheral_mode(PIO_PB14_IDX, USB_VBUS_FLAGS);
	
	//PWM Pins
	pio_set_peripheral(PIOD, PIO_PERIPH_A, PIO_PD24A_PWML0);
	pio_set_peripheral(PIOD, PIO_PERIPH_A, PIO_PD20A_PWMH0);
	
	/* ADC Pins. Disable pull-up*/
	PIOA->PIO_SODR = PIO_SODR_P17;
	PIOA->PIO_SODR = PIO_SODR_P18;
	
	//Allow TWI to control PA3 and PA4
	pio_set_peripheral(PIOA, PIO_PERIPH_A, PIO_PA3A_TWD0 | PIO_PA4A_TWCK0);
	
	//Allow USART0 to control PB0 and PB1
	pio_set_peripheral(PIOB, PIO_PERIPH_C, PIO_PB0C_RXD0 | PIO_PB1C_TXD0);
	
	//Rs4_DE
	pio_set_output(PIOA,RS4_DE_PIN_MASK,0,0,0);
	
	//Pines CAN0
	pio_set_peripheral(PIOB, PIO_PERIPH_A, PIO_PB3A_CANRX0);
	pio_set_peripheral(PIOB, PIO_PERIPH_A, PIO_PB2A_CANTX0);
	
	/* WIZNET Pins */
	//Reset
	pio_set_output(PIOD,WIZNET_RST_PIN_MASK,1,0,0);
	//Interrupt
	pio_set_input(PIOD,PIO_PD28,PIO_INPUT);
	//Configure External Interrupt on fall edge of PIO_PD26
	pio_handler_set(PIOD, ID_PIOD, PIO_PD28, PIO_IT_FALL_EDGE, pioHandler);
	//Enable external interrupt
	pio_enable_pin_interrupt(PIO_PD28_IDX);
	//Configure Ext Interrupt in NVIC
	irq_register_handler(PIOD_IRQn,0);
	
	//Pin DAC0
	pio_set_peripheral(PIOB, PIO_PERIPH_D, PIO_PB13X1_DAC0);
	
	//LTC1448 CS PIN
	pio_set_output(PIOD,LTC1448_CS_PIN_MASK,1,0,0);

	

}

//PIO Handler - called by the PIO ISR
void pioHandler(uint32_t id, uint32_t index)
{
	//If PD26 (Encoder A)
	if(id == ID_PIOD && index == PIO_PD26)
	{
		EncoderPulse();
	}
	
	
}



void EncoderPulse(void)
{
	if(ioport_get_pin_level(PIO_PD26_IDX))
	{
		pio_handler_set(PIOD, ID_PIOD, PIO_PD26, PIO_IT_FALL_EDGE, pioHandler);
		if(ioport_get_pin_level(PIO_PD27_IDX))
		{
			encoder_direction = false;
			encoder_pulse_counter--;
		}
		else
		{
			encoder_direction = true;
			encoder_pulse_counter++;
		}
		
	}
	else
	{
		pio_handler_set(PIOD, ID_PIOD, PIO_PD26, PIO_IT_RISE_EDGE, pioHandler);
		if(ioport_get_pin_level(PIO_PD27_IDX))
		{
			encoder_direction = true;
			encoder_pulse_counter++;
		}
		else
		{
			encoder_direction = false;
			encoder_pulse_counter--;
		}
		
	}
	
	encoder_pulse = true;
}

void save_params_to_flash(void)
{
	uint32_t * ptr;
	params.memory_blank = 1;
	params.lavar = 3;
	params.set_V_acido = 5;
	params.set_V_slurry = 7;
	params.set_V_agitador = 9;
	//copiamos la estructura en el array
	ptr = &params;
	for(int i=0;i<sizeof(PARAMETROS) / 4;i++)
	  ul_page_buffer[i] = * ptr++;
    
	flash_erase_user_signature();

	flash_write_user_signature(ul_page_buffer,IFLASH_PAGE_SIZE / sizeof(uint32_t));
	
		ul_page_buffer[0] = 6;
		ul_page_buffer[1] = 7;
		ul_page_buffer[2] = 8;
		ul_page_buffer[3] = 9;


}

void read_params_from_flash(void)
{

	flash_read_user_signature(ul_page_buffer,IFLASH_PAGE_SIZE / sizeof(uint32_t));
	
		ul_page_buffer[4] = 10;
		ul_page_buffer[5] = 20;
		ul_page_buffer[6] = 30;
		ul_page_buffer[7] = 40;

}



