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

void ADC_conf(ADC_TypeDef *adc, uint32_t voie) 
{
	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; 
	
	// Indique la voie a convertir
	adc->SQR3|= voie; 
	
	 // 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)
{
		// Lancement de la conversion
	  adc->CR2 |= ADC_CR2_ADON; 
    while(!(ADC1->SR & ADC_SR_EOC)) {}
			
    return ADC1->DR & ADC_DR_DATA_Msk;
}


double ADC_convertToVolt(uint16_t value)
{
	return ((double) value) / 4095.0 * 3.3;
}


double ADC_readVolt(ADC_TypeDef *adc)
{
	return ADC_convertToVolt(ADC_readRaw(adc));
}
