ADC
Resolution, sampling, noise, oversampling and DMA.
From a voltage to a number
An ADC (analog-to-digital converter) measures a voltage and returns an integer. Most microcontrollers have a SAR (successive-approximation) ADC: 10 to 16 bits, up to a few million samples per second, with a multiplexer in front so one converter serves many pins.
The basic relationship, for an N-bit ADC with reference voltage Vref:
code = Vin / Vref * (2^N - 1) Vin = code * Vref / (2^N - 1)
Strictly the ideal step is Vref / 2^N; using 2^N - 1 maps full scale exactly to Vref. The difference is one count, below the noise of most MCU ADCs.
Resolution is not accuracy
| Term | Meaning |
|---|---|
| Resolution | Number of bits: 12 bits = 4096 codes. One LSB at 3.3 V is 0.8 mV. |
| Offset error | The code at 0 V is not 0. |
| Gain error | The slope is wrong: full scale reads high or low. |
| INL / DNL | Integral and differential non-linearity: how far individual steps deviate. |
| ENOB | Effective number of bits once noise and distortion are counted. A "12-bit" MCU ADC typically gives 10 to 11 ENOB. |
And the biggest error source is often outside the ADC: the reference. If Vref is the 3.3 V supply with ±3% tolerance, every reading is ±3% no matter how many bits you have. For accurate measurements use a dedicated reference, or measure the internal reference channel (VREFINT, factory-calibrated) to calculate the true supply.
Sampling and the input circuit
A SAR ADC charges a small internal sampling capacitor through the source's impedance during the sampling time, then disconnects it and converts. If the source impedance is high (a sensor behind a 100 kΩ divider), the capacitor does not charge fully in the time allowed and readings come out low and channel-dependent.
Fixes: lengthen the sampling-time setting, lower the source impedance, or put a capacitor (for example 10 to 100 nF) right at the pin so it supplies the charge.
Sampling theory in one paragraph
To capture a signal you must sample at more than twice its highest frequency component (the Nyquist rate). Anything above half the sample rate does not disappear: it aliases, appearing as a false lower frequency. So an analog anti-aliasing filter (at minimum an RC low-pass) must remove content above half the sample rate before the ADC. Digital filtering afterwards cannot undo aliasing.
Signal-to-noise ratio
An ideal N-bit converter's quantisation noise limits SNR to about 6.02 * N + 1.76 dB: 74 dB for 12 bits. Real converters do worse, and ENOB is calculated backwards from the measured SINAD: ENOB = (SINAD - 1.76) / 6.02.
Oversampling and averaging
Averaging several samples reduces random noise. Averaging 4^k samples and shifting right by k gains k bits of resolution, if there is enough random noise (at least about 1 LSB) to dither the input between codes. With a perfectly quiet input, every sample is the same code and averaging gains nothing.
#include <stdio.h>
#include <stdint.h>
#define VREF_MV 3300u
#define FULL 4095u
static uint32_t to_mv(uint32_t code) { return (code * VREF_MV + FULL / 2) / FULL; }
int main(void) {
/* 16 noisy 12-bit samples of a signal sitting between codes 1241 and 1242. */
uint16_t s[16] = { 1241,1242,1241,1241,1242,1242,1241,1242,1241,1241,1242,1241,1242,1241,1241,1242 };
uint32_t sum = 0;
for (int i = 0; i < 16; i++) sum += s[i];
uint32_t code12 = sum / 16; /* plain average: still 12 bits */
uint32_t code14 = sum >> 2; /* 16 = 4^2 samples: 2 extra bits */
printf("single sample : %u -> %u mV\n", s[0], to_mv(s[0]));
printf("12-bit average : %u -> %u mV\n", code12, to_mv(code12));
printf("14-bit result : %u (= %u.%02u in 12-bit codes)\n", code14, code14 / 4, (code14 % 4) * 25);
return 0;
}
Many MCUs have hardware oversampling that does this without CPU time.
Calibration
- Run the ADC's built-in self-calibration after power-up (and after large temperature changes) as the reference manual describes; it removes most offset error.
- Use the factory VREFINT and temperature sensor calibration values stored in system memory.
- For product-level accuracy, do a two-point calibration in production (apply two known voltages, store gain and offset) and correct each reading:
corrected = (raw - offset) * gain.
Getting samples efficiently
| Method | CPU cost | Use |
|---|---|---|
| Software trigger + polling | High: CPU waits | Occasional single readings |
| Interrupt on end of conversion | One interrupt per sample | Low rates |
| Timer trigger + DMA | Almost none | Anything periodic: audio, control loops, waveform capture |
| Scan mode + DMA | Almost none | Several channels each period |
The standard design: a timer triggers conversions at an exact rate, DMA writes results into a circular buffer, and half-transfer and transfer-complete interrupts tell the CPU when each half is ready to process (double buffering). Timing jitter is then zero, which a software loop can never guarantee.
Pitfall: In scan mode the results land in the buffer in channel order. If one conversion is missed (an overrun), every later value shifts by one channel. Enable the overrun interrupt and restart the sequence when it fires.
Interview question: Your ADC readings are 5% low on one channel connected through a resistor divider. What do you check?
Answer: Source impedance versus sampling time first: a high-value divider cannot charge the ADC's sampling capacitor in the configured sample time, so readings are low. Increase the sampling time, use lower-value resistors, add a capacitor at the pin, or buffer with an op-amp. Then check the divider tolerance and the reference (measure VREFINT to get the true supply), and whether the ADC self-calibration was run.
Interview question: How would you sample four analog channels at exactly 1 kHz each with minimal CPU load?
Answer: Configure the ADC in scan mode over the four channels, triggered by a timer running at 1 kHz, so each trigger converts all four in sequence. Use DMA in circular mode into a buffer holding, say, two blocks of N scans, with half-transfer and transfer-complete interrupts. In each interrupt process the half that just filled while DMA fills the other. The CPU only wakes per block, the timing is set by hardware with no jitter, and an overrun interrupt catches lost samples.
Build it: calibrated soil moisture
This is step 3 of the module project: the soil probe that decides when the pump from step 1 runs.
Lab: Turn the soil probe into a moisture percentage
A capacitive soil probe is wired to PA4, ADC1 channel 4. It reads about 3000 counts in dry air and 1300 in water, so a wetter soil gives a lower reading. The pump will run below 30 %, so the number has to be right.
adc_init()powers the ADC on (ADON) for single conversions at 12 bits. The probe's output is high-impedance, so give channel 4 the longest sampling time: its 3 bits inSMPR2(bits 12 to 14) set to111.adc_read(ch)converts one channel: select it inSQR3, start withSWSTART, then wait forEOCbefore readingDR. IfEOChas not come after 1000 checks, return -1 rather than hang: a dead ADC must not freeze the greenhouse.soil_percent()takes 8 readings of channel 4 and averages them (sum / 8), to beat the noise from the pump motor. An average above 4000 or below 100 means the probe is disconnected or shorted: return -1. Otherwise return(3000 - avg) * 100 / (3000 - 1300), limited to 0 to 100.
Going deeper
Interview question: How would you design the soil-moisture measurement of a smart greenhouse controller?
Answer: Choose a capacitive probe (resistive ones corrode), power it only while sampling to save energy and slow electrolysis, and read it against a stable reference. Calibrate each probe at install (dry and wet), store the calibration with a CRC, average or median-filter several samples, and treat readings outside the calibrated range as a sensor fault rather than a moisture value.
Interview question: What is the difference between a SAR ADC and a delta-sigma ADC?
Answer: A successive-approximation ADC converts each sample by a binary search against an internal DAC in a fixed number of steps, giving 10 to 16 bits at up to a few megasamples per second with low latency; most MCU ADCs are SAR. A delta-sigma ADC oversamples heavily with a 1-bit modulator and digitally filters, giving 16 to 24 bits of resolution at lower rates with built-in anti-aliasing, ideal for audio, weighing and precision sensing, but with filter latency.
Interview question: How do you measure the MCU's own supply voltage with its ADC?
Answer: Convert the internal reference channel VREFINT, whose voltage the vendor measures at the factory and stores in system memory as a calibration value. Since reading = VREFINT × full_scale / VDDA, solve for VDDA = VREFINT_CAL × VDDA_cal / reading (using the factory calibration voltage). That gives the true supply, which also lets you correct other readings for supply variation and estimate battery level.
Explain it: In your own words, explain why a 12-bit ADC does not necessarily give 12 bits of accuracy.
Answer: Twelve bits is the resolution: the number of distinct codes. Accuracy depends on everything else in the chain: noise on the input and inside the converter, which typically makes the last bit or two random, offset and gain errors, non-linearity between codes, and above all the accuracy of the reference voltage, since every reading is a fraction of it. A supply reference that is only accurate to 3 percent limits accuracy to about 5 bits regardless of resolution. Effective number of bits and calibration describe what you really get.