---
title: "Project: a SAR ADC with capacitor mismatch"
heading: A behavioral model, its DNL and INL by the histogram test, and its ENOB by FFT
eyebrow: S2 · Lesson 53 · Project: a SAR ADC with capacitor mismatch
xp: 80
---

::: hook
A successive-approximation converter is a capacitor DAC, a comparator and a little logic doing a binary search. Its accuracy is the DAC's: each bit's capacitor should be exactly twice the next, and random mismatch (lesson 34) makes them not quite. In this project you'll build a behavioral model of a 10-bit SAR ADC with random capacitor mismatch, then measure it the way a lab would. A slow ramp and a histogram of output codes give the DNL and INL. A coherently sampled sine and an FFT give the SINAD and effective number of bits. Then you can see how much matching a design needs.
:::

::: predict
## A 10-bit SAR ADC's MSB capacitor is 2 LSB larger than it should be, and everything else is perfect. Where does its worst DNL appear?

- [ ] At code 0
- [ ] Spread evenly over all codes
- [x] At the midscale transition, where the MSB first turns on
- [ ] At the top code

::: reveal
At midscale. Every code below 512 uses only the smaller capacitors; every code from 512 up adds the MSB. An MSB that's too large makes the jump from 511 to 512 happen 2 LSB late, so code 511 is 2 LSB too wide: DNL = +2 there. The same error shows as an INL bow of ±1 LSB, and it costs about 0.8 effective bits. Mismatches in smaller capacitors show up at the quarter-scale and eighth-scale transitions, more weakly.
:::
:::

::: nameit
## The model

- **Capacitor DAC:** bit k (k = 0 for the LSB) has a capacitor of $2^k$ unit capacitors, each with independent relative mismatch σ, so its weight is $w_k = 2^k + \sigma\sqrt{2^k}\,\varepsilon_k$ with $\varepsilon_k$ standard normal. A dummy unit capacitor $1 + \sigma\varepsilon_d$ completes the array, and the total is $C_T = \sum w_k + w_d$.
- **DAC level** for a code with bits $b_k$: $V = V_\text{ref}\frac{\sum b_kw_k}{C_T}$.
- **Binary search:** start from code 0; for k from N − 1 down to 0, try setting bit k, and keep it if $v_\text{in}$ ≥ the DAC level of the trial code. Vectorize over an array of inputs.

## The histogram test

Feed a slow, uniform ramp across full scale, many samples per code, and count how many samples land in each code (dropping the two end codes, which collect out-of-range inputs). Then

$$\text{DNL}_c = \frac{\text{count}_c}{\text{mean count}} - 1, \qquad \text{INL}_c = \sum_{j \leq c}\text{DNL}_j$$

with the INL's end-point straight line removed.

## The sine test

Sample a sine of amplitude just under full scale with an integer, odd number of cycles in the record (coherent sampling, so no window is needed), convert, and take the FFT of the codes. SINAD is the signal bin's power over everything else except DC; $\text{ENOB} = \frac{\text{SINAD} - 1.76}{6.02}$.

## What you'll write

1. `make_dac(N, sigma, seed=1)` returning `(w, total)`, and `sar(vin, w, total, vref=1.0)` returning integer codes.
2. `dnl_inl(w, total, per_code=64)` returning `(dnl, inl)` arrays for codes 1 to $2^N - 2$.
3. `enob(w, total, samples=4096, cycles=127)` returning `(enob, sinad_dB)`.
:::

::: example
## What DNL and INL does a 10-bit DAC with its MSB 0.5 LSB heavy have?

::: solution
1. **Midscale transition.** The MSB's extra 0.5 LSB delays the midscale transition by 0.5 LSB, so code 511 is 1.5 LSB wide.
2. **DNL.** That makes DNL = +0.5 at code 511, and zero elsewhere.
3. **INL.** After removing the end-point line, the INL steps by 0.5 at midscale and so swings ±0.25 LSB.
4. **Check against the model.** The model's histogram test returns exactly that: DNL 0.5 at code 511, maximum INL 0.25.

