/*
 * dac.c
 *
 * Created: 19/11/2016 13:58:41
 *  Author: Ledo
 */ 

#include "dac.h"

/** Main function to configure the DAC and DMA, and begin conversions. */
void dac_init(void)
{
	/* GPIO pin/DAC-function map. */
	const gpio_map_t DACIFB_GPIO_MAP = {
		{AVR32_DACREF_PIN, AVR32_DACREF_FUNCTION},
		{AVR32_ADCREFP_PIN, AVR32_ADCREFP_FUNCTION},
		{AVR32_ADCREFN_PIN, AVR32_ADCREFN_FUNCTION},
		{DAC_ADC_PIN, DAC_ADC_FUNCTION},
		{DAC_AUDIO_PIN, DAC_AUDIO_FUNCTION}
	};


	/* Assign and enable GPIO pins to the DAC function. */
	gpio_enable_module(DACIFB_GPIO_MAP, sizeof(DACIFB_GPIO_MAP) /
	sizeof(DACIFB_GPIO_MAP[0]));

	/* Get DACIFB Factory Configuration */
	dacifb_get_calibration_data(&AVR32_DACIFB0,
	&dacifb_opt,
	DAC_AUDIO_INSTANCE);

	/* Configure DACIFB */
	dacifb_configure(&AVR32_DACIFB0,
	&dacifb_opt,
	48000000);

	/* Configure channel DACIFB */
	dacifb_configure_channel(&AVR32_DACIFB0,
	dac_channel_audio,
	&dacifb_channel_opt,
	DAC_PRESCALER_CLOCK);

	dacifb_start_channel(&AVR32_DACIFB0,
	dac_channel_audio,
	48000000);
    
	dacifb_opt.channel_selection = DACIFB_CHANNEL_SELECTION_B;
	
	/* Get DACIFB Factory Configuration */
	dacifb_get_calibration_data(&AVR32_DACIFB0,
	&dacifb_opt,
	1);
	
    /* Configure DACIFB */
    dacifb_configure(&AVR32_DACIFB0,
    &dacifb_opt,
    48000000);

    /* Configure channel DACIFB */
    dacifb_configure_channel(&AVR32_DACIFB0,
    dac_channel_adc,
    &dacifb_channel_opt,
    DAC_PRESCALER_CLOCK);

    dacifb_start_channel(&AVR32_DACIFB0,
    dac_channel_adc,
    48000000);

}

void dac_set_value(uint16_t value)
{
	dacifb_set_value(&AVR32_DACIFB0,dac_channel_audio,false,value);
}

void dac1_set_value(uint16_t value)
{
	dacifb_set_value(&AVR32_DACIFB0,dac_channel_adc,false,value);
}

void sinus(uint8_t volume, uint8_t signal)
{
	uint16_t itemp;
	float ftemp;
	itemp = sin_table[sinus_point] / (101 - volume);
	ftemp = (float)itemp * (float)iArea / 300.0f;
	itemp = (uint16_t)ftemp;
	dac_set_value(itemp);
	if(sinus_point++ >= SINUS_SAMPLES)
	  sinus_point = 0;
}


