From the physical world to a number
A weather station reports 18.4 °C. A bathroom scale says 61.2 kg. A phone knows which way up it is. Each of those numbers began as something that is not electrical at all — heat, force, gravity — and passed through a chain of conversions before a program could print it. Every link in the chain can add error, and the engineer's job is to know how much.
Sampling and the FFT treated sampling as mathematics: a signal, a sampling rate, aliasing. This lesson is about the hardware that does it, and everything around it: the sensors, the amplifiers in front of the converter, the converter's own architecture and limits, and the calibration that turns a code into a number you can defend.
Sensors: turning quantities into signals
Definition— Sensor, transducer, sensitivity
A sensor responds to a physical quantity (the measurand) with a change in an electrical property; a transducer converts energy from one form to another, and the word covers sensors and actuators alike. A sensor's sensitivity is the change in output per unit change of the measurand, its range the span it can measure, and its resolution the smallest change it can detect.
Five sensors cover a large share of real designs:
- Thermistor. A ceramic resistor whose resistance changes strongly with temperature. An NTC (negative temperature coefficient) thermistor of 10 kΩ at 25 °C might fall to 1.3 kΩ at 80 °C. A common model is the Beta equation, with in kelvin; more accurate is the three-term Steinhart–Hart equation. Thermistors are cheap and sensitive but nonlinear; platinum RTDs (100 Ω at 0 °C) are linear and stable, and thermocouples reach over 1,000 °C.
- Strain gauge. A zig-zag of thin metal foil glued to a part; when the part stretches by a fraction (the strain), the foil's resistance changes by , with a gauge factor GF of about 2. Strains are tiny, often below , so gauges sit in a Wheatstone bridge that outputs only the difference. A load cell in a kitchen scale is a metal beam with four gauges.
- MEMS accelerometer. A microscopic silicon proof mass on silicon springs, etched with comb-shaped electrodes. Acceleration deflects the mass by nanometres, changing the capacitance between combs by a tiny fraction of a picofarad, which an on-chip circuit measures. MEMS gyroscopes measure rotation with vibrating masses and the Coriolis force. They come with their own ADC and an I²C or SPI interface: the sensor is a small mixed-signal chip.
- Photodiode. A PN junction (from Semiconductors and diodes) in which absorbed photons create a current proportional to light power, roughly 0.4 to 0.6 A per watt for silicon in red and near-infrared light. The current is tiny, so a transimpedance amplifier — an op amp with a feedback resistor — turns it into a voltage : 2 µA through 1 MΩ gives 2 V.
- Hall sensor. A current through a thin semiconductor plate in a magnetic field is pushed sideways, giving a small Hall voltage proportional to . Hall sensors detect magnets (a laptop's lid, a motor's rotor position), measure current without touching the conductor, and sense position in joysticks and throttles.
Most sensors produce small, offset, noisy or high-impedance signals. Signal conditioning is the analogue circuitry that fixes them before conversion, mostly built from the amplifiers of Operational amplifiers:
- Amplify so the signal spans most of the ADC's input range, without clipping.
- Shift (offset) a signal that swings around zero into an ADC that accepts only 0 to .
- Filter, above all with an anti-aliasing low-pass filter that removes everything above half the sampling rate, because once a signal has aliased no software can tell it apart from a real one.
- Buffer a high-impedance source so the ADC's input does not load it.
- Protect the input against overvoltage and electrostatic discharge.
Example— A strain gauge needs an amplifier
A quarter bridge (one active gauge, three fixed resistors) excited by 3.3 V outputs approximately . At a strain of that is mV. A 12-bit ADC with a 3.3 V reference has steps of mV, so the whole signal is two codes. An instrumentation amplifier with a gain of 1,000 lifts it to 1.65 V, or a 24-bit sigma-delta converter with a built-in programmable-gain amplifier, as in most commercial scales, measures it directly. Either way the bridge's own excitation should be the ADC's reference, so that a drifting supply cancels.
Worked example: a thermistor thermometer
Put a 10 kΩ NTC thermistor ( K) at the bottom of a divider, a fixed 10 kΩ resistor at the top, and connect the midpoint to a 12-bit ADC whose reference is the same 3.3 V that feeds the divider. The ADC's code is then , and the supply voltage cancels out: a ratiometric measurement, immune to the supply's accuracy. The program tabulates the codes and the temperature change per code, and converts codes back to temperatures.
import math
R0, T0, B = 10_000.0, 298.15, 3950.0 # NTC thermistor: 10 kilohms at 25 C, beta 3950 K
R_FIXED = 10_000.0 # the divider's other resistor, from the reference to the ADC pin
BITS = 12
def thermistor_ohms(t_celsius):
t = t_celsius + 273.15
return R0 * math.exp(B * (1 / t - 1 / T0))
def adc_input(t_celsius):
"""The divider's output as a fraction of the reference: the ADC and the divider share it."""
r = thermistor_ohms(t_celsius)
return r / (R_FIXED + r)
def adc_code(t_celsius):
return math.floor(2**BITS * adc_input(t_celsius)) # an ideal 12-bit ADC
def code_to_celsius(code):
r = R_FIXED * (code + 0.5) / (2**BITS - code - 0.5) # +0.5: the middle of the code's interval
return 1 / (1 / T0 + math.log(r / R0) / B) - 273.15
print(f"{'T (C)':>6} {'R (ohm)':>9} {'V at 3.3 V':>11} {'code':>6} {'C per code':>11}")
for t in range(-20, 101, 20):
slope = (adc_input(t + 0.01) - adc_input(t - 0.01)) / 0.02 * 2**BITS # codes per degree
print(f"{t:>6} {thermistor_ohms(t):>9.0f} {3.3 * adc_input(t):>9.3f} V {adc_code(t):>6} {1 / abs(slope):>11.3f}")
print()
for code in (3000, 2048, 1000, 300):
print(f"code {code:4} -> {code_to_celsius(code):6.2f} C")The resolution is finest, about 0.022 °C per code, near room temperature, where the thermistor equals the fixed resistor and the divider is steepest, and is six times coarser at 100 °C. That is why the fixed resistor is chosen to match the thermistor at the temperature you care most about. Resolution is not accuracy, though: a typical thermistor is specified to ±1% in resistance, about ±0.25 °C near 25 °C, and the Beta model itself is off by a few tenths of a degree away from its reference points. A code that changes every 0.022 °C still has to be calibrated to mean anything at that level.
How an ADC works: four architectures
Definition— Analog-to-digital converter
An analog-to-digital converter (ADC) samples an input voltage at instants set by a clock and outputs, for each sample, an -bit code such that the input lies within the code's interval: for an ideal converter, where is the least significant bit, the width of one step. A sample-and-hold circuit freezes the input while it is converted.
Four architectures dominate, trading speed against resolution and power:
| Architecture | How it works | Typical resolution and speed | Where you meet it |
|---|---|---|---|
| SAR (successive approximation) | binary search: one comparator and an internal DAC decide one bit per clock | 8–18 bits, up to a few MS/s (tens of MS/s in fast parts) | inside almost every microcontroller; general data acquisition |
| Sigma-delta () | a 1-bit (or few-bit) converter running far faster than needed, with feedback that pushes its error to high frequencies, then a digital filter | 16–32 bits, from a few S/s to a few MS/s | weigh scales, precision instruments, audio |
| Flash | comparators compare the input against every threshold at once | 4–8 bits, up to several GS/s | the fastest oscilloscopes and radar, often as a building block |
| Pipelined | a chain of stages, each resolving a few bits and passing on the amplified remainder | 10–16 bits, tens to hundreds of MS/s, a few cycles of delay | software-defined radio, ultrasound imaging, communications |
The fastest converters of 2026, inside the receivers of data-centre links running at over 200 Gbit/s per lane, interleave dozens of SAR converters in time to sample at more than 100 GS/s. Murmann's ADC performance survey tracks where the frontier lies.
The program runs both of the commonest architectures. The SAR is ten comparisons. The first-order sigma-delta modulator is stranger: each clock it outputs a single bit, and an integrator accumulates the difference between the input and what has been output so far, so the bits' running average is forced to follow the input.
def sar_convert(vin, vref, bits, verbose=False):
"""Successive approximation: decide one bit per clock, most significant first."""
code = 0
for bit in reversed(range(bits)):
trial = code | (1 << bit) # tentatively set this bit
v_dac = vref * trial / 2**bits # the internal DAC's voltage for the trial code
keep = vin >= v_dac # one comparator decision
if keep:
code = trial
if verbose:
print(f" bit {bit}: try {trial:010b} = {v_dac:.4f} V -> {'keep' if keep else 'clear'}")
return code
vin, vref = 1.234, 3.3
code = sar_convert(vin, vref, 10, verbose=True)
print(f"10-bit SAR result: {code} = {code:010b}, i.e. {vref * code / 1024:.4f} V to {vref * (code + 1) / 1024:.4f} V\n")
def sigma_delta(x, n):
"""First-order sigma-delta modulator for an input 0 <= x <= 1 (as a fraction of the reference).
Each clock it outputs one bit; the integrator accumulates the error between input and output."""
integrator, bits = 0.0, []
for _ in range(n):
bit = 1 if integrator >= 0 else 0
integrator += x - bit # feedback: subtract what was output
bits.append(bit)
return bits
x = vin / vref
stream = sigma_delta(x, 4096)
print("input as a fraction of the reference:", round(x, 6))
print("first 40 output bits:", "".join(map(str, stream[:40])))
for n in (16, 64, 256, 1024, 4096):
estimate = sum(stream[:n]) / n
print(f"average of {n:4} bits = {estimate:.6f} error {abs(estimate - x):.6f} (bound 1/n = {1 / n:.6f})")Theorem— The first-order sigma-delta average converges
For a constant input , the fraction of ones among the first output bits of the modulator above differs from by less than .
Proof
Let be the integrator after steps, with . If the bit is 1 and ; otherwise the bit is 0 and . By induction for every : a non-negative value in moves down into , and a negative value in moves up into . Summing the updates, , so .
∎
Resolution, quantisation noise and ENOB
An ideal -bit converter rounds every input to its code, so it makes an error between and LSB. For a busy signal the error behaves like random noise spread evenly over that interval.
Theorem— Quantisation noise and the ideal SNR
If the quantisation error is uniformly distributed on , where is one LSB, its RMS value is . For a full-scale sine wave, the ideal signal-to-noise ratio of an -bit converter is then
Proof
The mean square of a uniform error is . A full-scale sine spans from peak to peak, so its amplitude is and its mean square is . The ratio is , and dB.
∎
Real converters fall short because of thermal noise, distortion and clock jitter, so datasheets quote the measured SINAD (signal to noise and distortion) and its translation into the effective number of bits, : the number of bits an ideal converter would need to be as good. The program checks the formula, shows what input noise does to ENOB, and then tests the popular trick of averaging many readings.
import numpy as np
def quantise(v, bits):
"""An ideal ADC for inputs in [-1, 1): find the code, then return the middle of its interval."""
lsb = 2 / 2**bits
codes = np.clip(np.floor(v / lsb), -2**(bits - 1), 2**(bits - 1) - 1)
return (codes + 0.5) * lsb
N = 4096
n = np.arange(N)
x = 0.999 * np.sin(2 * np.pi * 127 * n / N) # a near-full-scale sine, 127 whole cycles
print("bits SNR measured 6.02N + 1.76")
for bits in (6, 8, 10, 12, 14):
err = quantise(x, bits) - x
snr = 10 * np.log10(np.mean(x**2) / np.mean(err**2))
print(f"{bits:4} {snr:10.2f} dB {6.02 * bits + 1.76:10.2f} dB")
rng = np.random.default_rng(1)
bits = 12
lsb = 2 / 2**bits
noisy = x + rng.normal(0, 1.5 * lsb, N) # analog noise of 1.5 LSB rms in front of the ADC
err = quantise(noisy, bits) - x
sinad = 10 * np.log10(np.mean(x**2) / np.mean(err**2))
print(f"\n12-bit ADC with 1.5 LSB of input noise: SINAD {sinad:.2f} dB, ENOB {(sinad - 1.76) / 6.02:.2f} bits")
print("\nAveraging m readings of a constant input (rms error over 2000 trials, in LSB):")
print(" m no noise 0.5 LSB noise")
true = 100.3 * lsb
for k in range(0, 5):
m = 4**k
row = []
for sigma in (0.0, 0.5):
readings = quantise(true + rng.normal(0, sigma * lsb, (2000, m)), bits)
estimate = readings.mean(axis=1)
row.append(np.sqrt(np.mean((estimate - true)**2)) / lsb)
print(f"{m:7} {row[0]:10.4f} {row[1]:14.4f}")The formula holds to within a fraction of a decibel from 8 bits up. Input noise of 1.5 LSB RMS costs this 12-bit converter 2.4 bits, leaving an ENOB of 9.6, which is why a 12-bit ADC on a noisy microcontroller board often behaves like a 9- or 10-bit one.
The averaging table holds the lesson's most useful surprise. With a perfectly clean input of 100.3 LSB, every reading is the same code, and averaging 256 of them gives exactly the same answer, 0.2 LSB off. With half an LSB of random noise added, each reading is worse, but the noise makes readings land on neighbouring codes in the right proportions, and the average converges: every fourfold increase in readings halves the error, one extra bit per factor of four, because the standard deviation of a mean of independent readings falls as (Lumenary Math's Statistics proves it). This is oversampling with dither: to gain bits, average samples, which needs a sampling rate times higher than the signal requires, and enough noise, about half an LSB or more, to decorrelate the quantisation error. Some designs add the noise deliberately.
The sampling rate itself must exceed twice the highest frequency present, after the anti-aliasing filter, and in practice it is several times higher, because real filters roll off gradually. A microcontroller ADC sampling a thermistor ten times a second is limited by everything except speed; one digitising audio at 48 kHz needs a filter that is flat to 20 kHz and deep by 24 kHz, a sharp transition that is much easier to build digitally after an oversampling sigma-delta converter than in analogue circuitry before a SAR.
Back to analogue: DACs and PWM
A digital-to-analogue converter (DAC) runs the chain backwards: code in, voltage or current out. Three structures are common. An R-2R ladder uses only two resistor values; each bit switches its branch between the reference and ground, and the ladder's halving at every node weights bit by . A resistor string taps a chain of equal resistors, inherently monotonic but large for many bits. Current-steering DACs switch weighted current sources and reach GS/s for radio transmitters. Many microcontrollers include a 12-bit DAC.
If yours does not, a timer's pulse-width modulation (PWM) output and a resistor and capacitor make a cheap DAC. A PWM signal with duty cycle is high for a fraction of each period , so its average is . An RC low-pass filter with time constant much longer than passes the average and attenuates the switching. While the output is high, the capacitor charges with current about for a time , so the peak-to-peak ripple is approximately
largest at . The resolution is set by the timer: with a 64 MHz timer clock and 1,024 counts per period (10 bits), the PWM frequency is 62.5 kHz.
The simulation solves the RC circuit exactly, period by period, for two filters, and also measures how long each takes to settle after a step.
import math
VDD = 3.3 # PWM high level, volts
F_CLK, BITS = 64e6, 10 # timer clock and PWM resolution
T = 2**BITS / F_CLK # PWM period: 1024 timer ticks
print(f"PWM frequency {1 / T / 1e3:.1f} kHz, 1 LSB = {VDD / 2**BITS * 1e3:.2f} mV")
def rc_filtered_pwm(duty, tau, periods):
"""Exact response of a first-order RC low-pass to a PWM wave, period by period.
Returns the capacitor voltage at the end of each high and each low phase."""
v, highs, lows = 0.0, [], []
for _ in range(periods):
v = VDD + (v - VDD) * math.exp(-duty * T / tau) # charging towards VDD
highs.append(v)
v = v * math.exp(-(1 - duty) * T / tau) # discharging towards 0
lows.append(v)
return highs, lows
for r, c in [(10e3, 100e-9), (1e3, 100e-9)]:
tau = r * c
print(f"\nR = {r / 1e3:.0f} kilohm, C = {c * 1e9:.0f} nF: tau = {tau * 1e3:.1f} ms, cut-off {1 / (2 * math.pi * tau):.0f} Hz")
print(" duty average ripple (simulated) ripple (formula)")
for duty in (0.1, 0.25, 0.5, 0.9):
highs, lows = rc_filtered_pwm(duty, tau, periods=int(20 * tau / T))
ripple = highs[-1] - lows[-1]
approx = VDD * duty * (1 - duty) * T / tau
print(f" {duty:4.2f} {(highs[-1] + lows[-1]) / 2:8.3f} V {ripple * 1e3:12.2f} mV {approx * 1e3:16.2f} mV")
# settling: after a step from 0 to 50% duty, when is the mid-ripple voltage within 1 LSB of 1.65 V?
highs, lows = rc_filtered_pwm(0.5, tau, periods=int(20 * tau / T))
settle = next(i for i, (h, l) in enumerate(zip(highs, lows)) if abs((h + l) / 2 - VDD / 2) < VDD / 2**BITS)
print(f" after a step to 50% duty it settles within 1 LSB in {(settle + 1) * T * 1e3:.2f} ms")The formula matches the exact solution. With ms the ripple at 50% duty is 13.2 mV, about four LSBs of a 10-bit DAC, and a change of output takes 6.2 ms to settle; with ms it settles ten times faster but ripples ten times more. A single RC stage cannot have both. The fixes are a second RC stage or an active filter (ripple falls with the square of the ratio of PWM frequency to cut-off), or a higher PWM frequency with fewer bits. PWM's other weakness is that its accuracy is only as good as the supply, since the output swings between ground and . For many jobs — dimming an LED, setting a motor's speed, a slow control voltage — none of this matters, and the motor or the eye is the filter.
Calibration and the professional view
Every real chain has an offset (the reading at zero input is not zero) and a gain error (the slope is not exactly right), and many have nonlinearity too. Two-point calibration measures the raw reading at two known inputs and fits a straight line through them:
Example— Calibrating a kitchen scale
A load cell and a 24-bit ADC read 8,192 counts with nothing on the scale and 520,384 counts with a 5,000 g reference mass. The gain is g per count. A reading of 300,000 counts is then g. Firmware stores the two calibration constants in flash, and the "tare" button simply re-measures the offset. For a nonlinear sensor such as a thermistor, calibrate at three or more points and fit the Steinhart–Hart equation, or interpolate in a stored lookup table.
How good is the 5,000 g mass? Its maker calibrated it against a better one, which was calibrated against a better one still, in an unbroken chain that ends at a national metrology institute — NPL in the UK, NIST in the USA, PTB in Germany, NMIJ in Japan, NIM in China and their peers — and, through the BIPM, at the SI units themselves, which since 2019 have all been defined by fixed constants of nature. That chain, with a stated uncertainty at each link, is traceability, and it is what lets a pharmacy in Lagos and a lab in Seoul agree on a milligram.
The professional view. A converter's datasheet specifies far more than its bit count: offset and gain error, INL and DNL (integral and differential nonlinearity: how far the code transitions are from ideal, and whether any code is missing), SNR, SINAD, ENOB and SFDR (spurious-free dynamic range), all over temperature, with the test conditions defined by IEEE 1241. The precision of a system usually depends at least as much on the voltage reference as on the converter: a reference that drifts 50 ppm/°C moves a full-scale 16-bit reading by over three LSB per degree. Makers of converters and sensor front ends include Analog Devices and Texas Instruments (USA), STMicroelectronics (France and Italy), Infineon (Germany), Renesas (Japan), Bosch Sensortec (Germany) and TDK InvenSense (Japan and USA) for MEMS motion sensors, Sensirion (Switzerland) for humidity, Melexis (Belgium) for Hall sensors, and ams OSRAM (Austria) for optical sensors. More and more sensors are smart sensors: the transducer, conditioning, ADC, calibration constants and a digital bus in one package, talking over the interfaces of Buses and interfaces. Robots fuse dozens of them; Lumenary Robotics' sensing and Kalman filter lessons pick up the story.
Common misconceptions
Misconception
"A 16-bit ADC gives 16 accurate bits." It gives 16-bit codes. Noise, nonlinearity, the reference and the circuit around it decide how many of them mean anything; ENOB and the error budget tell you.
Misconception
"Averaging always adds resolution." Only if the readings differ: a perfectly clean input reads the same code every time and averaging changes nothing. It needs about half an LSB or more of random noise, and it removes only random error, never offset, gain error or drift.
Misconception
"Resolution is accuracy." The thermistor example resolves 0.02 °C but is accurate to only a few tenths of a degree without calibration. Resolution is the smallest change you can see; accuracy is how close the reading is to the truth.
Misconception
"The ADC measures volts." It measures the ratio of its input to its reference. With a reference that drifts, every reading drifts; with a ratiometric circuit, the supply's errors cancel.
Exercises
1. Sensors and data conversion
Warm-upHumanA 12-bit ADC has a 2.048 V reference. How large is one LSB, in microvolts?
2. Sensors and data conversion
CoreHumanA 14-bit ADC's datasheet gives a SINAD of 68.0 dB for a full-scale input. What is its effective number of bits, to the nearest whole bit?
3. Sensors and data conversion
CoreHumanA precision scale must resolve 1 part in a million of its full load. It needs only 10 readings per second. Which ADC architecture is the natural choice?
4. Sensors and data conversion
CoreHumanA 12-bit ADC's readings carry about one LSB of random noise. How many readings must be averaged to gain 3 extra bits of resolution, as the lesson's simulation suggests?
5. Sensors and data conversion
CoreHumanA microcontroller samples a vibration sensor at 1,000 samples per second with no anti-aliasing filter. The machine actually vibrates at 900 Hz. At what frequency, in hertz, does the vibration appear in the samples?
6. Sensors and data conversion
CoreComputationalImplement the logic of a SAR ADC. Write sar_convert(comparator, bits), where comparator(code) returns True when the (hidden) input voltage is at or above the internal DAC's voltage for code. Return the bits-bit code of the input, using exactly bits calls to comparator, as the hardware does: one comparison per bit, most significant first.
7. Sensors and data conversion
CoreComputationalWrite calibrate(raw, raw0, ref0, raw1, ref1), which converts a raw reading to engineering units using the straight line through two calibration points: raw reading raw0 at the known value ref0, and raw1 at ref1. (The starter forgets the offset.) Check it on the lesson's kitchen-scale example: calibrate(300000, 8192, 0.0, 520384, 5000.0) should be about 2848.6 g.
8. Sensors and data conversion
StretchHumanA PWM DAC uses a 10 kΩ resistor and a 100 nF capacitor, and its ripple is too large. Which change cuts the ripple by a factor of four without making it settle more slowly?
Further reading and resources
- ADC performance survey · Boris MurmannData on every ADC published at the major circuit conferences since 1997; the place to see the state of the art in speed, resolution and energy per conversion.
- Analog DevicesData-converter and sensor datasheets, application notes and tutorials from one of the largest makers.
- Texas InstrumentsData converters, sensor front ends and many free training courses on precision measurement.
- IEEE Standards AssociationPublishes IEEE 1241, the standard terminology and test methods for analog-to-digital converters.
- Bureau International des Poids et Mesures (BIPM)The international home of the SI units and the root of measurement traceability.