**Answer:** DNL is +0.5 LSB at code 511 and zero elsewhere, and INL swings ±0.25 LSB.
:::
:::

::: example
## With unit mismatch of 0.5%, how big is a typical worst-case DNL for 10 bits?

::: solution
1. **Midscale spread.** The midscale transition swaps all 1023 unit capacitors' worth of bits, so its error has spread
   $$0.005\sqrt{1023} \approx 0.16\ \text{LSB}$$
   and it's usually the worst.
2. **Simulated arrays.** Across 200 random arrays the median worst DNL is 0.15 LSB.
3. **The tails.** The tails are long: one of those arrays drew an MSB error beyond 3σ and reached 0.57 LSB.
4. **Design consequence.** Production yield is set by those tails, so designers size unit capacitors (and therefore kT/C noise and power) for the mismatch spec at 3σ or more.

**Answer:** a typical worst-case DNL is about 0.15 LSB (a midscale spread of 0.16 LSB), though a rare array can reach 0.57 LSB.
:::
:::

::: check
kind: python

## Step 1. Write `make_dac` and the vectorized `sar`.

```python starter
import numpy as np, math

def make_dac(N, sigma, seed=1):
    rng = np.random.default_rng(seed)
    w = 2.0 ** np.arange(N)
    return w, w.sum() + 1

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    return np.zeros(len(vin), dtype=np.int64)

w, tot = make_dac(10, 0.0)
print(sar([0.0, 0.25, 0.5, 0.999], w, tot))
```

```python solution
import numpy as np, math

def make_dac(N, sigma, seed=1):
    rng = np.random.default_rng(seed)
    w = np.array([2.0**k + sigma * math.sqrt(2.0**k) * rng.standard_normal() for k in range(N)])
    dummy = 1 + sigma * rng.standard_normal()
    return w, w.sum() + dummy

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    N = len(w)
    code = np.zeros(len(vin), dtype=np.int64)
    for k in range(N - 1, -1, -1):
        trial = code | (1 << k)
        bits = (trial[:, None] >> np.arange(N)) & 1
        level = vref * (bits @ w) / total
        code = np.where(vin >= level, trial, code)
    return code

w, tot = make_dac(10, 0.0)
print(sar([0.0, 0.25, 0.5, 0.999], w, tot))
```

```python tests
import numpy as np
w, tot = make_dac(10, 0.0)
assert np.allclose(w, 2.0 ** np.arange(10)) and abs(tot - 1024) < 1e-12, "With no mismatch the weights are 1, 2, 4, ... 512 and the total 1024."
got = sar([0.0, 0.25, 0.5, 0.999], w, tot)
assert list(got) == [0, 256, 512, 1022], f"An ideal 10-bit SAR should give [0, 256, 512, 1022]; got {list(got)}."
v = (np.arange(4096) + 0.5) / 4096
assert np.array_equal(sar(v, w, tot), np.floor(v * 1024).astype(int)), "An ideal SAR is a floor quantizer."
d = np.array([make_dac(10, 0.01, seed=s)[0][9] - 512 for s in range(1500)])
assert abs(d.std() / (0.01 * np.sqrt(512)) - 1) < 0.1 and abs(d.mean()) < 0.03, "The MSB's error should have spread σ√512 and zero mean."
```

::: right
Right. The binary search over a weighted capacitor array reproduces an ideal quantizer exactly, and the weights carry mismatch that grows as the square root of each capacitor's size.
:::
:::

::: check
kind: python

## Step 2. Write `dnl_inl(w, total, per_code=64)` by the histogram test.

```python starter
import numpy as np, math

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    N = len(w); code = np.zeros(len(vin), dtype=np.int64)
    for k in range(N - 1, -1, -1):
        trial = code | (1 << k)
        bits = (trial[:, None] >> np.arange(N)) & 1
        code = np.where(vin >= vref * (bits @ w) / total, trial, code)
    return code

def dnl_inl(w, total, per_code=64):
    N = len(w); M = 2**N
    # ramp, histogram, drop the end codes, normalize, accumulate, remove end-point line
    return np.zeros(M - 2), np.zeros(M - 2)

w = 2.0 ** np.arange(10); w[9] += 0.5
d, i = dnl_inl(w, w.sum() + 1)
print(np.abs(d).max(), np.abs(i).max())
```

