/*
 * drv_adc.c
 *
 *  Created on: 13 мар. 2025 г.
 *      Author: basov.g
 */
#include "drv_adc.h"
#include "MDR32VF0xI.h"
#include "MDR32VF0xI_adc.h"
#include "MDR32VF0xI_dma.h"
#include "MDR32VF0xI_port.h"
#include "MDR32VF0xI_rst_clk.h"

int temp = 0;// one per dot
int v5 = 0; //two per dot
int vBat = 0; //two per dot
int vBatInt = 0; //two per dot
int vRef = 0; //two per dot

void __attribute__ ((interrupt)) ADC_IRQHandler( void )
{
	if ((MDR_ADC->ADC1_STATUS & ADC_FLAG_END_OF_CONVERSION) != ADC_FLAG_END_OF_CONVERSION) {
		MDR_ADC->ADC1_STATUS = ADC_FLAG_END_OF_CONVERSION;
	    return;
	}

	const uint8_t adc_ch = (MDR_ADC->ADC1_RESULT & 0x00070000) >> 16;

	int adcRes = MDR_ADC->ADC1_RESULT & ADC1_RESULT_RESULT_Msk;
	switch(adc_ch)
	{
		case 7 : temp =250- ((33 * adcRes-14366) * 270/1024); break;//14366
		case 6 : v5 = 330*adcRes*1680/1024/680; break;
		case 5 : vBat = 330*adcRes/1024; break;
		case 4 : break;
		case 3 : break; //test
		case 2 : vBatInt = 330*adcRes/1024; break;
		case 1 : vRef = 330*adcRes/1024; break;
		case 0 : break; //test
	}

	/* reset bit of overwrite if it was set */
	MDR_ADC->ADC1_STATUS = ADC1_STATUS_ECOIF_IE;
}

void drv_adc_init(void)
{
	RST_CLK_PCLKCmd(RST_CLK_PCLK_ADC, ENABLE);
	RST_CLK_ADC_ClkSelection(RST_CLK_ADC_CLK_SRC_PLLCPU);
	RST_CLK_ADC_SetPrescaler(RST_CLK_ADC_PRESCALER_DIV_8);
	RST_CLK_ADC_ClkCmd(ENABLE);

	ADC_SetChannels(0xFF);

	ADC_InitTypeDef adcInitTypeDef = {0};
	adcInitTypeDef.ADC_ClockSource = ADC_CLOCK_SOURCE_PCLKd;
	adcInitTypeDef.ADC_Prescaler =ADC_PRESCALER_DIV_2048;
	adcInitTypeDef.ADC_VRefSource = ADC_VREF_SOURCE_INTERNAL;
	adcInitTypeDef.ADC_ChannelSwitching = ADC_CH_SWITCHING_ENABLE;
	adcInitTypeDef.ADC_SamplingMode = ADC_SAMPLING_MODE_CYCLIC_CONV;
	adcInitTypeDef.ADC_Channels = ADC_CH_ADC0_TEMP_SENSOR_MASK|ADC_CH_ADC1_SAR_AIN1_MASK|ADC_CH_ADC2_SAR_AIN2_MASK|
									ADC_CH_ADC3_SAR_AIN3_MASK|ADC_CH_ADC5_VDD_BG_MASK|ADC_CH_ADC6_VREF_MASK;
	adcInitTypeDef.ADC_DelayGo = 0;
	adcInitTypeDef.ADC_ChannelNumber = ADC_CH_ADC0_TEMP_SENSOR;
	adcInitTypeDef.ADC_Scale = ADC_SCALE_MAX_UCCA;
	ADC_Init(&adcInitTypeDef);
	ADC_Start();

	CLIC_SetPriorityIRQ(ADC_IRQn,4);
	CLIC_EnableIRQ(ADC_IRQn);
    MDR_ADC->ADC1_STATUS |= ADC1_STATUS_ECOIF_IE;
	ADC_Cmd(ENABLE);

}

void drv_adc_update(void)
{


}

int drv_adc_getVoltage5V(void)
{
	return v5;
}
int drv_adc_getBatteryVoltage(void)
{
	return vBat;
}
int drv_adc_getBatteryVoltageInternal(void)
{
	return vBatInt;
}
int drv_adc_getVref(void)
{
	return vRef;
}
int drv_adc_getTemp(void)
{
	return temp;
}
