---
title: "Project: an anti-aliasing filter for a data logger"
heading: Turn a converter's resolution into a filter, then build it from real parts
eyebrow: C4 · Lesson 28 · Project
xp: 80
---

::: hook
A data logger samples a vibration sensor 10,000 times a second with a 12-bit converter, and the vibrations of interest are below 1 kHz. Anything above 5 kHz would alias into the measurements and be impossible to remove afterward, so an analog filter must cut it first, far enough that aliases sit below the converter's own resolution. In this project you'll go from those three numbers to a filter order, to stage capacitors for a Sallen-Key cascade, and finally check the finished design's response from its component values, the way you'd verify a schematic before building it.
:::

::: play
- A Butterworth anti-aliasing filter's response (dB, log frequency) with its corner at the top of the signal band. The dashed line is the attenuation the converter needs; the marker is $f_s - f_\text{max}$, the first frequency that folds into the band.
- Raise the order until the curve passes below the line at the marker.
- Then try sampling faster: the gap widens, and a lower order does.
:::
:::

```sim plot
view: graph
x: f = 0.1..100 kHz log
y: A = -140..5 dB
slider: fm = 0.5..10 step 0.1 = 1 kHz
slider: fs = 5..100 step 1 = 10 kHz
slider: N = 8..16 step 1 = 12
slider: n = 1..8 step 1 = 4
plot: -10*log(1 + (f/fm)^(2*n)) | label: filter | samples: 600
plot: -(6.02*N + 1.76) + 0*f | label: converter's resolution | dashed | color: ch2
marker: x = fs - fm | label: first alias
readout: attenuation needed, dB = 6.02*N + 1.76 | digits: 4
readout: attenuation at the first alias, dB = 10*log(1 + ((fs - fm)/fm)^(2*n)) | digits: 4
```

::: predict
## The logger samples at 10 kHz with a 12-bit converter, and the signals go up to 1 kHz. What Butterworth order does the filter need, with its corner at 1 kHz?

- [ ] 2
- [ ] 3
- [x] 4
- [ ] 8

::: reveal
4. The first frequency that aliases into 0 to 1 kHz is 9 kHz, which must be 74 dB down ($6.02 \times 12 + 1.76$). A third-order filter gives 57 dB there, a fourth-order one 76 dB.
:::
:::

::: nameit
## The steps

1. **Attenuation needed:** aliases should sit below the converter's resolution, $A = 6.02N + 1.76$ dB for $N$ bits.
2. **Where:** the first frequency to fold into the signal band $0..f_\text{max}$ is $f_s - f_\text{max}$.
3. **Order:** with the Butterworth corner at $f_\text{max}$ (3 dB down there), $n \ge \frac{\log_{10}(10^{A/10} - 1)}{2\log_{10}\frac{f_s - f_\text{max}}{f_\text{max}}}$ (lesson 8).
4. **Stages:** each pole pair becomes an equal-resistor unity-gain Sallen-Key stage with $C_1 = \frac{2Q}{\omega_cR}$ and $C_2 = \frac{1}{2Q\omega_cR}$ (lesson 26); an odd order adds an RC section with $C = \frac{1}{\omega_cR}$.
5. **Check:** compute the response from the component values, $\frac{1}{s^2R^2C_1C_2 + 2sRC_2 + 1}$ per Sallen-Key stage and $\frac{1}{1 + sRC}$ per RC stage, and confirm the attenuation at $f_s - f_\text{max}$.

## Trade-offs

Putting the corner at $f_\text{max}$ loses 3 dB at the top of the band; moving it up a little preserves the band but needs a higher order. Sampling faster widens the gap: with oversampling and a digital filter afterward, the analog filter can be a simple second- or third-order one. Real designs also check the op amps' bandwidth and the capacitors' tolerance, since 5% capacitors shift each stage's Q and $f_0$.
:::

::: example
## Design the filter for 1 kHz signals sampled at 10 kHz by a 12-bit converter, with R = 10 kΩ.

::: solution
1. **Attenuation needed.**
   $$A = 74\ \text{dB at 9 kHz}$$
2. **Order.**
   $$n \ge 3.88$$
   so fourth order.
3. **Stage Qs.** Its pole pairs have Q = 0.541 and 1.307.
4. **Capacitors.** That gives stages of 17.2 nF with 14.7 nF, and 41.6 nF with 6.09 nF.
5. **Check.** Checked from those values, it's 76.3 dB down at 9 kHz.

**Answer:** a fourth-order filter: 17.2 nF with 14.7 nF (Q = 0.541) and 41.6 nF with 6.09 nF (Q = 1.307), 76.3 dB down at 9 kHz.
:::
:::

::: example
## The same signals sampled at 20 kHz: what does the filter need now?