```python solution
import numpy as np, math

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    N = len(w); code = np.zeros(len(vin), dtype=np.int64)
    for k in range(N - 1, -1, -1):
        trial = code | (1 << k)
        bits = (trial[:, None] >> np.arange(N)) & 1
        code = np.where(vin >= vref * (bits @ w) / total, trial, code)
    return code

def dnl_inl(w, total, per_code=64):
    N = len(w); M = 2**N
    v = (np.arange(M * per_code) + 0.5) / (M * per_code)
    codes = sar(v, w, total)
    counts = np.bincount(codes, minlength=M)[1:-1].astype(float)
    dnl = counts / counts.mean() - 1
    inl = np.cumsum(dnl)
    inl = inl - np.linspace(inl[0], inl[-1], len(inl))
    return dnl, inl

w = 2.0 ** np.arange(10); w[9] += 0.5
d, i = dnl_inl(w, w.sum() + 1)
print(np.abs(d).max(), np.abs(i).max())
```

```python tests
import numpy as np
w = 2.0 ** np.arange(10)
d, i = dnl_inl(w, w.sum() + 1)
assert len(d) == 1022 and np.abs(d).max() < 1e-9 and np.abs(i).max() < 1e-9, "An ideal converter has zero DNL and INL."
w = 2.0 ** np.arange(10); w[9] += 0.5
d, i = dnl_inl(w, w.sum() + 1)
assert abs(d[510] - 0.5) < 0.03 and np.abs(np.delete(d, 510)).max() < 0.03, f"A 0.5 LSB heavy MSB makes code 511 0.5 LSB too wide; got DNL {d[510]:.3f} there."
assert abs(np.abs(i).max() - 0.25) < 0.03, f"Its INL should swing ±0.25 LSB; got {np.abs(i).max():.3f}."
w = 2.0 ** np.arange(10); w[9] += 2
d, i = dnl_inl(w, w.sum() + 1)
assert abs(d.max() - 2) < 0.05 and abs(np.abs(i).max() - 1) < 0.05, "A 2 LSB MSB error: DNL 2 at midscale, INL ±1."
```

::: right
Right. The histogram test turns a ramp into per-code widths, and an injected MSB error shows up exactly where and as big as it should.
:::
:::

::: check
kind: python

## Step 3. Write `enob(w, total, samples=4096, cycles=127)` by the coherent sine test.

```python starter
import numpy as np, math

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    N = len(w); code = np.zeros(len(vin), dtype=np.int64)
    for k in range(N - 1, -1, -1):
        trial = code | (1 << k)
        bits = (trial[:, None] >> np.arange(N)) & 1
        code = np.where(vin >= vref * (bits @ w) / total, trial, code)
    return code

def enob(w, total, samples=4096, cycles=127):
    # sine 0.5 + 0.499 sin(2π cycles n/samples), convert, FFT, SINAD, ENOB
    return 0.0, 0.0

w = 2.0 ** np.arange(10)
print(enob(w, 1024.0))
```

```python solution
import numpy as np, math

def sar(vin, w, total, vref=1.0):
    vin = np.atleast_1d(np.asarray(vin, float))
    N = len(w); code = np.zeros(len(vin), dtype=np.int64)
    for k in range(N - 1, -1, -1):
        trial = code | (1 << k)
        bits = (trial[:, None] >> np.arange(N)) & 1
        code = np.where(vin >= vref * (bits @ w) / total, trial, code)
    return code

def enob(w, total, samples=4096, cycles=127):
    n = np.arange(samples)
    v = 0.5 + 0.499 * np.sin(2 * np.pi * cycles * n / samples)
    c = sar(v, w, total).astype(float)
    X = np.abs(np.fft.rfft(c - c.mean()))**2
    sig = X[cycles]
    noise = X[1:].sum() - sig
    sinad = 10 * np.log10(sig / noise)
    return (sinad - 1.76) / 6.02, sinad

w = 2.0 ** np.arange(10)
print(enob(w, 1024.0))
```

