Learn / Pins: in and out · guide 6 of 10

Read an analog voltage

You turn a potentiometer on Arduino pin A0 and see a number from 0 to 65535, and the same value in millivolts, printed on your PC every 200 ms.

Intermediate≈ 75 minBefore this:Print to your PC over the virtual COM portTopics:USARTADC

The ADC measures a voltage and gives you a number. On the STM32H7 it does not work out of the box: its clock source is off after reset, it sleeps in deep power-down, it has to be calibrated, and every input channel must be "preselected". This guide walks through each of those traps in order, with the page that explains each one.

You will learn
  • Find which pin and which ADC channel an Arduino analog pin uses
  • Give the ADC a working kernel clock: the reset default is a PLL that is switched off
  • Bring the ADC up in the right order: leave deep power-down, enable the regulator, calibrate, enable
  • Select a channel with ADC_PCSEL and ADC_SQR1, choose a sampling time, start a conversion and read ADC_DR
You need
  • STM32H750B-DK and a USB cable to CN14
  • STM32CubeIDE installed, and the code from the UART guide (we print the result with printf)
  • A potentiometer, 10 kΩ or lower (linear), and three jumper wires

On this board

Pulled from the datasheet tables and the board schematic. Click a pin for everything the finder knows about it.

PinBallBoard netUsed here asAFOpen
PC0L2ARD_A0Arduino A0: analog input, the wiper of the potentiometer (ADC channel INP10)
1

Find the analog pin and its ADC channel

The Arduino header has six analog pins, A0 to A5. The user manual's connector table shows that A0 is PC0 and gives its analog function as ADC123_IN10. The datasheet writes the same thing as ADC123_INP10 in the "additional functions" column of PC0: "INP10" means "positive input 10", and "ADC123" means that channel 10 exists on ADC1, ADC2 and ADC3. We will use ADC1, input 10.

Analog pins are not an alternate function. After reset a pin is in analog mode already (MODER = 11), which is exactly what the ADC needs. You only have to make sure not to change it.

Wire the potentiometer: one outer leg to the 3.3 V pin of the Arduino power header, the other outer leg to GND, and the middle leg (the wiper) to A0. The wiper then outputs a voltage between 0 V and 3.3 V. Never use the 5 V pin for this: the MCU pins are 3.3 V devices and the user manual says so.

2

What the number means

The ADC compares the input voltage with a reference voltage, VREF+, and returns how far up the scale it is. With 16-bit resolution (the reset setting) the scale has 65 536 steps: 0 V gives 0 and VREF+ gives about 65 535. So:

voltage ≈ raw / 65535 × VREF+

On this board VREF+ is the analog supply. The MCU power sheet of the schematic shows the VREF+ ball (M1) tied to VDDA through R66, a 0 Ω resistor, and VDDA comes from the 3.3 V supply through the ferrite bead L2. So VREF+ is about 3.3 V. If you need accuracy better than a percent or two, measure VREF+ with a multimeter and use that number.

How long does a conversion take? The ADC first samples: it connects the input to a small internal capacitor and waits until that capacitor has charged to the input voltage. A source with a higher output resistance (a big potentiometer) charges it more slowly and needs a longer sampling time. Then it converts. The total is the sampling time plus a fixed conversion time that depends on the resolution. We will pick a long sampling time, 64.5 ADC clock cycles, because speed does not matter here and accuracy does.

Tip. Because VREF+ is the 3.3 V supply, any noise or drop on that rail shows up in your readings. The chip also has an internal reference buffer (VREFBUF) for when you need a steadier reference.

3

Trap 1: the ADC has no clock yet

Three clock steps are needed, and this is where most first attempts fail silently.

  1. Bus clock. ADC1 and ADC2 share one enable bit: ADC12EN in RCC_AHB1ENR (ADC3 is on a different bus). Port C also needs GPIOCEN, although we leave PC0 in analog mode.
  2. Kernel clock source. The ADC runs from an asynchronous kernel clock chosen by ADCSEL in RCC_D3CCIPR. The reset value 00 selects pll2_p_ck, and PLL2 is switched off after reset, so the ADC would never get a clock. Pick 10, per_ck. The source of per_ck is CKPERSEL in RCC_D1CCIPR, and its reset value 00 is the 64 MHz internal oscillator (HSI), which is running after reset.
  3. Divider. PRESC in ADCx_CCR divides the kernel clock before it reaches the ADC. With PRESC = 0111 it divides by 16, which gives 4 MHz. Leave CKMODE = 00 (asynchronous mode); PRESC only works in that mode.

Why only 4 MHz? The ADC can run much faster (the datasheet allows 20 MHz, or 36 MHz with boost), but the BOOST field in ADC_CR must match the ADC clock. For a clock at or below 6.25 MHz the correct setting is 00, which is the reset value, so we do not touch it. This manual describes two silicon revisions (V and Y) with slightly different clock diagrams; 4 MHz is safely inside the limits of both, even if your chip applies an extra divide-by-2.

4

Trap 2: wake up, calibrate, enable

