/*
 * tmrs.c
 *
 * Created: 24/09/2016 11:38:27
 *  Author: Ledo
 */ 



#include "tmrs.h"



/**
 * \brief TC Initialization
 *
 * Initializes and start the TC module with the following:
 * - Counter in Up mode with automatic reset on RC compare match.
 * - fPBA/8 is used as clock source for TC
 * - Enables RC compare match interrupt
 * \param tc Base address of the TC module
 */
 void tc0_init(volatile avr32_tc_t *tc, uint16_t per)
{
	
	// Initialize the timer/counter.
	tc_init_waveform(tc, &waveform_opt0);
	tc_write_rc(tc, TMR_CHANNEL0, per);
	tc_configure_interrupts(tc, TMR_CHANNEL0, &tc_interrupt0);
	//INTC_register_interrupt(&tc_irq, AVR32_TC0_IRQ0, AVR32_INTC_INT0);
	INTC_register_interrupt(&tc0_irq, AVR32_TC0_IRQ0, 0);

	// Start the timer/counter.
	tc_start(tc, TMR_CHANNEL0);
	
	// Enable the clock to the selected example Timer/counter peripheral module.
	sysclk_enable_peripheral_clock(tc);

}


/**
 * \brief TC Initialization
 *
 * Initializes and start the TC module with the following:
 * - Counter in Up mode with automatic reset on RC compare match.
 * - fPBA/8 is used as clock source for TC
 * - Enables RC compare match interrupt
 * \param tc Base address of the TC module
 */
 void tc1_init(volatile avr32_tc_t *tc, uint16_t per)
{
	
	// Initialize the timer/counter.
	tc_init_waveform(tc, &waveform_opt1);
	tc_write_rc(tc, TMR_CHANNEL1, per);
	tc_configure_interrupts(tc, TMR_CHANNEL1, &tc_interrupt1);
	//INTC_register_interrupt(&tc_irq, AVR32_TC0_IRQ0, AVR32_INTC_INT0);
	INTC_register_interrupt(&tc1_irq, AVR32_TC0_IRQ1, 1);

	// Start the timer/counter.
	tc_start(tc, TMR_CHANNEL1);
	
	// Enable the clock to the selected example Timer/counter peripheral module.
	sysclk_enable_peripheral_clock(tc);

}



//Periodo de conmutación del emisor (20 Hz)
__attribute__((__interrupt__))
static void tc0_irq(void)
{
	int32_t sr = sysreg_read(AVR32_SR);//AVR32_SR;
	// Clear the interrupt flag. This is a side effect of reading the TC SR.
	tc_read_sr(&AVR32_TC0, 0);
	led_counter++;
	flags.lcd_menu = true;
    sysreg_write(AVR32_SR, sr) ;
}


//Periodo de muestreo del adc (48 KHz);
__attribute__((__interrupt__))
static void tc1_irq(void)
{
	int32_t sr = sysreg_read(AVR32_SR);//AVR32_SR;

	// Clear the interrupt flag. This is a side effect of reading the TC SR.
	tc_read_sr(&AVR32_TC0, 1);
	adc_sample = true;
    sysreg_write(AVR32_SR, sr) ;
	
}




