Tuesday, October 13, 2026

ADC & DAC — 🎮

STM32F4 — ADC & DAC Complete Reference
STM32F411 Black Pill BTS EII — Chapter 3 Register-Level + HAL

ADC & DAC —
complete reference

From analog/digital fundamentals to bare-metal register programming. Every register, every field, with code examples and interactive demos.

ADC1 — 12-bit — 25 MHz — CH1

Fundamentals

The physical world — temperature, pressure, light, sound — varies continuously. Microcontrollers live in a world of integers. The ADC and DAC are the translators at the boundary.

🌊

Analog signal

Varies continuously between 0 V and Vref. Theoretically infinite precision.

🔢

Digital signal

A discrete integer: 0–4095 for 12-bit. Finite steps, finite precision.

🔄

ADC

Analog → Digital. Reads a voltage, returns a number.

🔉

DAC

Digital → Analog. Takes a number, outputs a voltage.

STM32F411 (Black Pill): ADC input range is strictly 0 V to 3.3 V — never apply more. 12-bit ADC1, but no DAC. Use PWM + RC filter as a DAC substitute.

Sampling & Shannon theorem

An ADC takes discrete snapshots of a continuous signal. The rate of these snapshots is the sampling frequency fe.

Shannon–Nyquist: To faithfully reconstruct a signal with highest frequency fmax, you must sample at least twice as fast: fe > 2 × fmax. In practice, aim for 5–10×.
ApplicationfmaxMin. fePractical fe
Human speech4 kHz8 kHz8–16 kHz
Hi-fi audio20 kHz40 kHz44.1 / 48 kHz
Sensor (100 Hz)100 Hz200 Hz1–10 kHz
PWM sensing (20 kHz)20 kHz40 kHz100 kHz+
Aliasing: Sample too slowly and a high-frequency signal masquerades as a lower one — car wheels appearing to spin backward in a film. Always low-pass filter the signal before the ADC if the source may contain frequencies above fe/2.

Resolution, quantum & conversion time

Quantum (1 LSB) = Vref ÷ 2n
Vmeasured = raw × Vref ÷ (2n − 1)
@ 3.3 V, 12-bit: 1 LSB = 0.806 mV  |  raw=2048 → 1.650 V
ResolutionLevelsLSB @ 3.3 VConv. cyclesRES[1:0]
12-bit ★4 0960.806 mV1200
10-bit1 0243.22 mV1001
8-bit25612.9 mV810
6-bit6452 mV611
Tconv = (Tsample + Nbits) ÷ fADC
56-cycle sample, 12-bit, fADC=25 MHz: (56+12)/25 MHz = 2.72 µs → ~367 k samples/s

ADC register map — ADC1 base 0x40012000

RegisterOffsetAddressRole
ADC_SR0x000x40012000Status flags: EOC, OVR, STRT…
ADC_CR10x040x40012004Resolution, SCAN, interrupts
ADC_CR20x080x40012008ADON, CONT, DMA, EOCS, ALIGN, SWSTART
ADC_SMPR10x0C0x4001200CSample time — channels 10–18
ADC_SMPR20x100x40012010Sample time — channels 0–9
ADC_SQR10x2C0x4001202CSequence length L + SQ13–SQ16
ADC_SQR20x300x40012030SQ7–SQ12
ADC_SQR30x340x40012034SQ1–SQ6 (first conversions)
ADC_DR0x4C0x4001204CConversion result (read-only)
ADC_CCR0x3040x40012304Common: prescaler, TSVREFE, VBATE

In CMSIS: ADC1 for the first nine, ADC1_COMMON for ADC_CCR.

ADC_CCR — Clock & common control offset 0x304

The ADC clock derives from PCLK2 (APB2) through a prescaler. It must not exceed 36 MHz. The default /2 is wrong at 100 MHz.

PLL → PCLK2
100 MHz
→
÷2 default
50 MHz ✗
→
÷4 use this
25 MHz ✓
ADCPRE [17:16]PrescalerfADC @ 100 MHzValid?
00/250 MHz✗
01/425 MHz✓
10/616.7 MHz✓
11/812.5 MHz✓
BitNamePurpose
23TSVREFEEnable internal temperature sensor (CH16) and VREFINT (CH17)
22VBATEEnable VBAT monitoring (CH18)
17:16ADCPREClock prescaler — see table above
ADC1_COMMON->CCR = (1 << 16);    // ADCPRE=01 → /4 = 25 MHz ✓
ADC1_COMMON->CCR |= (1 << 23);   // TSVREFE: enable CH16 temp + CH17 VREF

ADC_SR — Status register offset 0x00

Read-only flags set by hardware. Poll or test these bits to know the ADC's state.