After reset the ADC is in deep power-down to save leakage (DEEPPWD = 1 in ADC_CR; the reset value of ADC_CR is 0x2000 0000). The manual's sequence is:

  1. Clear DEEPPWD.
  2. Set ADVREGEN, the ADC's own voltage regulator, and wait for its start-up time (the datasheet says at most 10 µs; the software must do the waiting). Our loop of 20 000 empty iterations is far longer than that at any clock speed.
  3. Calibrate: choose single-ended input (ADCALDIF = 0), also run the linearity calibration (ADCALLIN = 1), then set ADCAL and wait until hardware clears it. The datasheet gives about 165 000 ADC clock cycles for offset plus linearity, which is tens of milliseconds at 4 MHz. Calibration removes chip-to-chip offset errors and must be done before the ADC is enabled.
  4. Enable: clear ADRDY by writing 1 to it, set ADEN, wait until ADRDY is 1.

Many ADC_CR bits can only be written in a certain state (for example ADCALLIN only while the ADC is disabled). Writing the whole register in one go, as in the code below, keeps you out of trouble; do not use |= on this register unless you know why.

5

Trap 3: select the channel

Three registers describe what to convert:

  • ADC_SQR1 is the sequence: the field L = 0 means "one conversion", and SQ1 holds the channel number of the first (only) conversion: 10.
  • ADC_SMPR2 holds the sampling time of channels 10 to 18 (ADC_SMPR1 is for channels 0 to 9). The field SMP10 = 101 means 64.5 cycles.
  • ADC_PCSEL is the H7-specific one: the channel preselection. Every channel you put in the sequence must also have its bit set here (bit 10 for channel 10). It controls an analog switch inside the pin's I/O cell that is too slow to follow the ADC's own input multiplexer, so it has to be switched on ahead of time. If you forget it, the manual gives no guarantee for the result: the conversion still completes, but you can get wrong values, and nothing reports an error.

The other settings stay at their reset values: 16-bit resolution, single conversion (CONT = 0), software trigger (EXTEN = 00), data right-aligned in ADC_DR.

6

Convert and read

Now the ADC is ready. Set ADSTART in ADC_CR to start one conversion. When it is done, hardware sets EOC (end of conversion) in ADC_ISR and the result sits in ADC_DR. **Reading ADC_DR clears EOC automatically**, so a read function can simply be: start, wait for EOC, read.

Then convert to millivolts with integer maths: mV = raw × 3300 / 65535. The largest product is 65 535 × 3300 ≈ 216 million, which fits in 32 bits.

The program below prints two numbers every 200 ms. Put it into the same main.c as the UART guide's uart3_init() and __io_putchar(), open the terminal, and turn the potentiometer. At one end you should see about 0, at the other end about 65 000 and 3 300 mV.

#include <stdio.h>

/* Paste below the UART guide's code (same file): uart3_init() and __io_putchar() are used here. */

static void adc1_init(void)
{
    /* 1. clocks: bus clock of ADC1/2, kernel clock source, divider */
    RCC->AHB4ENR |= RCC_AHB4ENR_GPIOCEN;
    RCC->AHB1ENR |= RCC_AHB1ENR_ADC12EN;
    (void)RCC->AHB1ENR;
    RCC->D3CCIPR = (RCC->D3CCIPR & ~RCC_D3CCIPR_ADCSEL_Msk)
                 | RCC_D3CCIPR_ADCSEL_1;               /* ADCSEL = 10: per_ck (= HSI 64 MHz at reset) */
    ADC12_COMMON->CCR = (ADC12_COMMON->CCR & ~(ADC_CCR_CKMODE_Msk | ADC_CCR_PRESC_Msk))
                      | (7U << ADC_CCR_PRESC_Pos);     /* async clock mode, PRESC = 0111: /16 -> 4 MHz */
    /* PC0 is already in analog mode (MODER = 11 is the reset value) */

    /* 2. leave deep power-down, start the ADC regulator, wait for it */
    ADC1->CR = 0U;                                     /* DEEPPWD = 0 (and everything else 0) */
    ADC1->CR = ADC_CR_ADVREGEN;
    for (volatile uint32_t i = 0; i < 20000U; i++) { } /* >= 10 us regulator start-up */

    /* 3. calibrate: single-ended, with linearity calibration */
    ADC1->CR = ADC_CR_ADVREGEN | ADC_CR_ADCALLIN;      /* ADCALDIF = 0 */
    ADC1->CR = ADC_CR_ADVREGEN | ADC_CR_ADCALLIN | ADC_CR_ADCAL;
    while (ADC1->CR & ADC_CR_ADCAL) { }                /* tens of ms */

    /* 4. enable and wait for ADRDY */
    ADC1->ISR = ADC_ISR_ADRDY;                         /* clear ADRDY by writing 1 */
    ADC1->CR  = ADC_CR_ADVREGEN | ADC_CR_ADEN;
    while (!(ADC1->ISR & ADC_ISR_ADRDY)) { }

    /* 5. channel 10: preselect, put it in the sequence, long sampling time */
    ADC1->PCSEL = ADC_PCSEL_PCSEL_10;                  /* the H7 trap: without it the result is wrong */
    ADC1->SQR1  = (10U << ADC_SQR1_SQ1_Pos);           /* L = 0: one conversion; SQ1 = channel 10 */
    ADC1->SMPR2 = (ADC1->SMPR2 & ~ADC_SMPR2_SMP10_Msk)
                | (5U << ADC_SMPR2_SMP10_Pos);         /* SMP10 = 101: 64.5 cycles */
}

