/*
 * ACD.c
 *
 *  Created on: Feb 26, 2012
 *      Author: RomanM
 */

#include <inttypes.h>
#include "ADC.h"
#include "hal_ADC.h"

static adc_channel_t currentAdcChannel;
static uint16_t convResult[3] = {0, 0, 0};
static uint16_t convResultFilt[3] = {0, 0, 0};

void ADC1_Init(void) {
	hal_ADC_Init();
	currentAdcChannel = TEMP;
	hal_ADC_ChangeChannel(currentAdcChannel);
	hal_ADC_StartConversion();
}

void ADC1_InterruptHandler(void) {
	uint16_t adcValue = hal_ADC_Value();

	convResult[currentAdcChannel] = adcValue;
	convResultFilt[currentAdcChannel] = convResultFilt[currentAdcChannel] - (convResultFilt[currentAdcChannel]>>4) + adcValue;

	switch (currentAdcChannel) {
		case SENSOR1:
			currentAdcChannel = SENSOR2;
			break;
		case SENSOR2:
			currentAdcChannel = TEMP;
			break;
		default:
			currentAdcChannel = SENSOR1;
			break;
	}
	hal_ADC_ChangeChannel(currentAdcChannel);
	hal_ADC_StartConversion();
}

uint16_t ADC1_GetValue(uint8_t channel) {
	if (channel < 3) {
		return convResult[channel];
	}
	else {
		return 0;
	}
}

uint16_t ADC1_GetValueFilt(uint8_t channel) {
	if (channel < 3) {
		return convResultFilt[channel] >> 4;
	}
	else {
		return 0;
	}
}

float ADC1_Temperature(void) {
	float Vsense = ((float)convResult[TEMP] / 4096.0) * 3.3;
	float temperature = ((1.41 - Vsense) / 4.3) + 25;

	return temperature;
}
