Skip to content
systemcoding.dev
Embedded

Read one ADC channel with HAL_ADC_Start and HAL_ADC_PollForConversion

Read one STM32 ADC channel in polling mode with HAL_ADC_Start, HAL_ADC_PollForConversion and HAL_ADC_GetValue, and convert the result to millivolts.

1 min read
Summarize in AI

For a single slow reading, polling is the least code. You start the conversion, wait for the end-of-conversion flag and read the data register. With the STM32F4 HAL and the ADC set to 12 bits, a 3.3 V reference gives 0 to 4095.

c
uint32_t adc_read_mv(void)
{
    HAL_ADC_Start(&hadc1);
    if (HAL_ADC_PollForConversion(&hadc1, 10) != HAL_OK) {
        HAL_ADC_Stop(&hadc1);
        return 0;
    }
    uint32_t raw = HAL_ADC_GetValue(&hadc1);
    HAL_ADC_Stop(&hadc1);

    printf("raw=%lu\n", raw);
    return (raw * 3300U) / 4095U;
}

With the input at mid-supply the print shows the raw count and the function returns about 1650 millivolts:

Text
raw=2048

The 10 is a timeout in milliseconds. If HAL_ADC_PollForConversion returns HAL_TIMEOUT the ADC is not running, often because the clock for the peripheral was not enabled or the channel was never configured.

Check the EOCSelection field in the ADC init. With ADC_EOC_SEQ_CONV the flag is raised only at the end of the whole sequence, so a multi-channel scan seems to finish early or return only the last channel. For a scan, use ADC_EOC_SINGLE_CONV, or switch to DMA.

Stopping after each read is not required in continuous mode but keeps single-shot code predictable. The functions are in stm32f4xx_hal_adc.c.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.