/*
 * adc.c
 *
 *  Created on: Mar 11, 2025
 *      Author: andre
 */

#include "main.h"
#include "adc.h"

extern ADC_HandleTypeDef hadc1;

#define ADC_REGULAR_BUF_LEN			1
uint32_t ADCRegular[ADC_REGULAR_BUF_LEN];   // ADC regular conventions

void ADC_Init(void) {
	ADC_Enable(&hadc1);

	// ADC Calibration
	if (HAL_ADCEx_Calibration_Start(&hadc1) != HAL_OK) {
	    Error_Handler();
	}

	HAL_ADC_Start_DMA(&hadc1, ADCRegular, ADC_REGULAR_BUF_LEN);
}

void ADC_Start_Convertion(void) {
	HAL_ADC_Stop_DMA(&hadc1);
	HAL_ADC_Start_DMA(&hadc1, ADCRegular, ADC_REGULAR_BUF_LEN);
}

uint16_t ADC_GetVoltage(void) {
	uint32_t adc_value;

	adc_value = ADC_REF_Voltage_mV * ADCRegular[0] / 4095;
	adc_value = (adc_value* (ADC_Voltage_R1 + ADC_Voltage_R2)) / ADC_Voltage_R2; // Milivolts

	adc_value = adc_value / 100; // Volts * 10  It is need for telemetry
	return adc_value;
}