5
OVR
4
STRT
3
JSTRT
2
JEOC
1
EOC
0
AWD
BitNameMeaningCleared by
1EOCEnd of Conversion — result ready in ADC_DRReading ADC_DR, or write 0
5OVROverrun — new result before old one was read; data lostWrite 0
4STRTRegular channel conversion startedWrite 0
0AWDAnalog watchdog threshold crossedWrite 0
while (!(ADC1->SR & (1 << 1)));          // wait EOC
if (ADC1->SR & (1 << 5)) ADC1->SR &= ~(1 << 5); // clear OVR

ADC_CR1 — Configuration 1 offset 0x04

26
OVRIE
25:24
RES[1:0]
23
AWDEN
11
DISCEN
8
SCAN
5
EOCIE
0:4
AWDCH
BitsNameMeaning
25:24RES[1:0]Resolution: 00=12 bit, 01=10, 10=8, 11=6
8SCAN1 = convert full sequence SQ1…SQ[L+1]. 0 = only SQ1.
5EOCIE1 = interrupt when EOC rises
26OVRIE1 = interrupt on overrun
11DISCENDiscontinuous mode — one channel per SWSTART trigger
ADC1->CR1 = (1 << 8);     // SCAN on, RES=00 (12-bit)
ADC1->CR1 |= (1 << 5);    // EOCIE — only when using interrupt mode

ADC_CR2 — Configuration 2 offset 0x08

30
SWSTART
29:28
EXTEN
11
ALIGN
10
EOCS
9
DDS
8
DMA
1
CONT
0
ADON
BitNameMeaning
0ADONADC on. Write 1 to power up. Wait ~3 µs startup before SWSTART.
1CONTContinuous: restart sequence immediately after completing it.
8DMAEnable DMA request after each conversion.
9DDSKeep DMA requests going after the last transfer (needed for loops).
10EOCS0 = EOC at end of sequence. 1 = EOC after each channel.
11ALIGN0 = right-aligned (normal). 1 = left-aligned (shifted left 4 bits).
30SWSTARTWrite 1 to start conversion by software. Auto-cleared by hardware.
CONTEOCSDMABehavior
00—Single sequence per SWSTART, one EOC at end
01—Single sequence, EOC after each channel — good for 2–3 ch polling
11—Continuous, EOC per channel — interrupt-driven acquisition
10DMA+DDSContinuous + DMA — array fills automatically, CPU free
EXTEN [29:28] must stay 00 (default) to use SWSTART. Setting an external trigger and also using SWSTART is undefined behavior.
ADC1->CR2 = (1 << 10);       // EOCS=1: EOC per channel
ADC1->CR2 |= (1 << 0);       // ADON: power up
// ... ~3 µs delay ...
ADC1->CR2 |= (1 << 30);      // SWSTART

ADC_SMPR1 & SMPR2 — Sample time 0x0C / 0x10

3 bits per channel control how long the internal capacitor charges. Longer = more accurate for high-impedance sources.

CodeCyclesWhen to use
0003Low impedance, fast scan
00115General purpose low-Z
01028Moderate impedance
01156Medium impedance (~10 kΩ)
10084Higher impedance (~50 kΩ)
101112High impedance
110144Very high impedance / NTC / LDR dividers
111480Required for internal temperature sensor (CH16)
RegisterChannelsBit position for channel n
SMPR2CH0 to CH9bits (3n+2):(3n) → shift n × 3
SMPR1CH10 to CH18shift (n − 10) × 3
ADC1->SMPR2 |= (4 << (1*3));        // CH1 → 84 cycles
ADC1->SMPR2 |= (4 << (4*3));        // CH4 → 84 cycles
ADC1->SMPR1 |= (7 << ((16-10)*3)); // CH16 (temp) → 480 cycles — required
Total time per channel = (sample cycles + RES cycles) ÷ fADC. Example: (84+12) ÷ 25 MHz = 3.84 µs. Total for 3 channels: 11.5 µs → ~87 k seq/s.

ADC_SQR1 / SQR2 / SQR3 — Sequence 0x2C / 0x30 / 0x34

These three registers define the conversion sequence: which channels, in what order. Each SQx slot is 5 bits and holds a channel number (0–18).

RegisterSlotsKey layout
ADC_SQR3SQ1–SQ6SQ1=bits[4:0], SQ2=[9:5], SQ3=[14:10], SQ4=[19:15], SQ5=[24:20], SQ6=[29:25]
ADC_SQR2SQ7–SQ12SQ7=bits[4:0], SQ8=[9:5] … same pattern
ADC_SQR1SQ13–SQ16 + LL[3:0]=bits[23:20] → number of conversions = L + 1
L = N − 1. To convert 3 channels, write L = 2, not 3. This is the most common initialization bug in bare-metal ADC code.
// 3 sensors on CH1, CH2, CH4
ADC1->SQR1 = (2 << 20);                              // L=2 → 3 conversions
ADC1->SQR3 = (1 << 0) | (2 << 5) | (4 << 10);    // SQ1=CH1, SQ2=CH2, SQ3=CH4

