#include "ADC.h"
#include "stm32f1xx_ll_bus.h" 	// Pour horloge

const float MAX_VOLTS = 3.3;
const float MAX_CONVERTED_VALUE = 4095.0;

void ADC_conf(ADC_TypeDef *adc) 
{
	if (adc == ADC1) {
		LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_ADC1);
	} else if (adc == ADC2) {
		LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_ADC2);
	}
	
	// Division de la frequence
	RCC->CFGR |= RCC_CFGR_ADCPRE_DIV6;
	
	// Fixe le nombre de conversion à 1
	adc->SQR1 &= ADC_SQR1_L; 
	

	
	 // Calibration
	adc->CR2 |= ADC_CR2_CAL_Msk;
	while ((adc->CR2 & ADC_CR2_CAL_Msk));	
}


void ADC_start(ADC_TypeDef *adc)
{
	adc->CR2 |= ADC_CR2_ADON;
}


uint16_t ADC_readRaw(ADC_TypeDef *adc, int channel)
{
		// Indique la voie a convertir
		adc->SQR3 = channel; 
		// Lancement de la conversion
	  adc->CR2 |= ADC_CR2_ADON; 
    while(!(ADC1->SR & ADC_SR_EOC)) {}

    return ADC1->DR & ADC_DR_DATA_Msk;
}


float ADC_convertToVolt(uint16_t value)
{
	return ((double) value) / MAX_CONVERTED_VALUE * MAX_VOLTS;
}


float ADC_readVolt(ADC_TypeDef *adc, int channel)
{
	return ADC_convertToVolt(ADC_readRaw(adc, channel));
}