```python tests
import numpy as np
e10, s10 = enob(2.0 ** np.arange(10), 1024.0)
assert abs(e10 - 9.987) < 0.02, f"An ideal 10-bit converter should measure about 9.99 effective bits; got {e10:.3f}."
e8, s8 = enob(2.0 ** np.arange(8), 256.0)
assert abs(e8 - 8.018) < 0.02, f"An ideal 8-bit converter should measure about 8.02; got {e8:.3f}."
w = 2.0 ** np.arange(10); w[9] += 2
e, s = enob(w, w.sum() + 1)
assert abs(e - 9.153) < 0.03, f"A 2 LSB MSB error should cost about 0.8 bits (9.15); got {e:.3f}."
```

::: right
Right. The sine test confirms the ideal converter at its resolution and shows the cost of mismatch in effective bits.
:::
:::

::: check
given: s = 0.2 | 0.5 | 1; N = 8 | 10 | 12
answer: s/100*sqrt(2^N - 1)
tolerance: 1%

## A {N}-bit SAR DAC uses unit capacitors with {s}% mismatch. What's the spread of its midscale DNL?

::: right
Right. $\sigma\sqrt{2^N - 1}$ = {answer} LSB.
:::

::: misses
- [s/100*sqrt(2^(N - 1))] The midscale step swaps all $2^N - 1$ units' worth of bits.
- [any] Not yet. Add the variances of every switched unit.
:::
:::

::: check
given: e = 0.5 | 1 | 2
answer: e/2
tolerance: 1%

## A SAR DAC's MSB is {e} LSB heavy. What's the peak INL after removing the end-point line?

::: right
Right. A step of {e} LSB at midscale becomes a ±{answer} LSB swing.
:::

::: misses
- [e] The end-point line splits the step: half above, half below.
- [any] Not yet. The INL steps by the error at midscale.
:::
:::

::: check
given: N = 8 | 12 | 16; f = 1 | 10 | 50
answer: (N + 1)*f
unit: MHz
tolerance: 0.1%

## A {N}-bit SAR ADC samples at {f} MS/s, spending one clock cycle sampling and one per bit. What internal clock does it need?

::: right
Right. $(N + 1)f_s$ = {answer} MHz.
:::

::: misses
- [N*f] Add the sampling cycle.
- [any] Not yet. One cycle per bit, plus one.
:::
:::

::: explain
## Why is a SAR converter's linearity set by its capacitor matching rather than its comparator?

::: model
A SAR converter compares the input with a sequence of DAC voltages and keeps or drops each bit. The comparator only has to say which of two voltages is larger; its offset shifts every decision by the same amount, which looks like a constant offset of the whole transfer curve, not a nonlinearity, and its noise adds random error to each conversion. The code thresholds themselves, where each output code begins and ends, are set entirely by the DAC's voltages, which come from capacitor ratios. If the capacitors aren't exactly binary weighted, the thresholds are unevenly spaced, and that uneven spacing is exactly what DNL and INL measure.
:::
:::

::: practice

::: check
given: s = 0.3 | 0.8; N = 9 | 11
answer: s/100*sqrt(2^N - 1)
tolerance: 1%

## Midscale DNL spread: {N} bits, {s}% units?

::: misses
- [any] $\sigma\sqrt{2^N - 1}$.
:::
:::

::: check
given: S = 50 | 56 | 60 | 62 | 68 | 72
answer: (S - 1.76)/6.02
tolerance: 0.5%

## ENOB from {S} dB SINAD?

::: misses
- [any] $(S - 1.76)/6.02$.
:::
:::

::: check
given: e = 0.5 | 0.8 | 1 | 1.5 | 2 | 3
answer: e/2
tolerance: 1%

## Peak INL from an MSB {e} LSB heavy?

::: misses
- [any] Half the step.
:::
:::
:::
