#include "Alimentation.h"

#include "stm32f1xx_ll_adc.h"
#include "stm32f1xx_ll_bus.h"
#include "stm32f1xx_ll_rcc.h"
#include "stm32f1xx_ll_gpio.h"
#include <math.h>

void ALIMENTATION_Init(void){
	RCC -> CFGR |= (0x1<<15);
	RCC-> CFGR &= ~ (0x1<<14);
	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_ADC1);
	LL_APB1_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOC);
	
	LL_GPIO_InitTypeDef pc2;
	LL_ADC_InitTypeDef adc;
	LL_ADC_REG_InitTypeDef adcReg;
	
	LL_GPIO_StructInit(&pc2);
	pc2.Pin = LL_GPIO_PIN_0;
	pc2.Mode = LL_GPIO_MODE_ANALOG;
	LL_GPIO_Init(GPIOC, &pc2);


	adc.DataAlignment = LL_ADC_DATA_ALIGN_RIGHT;
	adc.SequencersScanMode = LL_ADC_SEQ_SCAN_DISABLE;
	LL_ADC_Init(ADC1, &adc);

	adcReg.TriggerSource = LL_ADC_REG_TRIG_SOFTWARE ;
	adcReg.SequencerLength = LL_ADC_REG_SEQ_SCAN_DISABLE;
	adcReg.SequencerDiscont = LL_ADC_REG_SEQ_DISCONT_DISABLE;
	adcReg.ContinuousMode = LL_ADC_REG_CONV_SINGLE;
	adcReg.DMATransfer = LL_ADC_REG_DMA_TRANSFER_NONE;    
	
	
	LL_ADC_REG_Init(ADC1, &adcReg);
	LL_ADC_Enable(ADC1);
}

float ALIMENTATION_GetBatteryLevel(void){		
	float u2;
	float battery_level;
	LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_12);
	LL_ADC_REG_StartConversionSWStart(ADC1);	
	while (LL_ADC_IsActiveFlag_EOS(ADC1) != 1);
	battery_level = LL_ADC_REG_ReadConversionData12(ADC1);
	u2 = (battery_level*3.3)/4095.0;
	float level = u2*13.0;	
	return level;
}
	
int ALIMENTATION_IsLevelEnough(void){
	if (ALIMENTATION_GetBatteryLevel()<(0.8*12)){
		return 0;
	}else{
		return 1;
	}
}
