STM32L4 ADC: remove adc_inited flag

pull/5513/head
bcostm 2017-11-14 15:27:41 +01:00
parent 52d942e2d2
commit 072ec2e765
1 changed files with 30 additions and 33 deletions

View File

@ -36,10 +36,9 @@
#include "mbed_error.h"
#include "PeripheralPins.h"
int adc_inited = 0;
void analogin_init(analogin_t *obj, PinName pin)
{
static int adc_calibrated = 0;
uint32_t function = (uint32_t)NC;
// ADC Internal Channels "pins" (Temperature, Vref, Vbat, ...)
@ -48,14 +47,14 @@ void analogin_init(analogin_t *obj, PinName pin)
if ((pin < 0xF0) || (pin >= 0x100)) {
// Normal channels
// Get the peripheral name from the pin and assign it to the object
obj->handle.Instance = (ADC_TypeDef *) pinmap_peripheral(pin, PinMap_ADC);
obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC);
// Get the functions (adc channel) from the pin and assign it to the object
function = pinmap_function(pin, PinMap_ADC);
// Configure GPIO
pinmap_pinout(pin, PinMap_ADC);
} else {
// Internal channels
obj->handle.Instance = (ADC_TypeDef *) pinmap_peripheral(pin, PinMap_ADC_Internal);
obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(pin, PinMap_ADC_Internal);
function = pinmap_function(pin, PinMap_ADC_Internal);
// No GPIO configuration for internal channels
}
@ -67,16 +66,8 @@ void analogin_init(analogin_t *obj, PinName pin)
// Save pin number for the read function
obj->pin = pin;
// The ADC initialization is done once
if (adc_inited == 0) {
adc_inited = 1;
// Enable ADC clock
__HAL_RCC_ADC_CLK_ENABLE();
__HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_SYSCLK);
// Configure ADC object structures
obj->handle.State = HAL_ADC_STATE_RESET;
// Configure ADC
obj->handle.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV2; // Asynchronous clock mode, input ADC clock
obj->handle.Init.Resolution = ADC_RESOLUTION_12B;
obj->handle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
@ -93,11 +84,17 @@ void analogin_init(analogin_t *obj, PinName pin)
obj->handle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; // DR register is overwritten with the last conversion result in case of overrun
obj->handle.Init.OversamplingMode = DISABLE; // No oversampling
// Enable ADC clock
__HAL_RCC_ADC_CLK_ENABLE();
__HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_SYSCLK);
if (HAL_ADC_Init(&obj->handle) != HAL_OK) {
error("Cannot initialize ADC\n");
error("Cannot initialize ADC");
}
// Calibrate ADC
// ADC calibration is done only once
if (adc_calibrated == 0) {
adc_calibrated = 1;
HAL_ADCEx_Calibration_Start(&obj->handle, ADC_SINGLE_ENDED);
}
}
@ -181,7 +178,7 @@ static inline uint16_t adc_read(analogin_t *obj)
// Wait end of conversion and get value
if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) {
return (HAL_ADC_GetValue(&obj->handle));
return (uint16_t)HAL_ADC_GetValue(&obj->handle);
} else {
return 0;
}