#include "bexus_adc.h"

// memory adress of calibration values for STM32F429
const uint16_t*  ADC_TEMP_3V3_30C =  (uint16_t*)(0x1FFF7A2C); //bei uns 0°C
const uint16_t*  ADC_TEMP_3V3_110C = (uint16_t*)(0x1FFF7A2E); //bei uns 30°C
const double CALIBRATION_REF_VOLTAGE_ADC = 3.3;

const double REF_VOLTAGE_ADC = 3.; // supplied with Vref+ or VDDA

	// scale constants to current reference voltage
	double adcCalTemp30C = 0; 
	double adcCalTemp110C = 0;

uint32_t adc3_buff[4],adc1_buff[1];

struct Dataset *data_adc;


void Adc_Init() {
	HAL_ADC_Start_DMA(&hadc3, adc3_buff,3);
	//HAL_ADC_Start_DMA(&hadc1,&data_adc->adc_temperature_internal_raw,1);
	HAL_ADC_Start_DMA(&hadc1,adc1_buff,1);
	HAL_ADC_Start_IT(&hadc3);
	HAL_ADC_Start_IT(&hadc1);


	 adcCalTemp30C = (double)(*ADC_TEMP_3V3_30C) * (REF_VOLTAGE_ADC/CALIBRATION_REF_VOLTAGE_ADC);
	 adcCalTemp110C = (double)(*ADC_TEMP_3V3_110C) * (REF_VOLTAGE_ADC/CALIBRATION_REF_VOLTAGE_ADC);
	


}

int Adc_Read() {
	//HAL_ADC_Start_IT(&hadc1);
	//HAL_ADC_Start_IT(&hadc3);
	
	data_adc = &Dataset_Master[buff_sensor_data_index];
	
	//data_adc->adc_temperature_internal_raw = adc1_buff[0] - (adc1_buff[0] & 0xFFFF0000);
	data_adc->adc_temperature_internal_raw = adc1_buff[0];
	data_adc->adc_voltage_raw  = (adc3_buff[0]>>16);
	data_adc->adc_current_raw  = adc3_buff[0] - (adc3_buff[0] & 0xFFFF0000);
	data_adc->adc_temperature_raw = adc3_buff[1];	
		
	//Temperature
	//PT1000
	//data_adc->adc_temperature=(double)((-3.9083) +	sqrt(15.27480889+0.00231*(1000-((data_adc->adc_temperature_raw*0.125)/4096)*3./0.0002)))/(-0.001155);
		data_adc->adc_temperature=(double)((-3.9083) +	sqrt(15.27480889+0.00231*(1000-data_adc->adc_temperature_raw*0.6105)))/(-0.001155);
	//internal
	//data_adc->adc_temperature_internal = ((data_adc->adc_temperature_internal_raw*1.) - adcCalTemp30C)/(adcCalTemp110C - adcCalTemp30C) * (110. - 30.) + 30.;
		data_adc->adc_temperature_internal = ((data_adc->adc_temperature_internal_raw*1.) - adcCalTemp30C)/(adcCalTemp110C - adcCalTemp30C) * 30. ;
	//Spannung
	data_adc->adc_voltage=(REF_VOLTAGE_ADC/4096*data_adc->adc_voltage_raw)*20;
	
	//Strom - Shunt?!
	data_adc->adc_current=(REF_VOLTAGE_ADC/4095*data_adc->adc_current_raw)/100/0.015;
	//data_adc->adc_current=(REF_VOLTAGE_ADC/4096*data_adc->adc_current_raw);

	
	return HAL_OK;
	
}