// Single channel CH1
ADC1->SQR1 = 0;    // L=0 → 1 conversion
ADC1->SQR3 = 1;    // SQ1=CH1

ADC_DR — Data register offset 0x4C

Read-only. Contains the most recent conversion result. Reading it clears EOC.

One slot only. Each new conversion overwrites the previous value. For multi-channel scans without DMA, read DR after every EOC before the next conversion finishes — or the OVR flag fires and data is lost.
uint16_t raw   = ADC1->DR;              // 0 to 4095 (12-bit right-aligned)
float    volts = raw * 3.3f / 4096.0f;  // approximate voltage

Bare-metal initialization — complete sequence

Three channels (CH1=PA1, CH2=PA2, CH4=PA4), 12-bit, software trigger, polling. No HAL.

/* 1. Enable peripheral clocks */
RCC->APB2ENR |= (1 << 8);           // ADC1EN
RCC->AHB1ENR |= (1 << 0);           // GPIOAEN

/* 2. PA1, PA2, PA4 → analog mode (MODER = 11) */
GPIOA->MODER |= (3<<2) | (3<<4) | (3<<8);

/* 3. ADC clock: PCLK2 / 4 = 25 MHz */
ADC1_COMMON->CCR = (1 << 16);

/* 4. CR1: SCAN on, 12-bit (RES=00 is default) */
ADC1->CR1 = (1 << 8);

/* 5. CR2: EOCS per channel */
ADC1->CR2 = (1 << 10);

/* 6. Sample time: 84 cycles for all three */
ADC1->SMPR2 = (4<<(1*3)) | (4<<(2*3)) | (4<<(4*3));

/* 7. Sequence: L=2 (3 convs), SQ1=CH1, SQ2=CH2, SQ3=CH4 */
ADC1->SQR1 = (2 << 20);
ADC1->SQR3 = (1<<0) | (2<<5) | (4<<10);

/* 8. Power on, wait startup */
ADC1->CR2 |= (1 << 0);
for (volatile int i=0; i<100; i++);  // ~3 µs @ 100 MHz

/* --- Reading the three channels --- */
ADC1->CR2 |= (1 << 30);               // SWSTART
uint16_t ch[3];
for (int i=0; i<3; i++) {
    while (!(ADC1->SR & (1<<1)));    // wait EOC
    ch[i] = (uint16_t)ADC1->DR;
}

Using the ADC with HAL (polling)

1

HAL_ADC_Start(&hadc1)

Triggers one conversion (or sequence in SCAN mode).

2

HAL_ADC_PollForConversion(&hadc1, timeout)

Blocks until EOC is set or timeout expires.

3

HAL_ADC_GetValue(&hadc1)

Returns ADC_DR — the raw value 0 to 4095.

4

HAL_ADC_Stop(&hadc1)

Clears ADON, returns ADC to idle.

uint16_t adc_read(void)
{
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1, 10);
    uint16_t raw = HAL_ADC_GetValue(&hadc1);
    HAL_ADC_Stop(&hadc1);
    return raw;
}

float v = adc_read() * 3.3f / 4095.0f;

// LED blink speed from potentiometer
while (1) {
    uint32_t d = 50 + (adc_read() * 450UL) / 4095; // 50–500 ms
    HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
    HAL_Delay(d);
}

Interrupt & DMA modes

ModeCPU usageBest for
PollingHigh — blocked while waitingSimple one-off reads
InterruptMedium — ISR overheadLow-rate sensors, precise timing
DMANear zeroHigh-speed, multi-channel, audio
/* Interrupt mode (HAL) */
volatile uint16_t g_raw;
HAL_ADC_Start_IT(&hadc1);           // fire and forget

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *h) {
    g_raw = HAL_ADC_GetValue(h);
    HAL_ADC_Start_IT(h);              // re-arm
}

/* DMA mode — 2 channels, array fills automatically */
uint16_t samples[2];
HAL_ADC_Start_DMA(&hadc1, (uint32_t*)samples, 2);
// samples[0] and samples[1] are updated continuously — just read them:
float v0 = samples[0] * 3.3f / 4095.0f;

Internal temperature sensor (CH16)

No external parts needed — the STM32F4 integrates a temperature sensor in the silicon itself, connected to ADC channel 16.

