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.
- 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_PCSELandADC_SQR1, choose a sampling time, start a conversion and readADC_DR
- 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.
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.
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.
Trap 1: the ADC has no clock yet
Three clock steps are needed, and this is where most first attempts fail silently.
- Bus clock. ADC1 and ADC2 share one enable bit:
ADC12ENinRCC_AHB1ENR(ADC3 is on a different bus). Port C also needsGPIOCEN, although we leave PC0 in analog mode. - Kernel clock source. The ADC runs from an asynchronous kernel clock chosen by
ADCSELinRCC_D3CCIPR. The reset value00selects pll2_p_ck, and PLL2 is switched off after reset, so the ADC would never get a clock. Pick10, per_ck. The source of per_ck isCKPERSELinRCC_D1CCIPR, and its reset value00is the 64 MHz internal oscillator (HSI), which is running after reset. - Divider.
PRESCinADCx_CCRdivides the kernel clock before it reaches the ADC. WithPRESC=0111it divides by 16, which gives 4 MHz. LeaveCKMODE=00(asynchronous mode);PRESConly 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.
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:
- Clear
DEEPPWD. - 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. - Calibrate: choose single-ended input (
ADCALDIF= 0), also run the linearity calibration (ADCALLIN= 1), then setADCALand 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. - Enable: clear
ADRDYby writing 1 to it, setADEN, wait untilADRDYis 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.
Trap 3: select the channel
Three registers describe what to convert:
ADC_SQR1is the sequence: the fieldL= 0 means "one conversion", andSQ1holds the channel number of the first (only) conversion: 10.ADC_SMPR2holds the sampling time of channels 10 to 18 (ADC_SMPR1is for channels 0 to 9). The fieldSMP10=101means 64.5 cycles.ADC_PCSELis 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.
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 */
}
}#include <stdio.h>
ADC_HandleTypeDef hadc1;
static void adc1_init(void)
{
/* 1. kernel clock: ADCSEL = per_ck, per_ck = HSI (what RCC_CLKPSOURCE_HSI means) */
RCC_PeriphCLKInitTypeDef pc = {0};
pc.PeriphClockSelection = RCC_PERIPHCLK_ADC | RCC_PERIPHCLK_CKPER;
pc.AdcClockSelection = RCC_ADCCLKSOURCE_CLKP;
pc.CkperClockSelection = RCC_CLKPSOURCE_HSI;
if (HAL_RCCEx_PeriphCLKConfig(&pc) != HAL_OK) { Error_Handler(); }
__HAL_RCC_ADC12_CLK_ENABLE(); /* RCC_AHB1ENR.ADC12EN */
__HAL_RCC_GPIOC_CLK_ENABLE();
GPIO_InitTypeDef io = {0};
io.Pin = GPIO_PIN_0; /* PC0 = A0 */
io.Mode = GPIO_MODE_ANALOG;
io.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOC, &io);
/* 2. ADC itself. HAL_ADC_Init leaves deep power-down, enables the regulator
and waits for it (ADC_STAB_DELAY_US = 10 us), and picks BOOST from the clock. */
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV16; /* ADCx_CCR.PRESC = /16 */
hadc1.Init.Resolution = ADC_RESOLUTION_16B;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
hadc1.Init.LowPowerAutoWait = DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR;
hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
hadc1.Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE;
hadc1.Init.OversamplingMode = DISABLE;
if (HAL_ADC_Init(&hadc1) != HAL_OK) { Error_Handler(); }
/* 3. calibration (offset + linearity, single-ended): ADCAL */
if (HAL_ADCEx_Calibration_Start(&hadc1, ADC_CALIB_OFFSET_LINEARITY, ADC_SINGLE_ENDED) != HAL_OK) {
Error_Handler();
}
/* 4. channel: HAL sets ADC_PCSEL, ADC_SQR1 and ADC_SMPR2 for you */
ADC_ChannelConfTypeDef ch = {0};
ch.Channel = ADC_CHANNEL_10; /* PC0 = INP10 */
ch.Rank = ADC_REGULAR_RANK_1;
ch.SamplingTime = ADC_SAMPLETIME_64CYCLES_5;
ch.SingleDiff = ADC_SINGLE_ENDED;
ch.OffsetNumber = ADC_OFFSET_NONE;
ch.Offset = 0;
if (HAL_ADC_ConfigChannel(&hadc1, &ch) != HAL_OK) { Error_Handler(); }
}
static uint32_t adc1_read(void)
{
HAL_ADC_Start(&hadc1); /* enables the ADC the first time, then ADSTART */
HAL_ADC_PollForConversion(&hadc1, 10); /* waits for EOC, 10 ms timeout */
return HAL_ADC_GetValue(&hadc1); /* reads ADC_DR */
}
/* in main(), after HAL_Init(), SystemClock_Config() and uart3_init() */
adc1_init();
while (1) {
unsigned raw = (unsigned)adc1_read();
printf("raw = %5u %4u mV\n", raw, raw * 3300U / 65535U);
HAL_Delay(200);
}Tip. In the HAL tab the lines after adc1_init(); are the body of main(): put adc1_init() and adc1_read() above it.
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 inADC_CFGR) and readADC_DRwhenever you like, or let the ADC raise an interrupt on EOC. - Read the internal temperature sensor: it is a channel of ADC3, enabled by
TSENinADCx_CCR. The chapter's connectivity table shows which channel. - Lower the resolution with
RESinADC_CFGRand see how the number of steps changes.
Common mistakes
- No
ADCSELchange: the kernel clock ispll2_p_ckand PLL2 is off. Without a clock the ADC cannot calibrate or become ready, so expect the program to hang in theADCALorADRDYloop. - 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
DEEPPWDstill set:ADCALis ignored. - Writing
ADC_CRwith|=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
ADSTARTagain whileEOCis still set. ReadingADC_DRclearsEOC, so always read the result before the next start. - Reading
ADC_DRbeforeEOC: 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
SMPvalues, 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.
| UM2488 | UM2488 STM32H745I/H750B-DK Discovery kit user manual | p.17 |
| MB1381 | MB1381 Discovery board schematic (H750XB variant) | sheet 3sheet 4sheet 16 |
| DS12556 | STM32H750xB datasheet | p.53p.158 |
| RM0433 | RM0433 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.