::: solution
1. **First alias.** It's now at 19 kHz.
2. **Order.**
   $$\begin{aligned} n &\ge \frac{7.40}{2\log_{10}19} \\ &= 2.89 \end{aligned}$$
   so third order.
3. **Stages.** That's one Sallen-Key stage (Q = 1) plus an RC section.
4. **Check.** Checked, it's 76.7 dB down at 19 kHz.

**Answer:** a third-order filter, one Sallen-Key stage (Q = 1) plus an RC section, 76.7 dB down at 19 kHz.
:::
:::

::: check
given: N = 10 | 12 | 16
answer: 6.02*N + 1.76
unit: dB
tolerance: 0.5%

## How far down must aliases be for an {N}-bit converter?

::: right
Right. $6.02N + 1.76$ = {answer}.
:::

::: misses
- [any] Not yet. The converter's ideal SNR.
:::
:::

::: check
given: fs = 8 | 20 | 48; fm = 1 | 3
answer: fs - fm
unit: kHz
tolerance: 0.5%

## Signals up to {fm} kHz are sampled at {fs} kHz. Where is the first frequency that aliases into the signal band?

::: right
Right. $f_s - f_\text{max}$ = {answer}.
:::

::: misses
- [fs/2] Frequencies just above $f_s/2$ fold to just below it, outside a signal band that stops at $f_\text{max}$.
- [any] Not yet. Which input lands at $f_\text{max}$ after folding?
:::
:::

::: check
given: fm = 1 | 2; fs = 10 | 40; N = 12 | 16
answer: ceil(log(10^((6.02*N + 1.76)/10) - 1)/(2*log((fs - fm)/fm)))
tolerance: 0.1%

## Signals up to {fm} kHz, sampled at {fs} kHz by an {N}-bit converter. What Butterworth order, cornered at {fm} kHz, does the filter need?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. Steps 1 to 3.
:::
:::

::: check
given: fc = 1 | 4; R = 4.7 | 10
answer: 1/(2*pi*fc*1000*R*1000)*1e9
unit: nF
tolerance: 0.5%

## An odd-order design needs an RC section cornered at {fc} kHz with R = {R} kΩ. What capacitor?

::: right
Right. $\frac{1}{\omega_cR}$ = {answer}.
:::

::: misses
- [any] Not yet. $C = 1/(2\pi f_cR)$.
:::
:::

::: check
given: R = 10 | 22; C1 = 22 | 47; C2 = 4.7 | 10; f = 1 | 5
answer: 20*log(abs(1/(-(2*pi*f*1000)^2*(R*1000)^2*C1*C2*1e-18 + j*2*pi*f*1000*C2*1e-9*2*R*1000 + 1)))
unit: dB
tolerance: 0.5%

## A Sallen-Key stage has R = {R} kΩ (both), $C_1$ = {C1} nF and $C_2$ = {C2} nF. What is its gain at {f} kHz?

::: right
Right. $\left|\frac{1}{1 + 2sRC_2 + s^2R^2C_1C_2}\right|$ = {answer}.
:::

::: misses
- [any] Not yet. Evaluate the stage's transfer function at $s = j2\pi f$.
:::
:::

::: check
given: n = 3 | 4 | 6; r = 4 | 9
answer: 10*log(1 + r^(2*n))
unit: dB
tolerance: 0.5%

## An order-{n} Butterworth filter is checked at {r} times its corner. How far down is it?

::: right
Right. {answer}.
:::

::: misses
- [any] Not yet. $10\log_{10}(1 + r^{2n})$.
:::
:::

::: check
kind: python

## Write `required_order(fmax, fs, bits)` (the Butterworth order, cornered at `fmax`, that puts the first alias below an ideal `bits`-bit converter's resolution) and `design(fmax, fs, bits, R)`: return a list of stages, each `('SK', C1, C2)` in order of increasing Q, then `('RC', C, None)` if the order is odd.

```python starter
import numpy as np

def required_order(fmax, fs, bits):
    return 2

def design(fmax, fs, bits, R):
    wc = 2 * np.pi * fmax
    return [('SK', np.sqrt(2) / (wc * R), 1 / (np.sqrt(2) * wc * R))]
```

```python solution
import numpy as np

def required_order(fmax, fs, bits):
    A = 6.02 * bits + 1.76
    return int(np.ceil(np.log10(10 ** (A / 10) - 1) / (2 * np.log10((fs - fmax) / fmax))))

def design(fmax, fs, bits, R):
    n = required_order(fmax, fs, bits)
    wc = 2 * np.pi * fmax
    k = np.arange(1, n + 1)
    p = wc * np.exp(1j * np.pi * (2 * k + n - 1) / (2 * n))
    Qs = sorted(abs(q) / (-2 * q.real) for q in p if q.imag > 1e-9 * wc)
    stages = [('SK', 2 * Q / (wc * R), 1 / (2 * Q * wc * R)) for Q in Qs]
    if n % 2:
        stages.append(('RC', 1 / (wc * R), None))
    return stages
```