Accuracy ±5°C typical. Good for detecting thermal runaway, not for precision measurement. Enable TSVREFE in CCR, and use 480-cycle sample time (code 111 in SMPR1).
T (°C) = (Vsense − 0.76) ÷ 0.0025 + 25
Vsense at 25°C ≈ 0.76 V  |  Slope ≈ 2.5 mV/°C  |  Values from datasheet, varies chip-to-chip
ADC1_COMMON->CCR |= (1 << 23);        // TSVREFE: unlock CH16
ADC1->SMPR1 |= (7 << ((16-10)*3));    // 480 cycles on CH16
// configure SQR to put CH16 in sequence, then:
uint16_t raw  = adc_read();
float    v    = raw * 3.3f / 4095.0f;
float    temp = (v - 0.76f) / 0.0025f + 25.0f;

Noise reduction — averaging & oversampling

ADC outputs contain random noise of several LSB. Averaging N samples reduces it by √N.

σout = σraw ÷ √N
8 samples → noise ÷ 2.8×  |  64 samples → noise ÷ 8×
uint16_t adc_avg(uint8_t n) {
    uint32_t s = 0;
    for (uint8_t i=0; iadc_read();
    return (uint16_t)(s / n);
}
Oversampling trick: average 22k samples and right-shift k bits → gain k extra bits of effective resolution. 16 samples (shift 2) → 14-bit effective from a 12-bit ADC.

Measuring voltages above 3.3 V

Use a resistor divider to scale the voltage down to the ADC's range.

VADC = Vin × R2 ÷ (R1 + R2)
Vin = VADC × (R1 + R2) ÷ R2
R1=22 kΩ, R2=6.8 kΩ: Vin=12 V → VADC=2.83 V ✓  |  Max Vin ≈ 14 V
Impedance matters: R1+R2 should be ≤ 10 kΩ for the standard sample time. With larger resistors, increase the sample time (use code 110 or 111 in SMPR).

DAC — digital to analog

A DAC takes a number and outputs a proportional voltage: Vout = Vref × N ÷ 2n.

The STM32F411 (Black Pill) has no built-in DAC. The STM32F407 and F446 do. Options on the F411:
MethodPrecisionExtra partsSpeed
PWM + RC filter~8–10 eff. bitsR + C onlyLimited by RC cutoff
MCP4921 (SPI)12-bitIC + capsUp to 20 MHz SPI
MCP4725 (I²C)12-bitIC + capsUp to 400 kHz
STM32F407/F44612-bit nativeNoneDMA-capable

PWM + RC filter as DAC

A PWM signal with duty cycle D has an average voltage of Vref × D. A low-pass RC filter removes the switching ripple, leaving clean DC.

Duty cycle: 50% Vout ≈ 1.65 V
3.3 V 0 V avg
fPWM = ftimer ÷ ((PSC+1) × (ARR+1))
Vout = Vref × CCR ÷ (ARR+1)
100 MHz ÷ (1×1000) = 100 kHz, ARR=999, CCR=500 → 1.65 V after RC filter
/* Set PWM duty cycle — TIM3_CH1, ARR=999 */
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, 500); // 50% → 1.65 V
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, 250); // 25% → 0.825 V
__HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, 750); // 75% → 2.475 V
RC filter design: fc = 1/(2π·R·C) should be ≥ 10× below fPWM and ≥ 2× above your signal bandwidth. Example: fPWM=100 kHz → R=1 kΩ, C=15 nF → fc≈10.6 kHz.

Generating a sine wave with PWM

Build a 64-entry lookup table of sinusoidal CCR values and feed them one per timer tick. The RC filter sees a continuous sine wave.

uint16_t sine64[64];

/* Build once at startup */
for (int i=0; i<64; i++)
    sine64[i] = (uint16_t)(500.0f + 450.0f * sinf(2.0f*3.14159f*i/64));

/* Play — 1 value per ms → f = 1/(64×0.001) = 15.6 Hz */
for (int i=0; i<64; i++) {
    __HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_1, sine64[i]);
    HAL_Delay(1);
}
// Use TIM+DMA for audio-rate output without blocking main()
Frequency: fout = ftick ÷ Ntable. With 64 entries at 100 µs each: 156 Hz. At 22.7 µs (44 kHz DAC rate with 64 points): 687 Hz.

Quick quiz

⚡ Test yourself

1. ADC_DR is at which offset from ADC1 base 0x40012000?

2. To convert 3 channels, what value do you write into L (SQR1[23:20])?

3. PCLK2=100 MHz, default ADCPRE=00. What's the ADC clock — and is it valid?

4. Which CR2 bit starts a conversion by software?

5. The internal temperature sensor requires which SMPR sample time code?

6. EOCS=0 means EOC fires …

STM32F411 Black Pill — ADC & DAC Complete Reference  ·  BTS EII Chapter 3