static uint32_t adc1_read(void)
{
    ADC1->CR |= ADC_CR_ADSTART;                        /* one conversion (software trigger) */
    while (!(ADC1->ISR & ADC_ISR_EOC)) { }
    return ADC1->DR;                                   /* reading DR also clears EOC */
}

int main(void)
{
    uart3_init();
    adc1_init();

    for (;;) {
        unsigned raw = (unsigned)adc1_read();
        unsigned mv  = raw * 3300U / 65535U;
        printf("raw = %5u   %4u mV\n", raw, mv);
        for (volatile uint32_t i = 0; i < 4000000U; i++) { }   /* crude delay, tune it */
    }
}

Tip. In the HAL tab the lines after adc1_init(); are the body of main(): put adc1_init() and adc1_read() above it.

7

Make it yours

The reading will jitter by some counts even with a steady knob. That is normal: it is noise from the supply, the wires and the ADC itself. Try:

  • Average 16 samples and print the average. How many counts does the jitter shrink to? Add a 100 nF capacitor from A0 to GND and see what changes.
  • Use the number: map the potentiometer to the PWM duty cycle from the PWM guide, so the knob dims the LED.
  • Switch to continuous conversion (CONT = 1 in ADC_CFGR) and read ADC_DR whenever you like, or let the ADC raise an interrupt on EOC.
  • Read the internal temperature sensor: it is a channel of ADC3, enabled by TSEN in ADCx_CCR. The chapter's connectivity table shows which channel.
  • Lower the resolution with RES in ADC_CFGR and see how the number of steps changes.

Common mistakes

  • No ADCSEL change: the kernel clock is pll2_p_ck and PLL2 is off. Without a clock the ADC cannot calibrate or become ready, so expect the program to hang in the ADCAL or ADRDY loop.
  • Skipping ADC_PCSEL: the manual requires it for every channel in the sequence. Without it the result is not reliable (typically wrong or stuck values), and nothing flags an error.
  • Starting calibration before the regulator has had its 10 µs, or with DEEPPWD still set: ADCAL is ignored.
  • Writing ADC_CR with |= at the wrong moment: some bits (ADEN, ADCAL, ADSTART) are "set-only" and only valid in certain states. Write the whole value as shown.
  • Setting ADSTART again while EOC is still set. Reading ADC_DR clears EOC, so always read the result before the next start.
  • Reading ADC_DR before EOC: you get the previous result.
  • Using the 5 V pin of the Arduino header for the potentiometer: the ADC input can only take up to VREF+ (about 3.3 V) and a higher voltage can damage the pin.
  • A high-resistance source (a 100 kΩ potentiometer) with a short sampling time: the reading drifts and depends on the previous channel. Use the longer SMP values, or a lower-resistance part.

Check yourself

Try to answer before opening. If you get stuck, the pages linked above have the answer.

The raw reading is 32768 and VREF+ is 3.3 V. What is the voltage?

About 1.65 V: 32768 / 65535 × 3.3 V ≈ 1.65 V. With the integer formula 32768 × 3300 / 65535 = 1650 mV.

Why is ADCSEL = 00 a trap on this chip?

00 selects the output of PLL2, and PLL2 is switched off after reset. The ADC therefore has no kernel clock and cannot calibrate or convert until you select a running source (per_ck, which comes from the 64 MHz HSI, or start PLL2 or PLL3).

You want faster conversions. Name two things you can change and the catch of each.

Use a shorter sampling time (SMPx): the catch is that a source with a high output resistance no longer charges the sampling capacitor in time, so the reading gets wrong. Or raise the ADC clock (a smaller PRESC): the catch is that BOOST in ADC_CR must be raised above 6.25 MHz, and the datasheet limits (20 MHz, or 36 MHz with boost) must be respected.

Reading list

Every page this guide sent you to, by document. Reading them in order is a good revision.

UM2488UM2488 STM32H745I/H750B-DK Discovery kit user manualp.17
MB1381MB1381 Discovery board schematic (H750XB variant)sheet 3sheet 4sheet 16
DS12556STM32H750xB datasheetp.53p.158
RM0433RM0433 reference manual (STM32H742/743/753/750)p.353p.411p.417p.453p.457p.913p.917p.923p.924p.930p.931p.932p.932p.933p.934p.936p.954p.970p.991p.996p.1001p.1010p.1017p.1020p.1024p.1035

Search next

Each of these opens the finder with pins, registers, schematic hits and document pages for the term.

Where to go next