From c62b23094fbd6cc8c1f064fc8ed86a2e6c6f9358 Mon Sep 17 00:00:00 2001 From: Damien George Date: Sat, 4 Aug 2018 13:25:43 +1000 Subject: [PATCH] stm32/adc: Disable VBAT in read channel helper function. Prior to this patch, if VBAT was read via ADC.read() or ADCAll.read_channel(), then it would remain enabled and subsequent reads of TEMPSENSOR or VREFINT would not work. This patch makes sure that VBAT is disabled for all cases that it could be read. --- ports/stm32/adc.c | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/ports/stm32/adc.c b/ports/stm32/adc.c index d0689cd8c9..4755a8ede0 100644 --- a/ports/stm32/adc.c +++ b/ports/stm32/adc.c @@ -315,7 +315,20 @@ STATIC uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) { STATIC uint32_t adc_config_and_read_channel(ADC_HandleTypeDef *adcHandle, uint32_t channel) { adc_config_channel(adcHandle, channel); - return adc_read_channel(adcHandle); + uint32_t raw_value = adc_read_channel(adcHandle); + + #if defined(STM32F4) || defined(STM32F7) + // ST docs say that (at least on STM32F42x and STM32F43x), VBATE must + // be disabled when TSVREFE is enabled for TEMPSENSOR and VREFINT + // conversions to work. VBATE is enabled by the above call to read + // the channel, and here we disable VBATE so a subsequent call for + // TEMPSENSOR or VREFINT works correctly. + if (channel == ADC_CHANNEL_VBAT) { + ADC->CCR &= ~ADC_CCR_VBATE; + } + #endif + + return raw_value; } /******************************************************************************/ @@ -692,15 +705,6 @@ float adc_read_core_vbat(ADC_HandleTypeDef *adcHandle) { // be 12-bits. raw_value <<= (12 - adc_get_resolution(adcHandle)); - #if defined(STM32F4) || defined(STM32F7) - // ST docs say that (at least on STM32F42x and STM32F43x), VBATE must - // be disabled when TSVREFE is enabled for TEMPSENSOR and VREFINT - // conversions to work. VBATE is enabled by the above call to read - // the channel, and here we disable VBATE so a subsequent call for - // TEMPSENSOR or VREFINT works correctly. - ADC->CCR &= ~ADC_CCR_VBATE; - #endif - return raw_value * VBAT_DIV * ADC_SCALE * adc_refcor; }