```python tests
import numpy as np
assert required_order(1000, 10000, 12) == 4, "1 kHz signals at 10 kHz with 12 bits need fourth order."
assert required_order(2000, 20000, 16) == 6, "2 kHz at 20 kHz with 16 bits needs sixth order."
assert required_order(1000, 20000, 12) == 3, "Sampling at 20 kHz, third order is enough."
st = design(1000, 10000, 12, 1e4)
assert [s[0] for s in st] == ['SK', 'SK'], "Fourth order is two Sallen-Key stages."
assert np.allclose([[s[1] * 1e9, s[2] * 1e9] for s in st], [[17.2268, 14.7040], [41.5892, 6.0906]], rtol=1e-4), f"Got {[(s[1] * 1e9, s[2] * 1e9) for s in st]} nF."
st = design(1000, 20000, 12, 1e4)
assert [s[0] for s in st] == ['SK', 'RC'], "Third order is one Sallen-Key stage plus an RC section."
assert abs(st[1][1] * 1e9 - 15.9155) < 1e-3, f"The RC section needs 15.9 nF with 10 kΩ; got {st[1][1] * 1e9:.4f}."
```

::: right
Right. The starter always built one second-order stage, which here gives only about 38 dB at the first alias: an alias about 1% of full scale, some fifty LSBs.
:::
:::

::: check
kind: python

## Write `gain_db(stages, R, f)`: the filter's gain in dB at the frequencies `f` (an array), computed from the stage values that `design` returns.

```python starter
import numpy as np

def gain_db(stages, R, f):
    return np.zeros(len(f))
```

```python solution
import numpy as np

def gain_db(stages, R, f):
    s = 2j * np.pi * np.asarray(f, dtype=float)
    H = np.ones_like(s)
    for kind, C1, C2 in stages:
        if kind == 'SK':
            H = H / (s * s * R * R * C1 * C2 + s * C2 * 2 * R + 1)
        else:
            H = H / (1 + s * R * C1)
    return 20 * np.log10(abs(H))
```

```python tests
import numpy as np
st4 = [('SK', 17.226806904e-9, 14.703999442e-9), ('SK', 41.589190864e-9, 6.090595990e-9)]
g = gain_db(st4, 1e4, [1000, 9000])
assert abs(g[0] + 3.0103) < 1e-3, f"At the corner a Butterworth design is down 3.01 dB; got {g[0]:.4f}."
assert abs(g[1] + 76.3394) < 1e-3, f"At 9 kHz it should be 76.3 dB down, past the 74 dB needed; got {g[1]:.4f}."
st3 = [('SK', 31.830988618e-9, 7.957747155e-9), ('RC', 15.915494309e-9, None)]
g = gain_db(st3, 1e4, [19000])
assert abs(g[0] + 76.7252) < 1e-3, f"The third-order design is 76.7 dB down at 19 kHz; got {g[0]:.4f}."
```

::: right
Right. Rounding these capacitors to standard values and recomputing the gain is the next step a real design would take.
:::
:::

::: explain
## Why does sampling faster make the anti-aliasing filter easier to build?

::: model
The filter has to pass the signal band unchanged while cutting everything that would fold back into it, and the first such frequency is the sampling rate minus the top of the signal band. Sampling faster pushes that frequency up, so the filter has a wider transition band in which to fall from passing everything to blocking almost everything. Each order of filter adds a fixed amount of attenuation per decade, so a wider gap on the log scale means fewer orders are needed to reach the same attenuation, and fewer stages, parts and op amps.
:::
:::

::: practice

::: check
given: N = 12 | 16; V = 3.3 | 5
answer: V/2^N*1e6
unit: µV
tolerance: 0.5%

## What is one LSB of an {N}-bit converter with a {V} V range?

::: misses
- [any] $V/2^N$.
:::
:::

::: check
given: n = 3 | 5 | 7
answer: (n - 1)/2
tolerance: 0.5%

## How many Sallen-Key stages does an odd order of {n} need, besides its RC section?

::: misses
- [any] One per pole pair.
:::
:::

::: check
given: fm = 1 | 20; fs = 10 | 96
answer: (fs - fm)/fm
tolerance: 0.5%

## For signals to {fm} kHz sampled at {fs} kHz, what is the ratio $(f_s - f_\text{max})/f_\text{max}$?

::: misses
- [any] Divide.
:::
:::
:::
