---
title: "Project: a touch-tone decoder"
heading: Detecting keypad tones with the Goertzel algorithm
eyebrow: C9 · Lesson 53 · Project
xp: 80
---

::: hook
Press a key on a phone and it sends two tones at once, one for the key's row and one for its column: dual-tone multi-frequency, or **DTMF**. Phone exchanges, voicemail systems and alarm panels decode these by asking, for each of eight frequencies, how much of it is in a short burst of samples. A full FFT would compute hundreds of frequencies to use eight; the **Goertzel algorithm** computes just one DFT bin with a two-line recursion, the second-order resonator of lessons 9 and 36 tuned to the frequency in question. In this project you'll generate DTMF tones, write Goertzel, and build a decoder that survives noise.
:::

::: play
- The keypad tone for the row and column you choose: two sinusoids added, with its spectrum below. Press Listen to hear it.
- The four row frequencies are 697, 770, 852 and 941 Hz and the four column frequencies 1209, 1336, 1477 and 1633 Hz. None is a harmonic of another, so speech rarely fakes a key.
- The decoder's job is to find the strongest row line and the strongest column line in a burst of 205 samples at 8 kHz, about 26 ms.
:::
:::

```sim plot
view: spectrum
x: t = 0..25.6m s
y: v = -2.2..2.2
slider: r = 0..3 = 1 step 1
slider: c = 0..3 = 1 step 1
plot: sin(2*pi*(697 + 73*step(r - 0.5) + 82*step(r - 1.5) + 89*step(r - 2.5))*t) + sin(2*pi*(1209 + 127*step(c - 0.5) + 141*step(c - 1.5) + 156*step(c - 2.5))*t) | label: tone
freq: f = 0..2k Hz
samples: 2048
readout: row frequency = 697 + 73*step(r - 0.5) + 82*step(r - 1.5) + 89*step(r - 2.5) Hz
readout: column frequency = 1209 + 127*step(c - 0.5) + 141*step(c - 1.5) + 156*step(c - 2.5) Hz
sound: sin(2*pi*(697 + 73*step(r - 0.5) + 82*step(r - 1.5) + 89*step(r - 2.5))*t) + sin(2*pi*(1209 + 127*step(c - 0.5) + 141*step(c - 1.5) + 156*step(c - 2.5))*t) | scale: 2.2
```

::: predict
## A decoder takes N = 205 samples at 8 kHz. How far apart are the frequencies a DFT of that length can resolve?

- [ ] 8 Hz
- [x] About 39 Hz
- [ ] 205 Hz
- [ ] 4 kHz

::: reveal
$8000/205 = 39$ Hz. The closest DTMF tones are 697 and 770 Hz, 73 Hz apart: about two bins, enough to tell them apart. A shorter burst would blur them together; a longer one would take more time per key.
:::
:::

::: nameit
## The keypad

| | 1209 Hz | 1336 Hz | 1477 Hz | 1633 Hz |
|---|---|---|---|---|
| **697 Hz** | 1 | 2 | 3 | A |
| **770 Hz** | 4 | 5 | 6 | B |
| **852 Hz** | 7 | 8 | 9 | C |
| **941 Hz** | * | 0 | # | D |

A key's signal is $\sin(2\pi f_\text{row}t) + \sin(2\pi f_\text{col}t)$, sampled at 8 kHz.

## The Goertzel algorithm

To measure frequency f in N samples, set $c = 2\cos(2\pi f/f_s)$ and run

$$s[n] = x[n] + c\,s[n-1] - s[n-2]$$

over the block from rest. Then the power at f is

$$P = s[N-1]^2 + s[N-2]^2 - c\,s[N-1]\,s[N-2]$$

which equals $\lvert X[k]\rvert^2$, the squared DFT bin, when f is the bin frequency $kf_s/N$. It's a resonator with poles on the unit circle at angle $2\pi f/f_s$: a tone at f builds up inside it, other frequencies don't. One multiplication per sample per frequency, so eight frequencies cost 8N, against the FFT's $\frac N2\log_2N$ for every bin.

## Decoding

Measure the four row powers and the four column powers; the key is at the strongest row and the strongest column. Real decoders also check that the strongest tone is well above the rest, that the row and column levels are within a few dB of each other (the **twist**), and that the tone lasts long enough, to avoid triggering on speech.
:::

::: example
## What are the Goertzel coefficients for the four row frequencies at 8 kHz?

::: solution
1. **The coefficient.**
   $$c = 2\cos(2\pi f/8000)$$
2. **The four rows.**
   $$\begin{aligned} c_{697} &= 1.7077 \\ c_{770} &= 1.6453 \\ c_{852} &= 1.5687 \\ c_{941} &= 1.4782 \end{aligned}$$
3. **What a decoder keeps.** A decoder stores these eight numbers and nothing else.

**Answer:** 1.7077 for 697 Hz, 1.6453 for 770 Hz, 1.5687 for 852 Hz and 1.4782 for 941 Hz.
:::
:::

::: example
## Which DFT bins (N = 205, 8 kHz) are nearest the row frequencies?

::: solution
1. **Bin index.**
   $$k = fN/f_s$$
2. **The four rows.**
   $$\begin{aligned} k_{697} &= 17.86 \\ k_{770} &= 19.73 \\ k_{852} &= 21.83 \\ k_{941} &= 24.11 \end{aligned}$$
   so bins 18, 20, 22 and 24.
3. **Off-bin cost.** The tones fall a little off-bin, which costs some power in each, but the nearest bins stay well separated, which is why 205 became the usual block length.

**Answer:** bins 18, 20, 22 and 24.
:::
:::

::: check
given: f = 697 | 941 | 1209 | 1633; fs = 8000
answer: 2*cos(2*pi*f/fs)
tolerance: 0.5%

## What is the Goertzel coefficient for {f} Hz at {fs} Hz?

::: right
Right. $2\cos(2\pi f/f_s)$ = {answer}.
:::

::: misses
- [cos(2*pi*f/fs)] The recursion uses twice the cosine.
- [any] Not yet. $2\cos(2\pi f/f_s)$.
:::
:::

::: check
given: f = 770 | 852 | 1336 | 1477; N = 205 | 410
answer: round(f*N/8000)
tolerance: 0

## Which DFT bin of an {N}-point DFT at 8 kHz is nearest {f} Hz?

::: right
Right. $fN/f_s$, rounded: bin {answer}.
:::

::: misses
- [any] Not yet. f divided by the bin spacing $f_s/N$, rounded.
:::
:::

::: check
given: d = 73 | 82 | 127; fs = 8000 | 16000
answer: fs/d
tolerance: 0.5%

## Two tones {d} Hz apart must land at least one bin apart. What is the shortest block length N, at {fs} Hz? (Give $f_s/\Delta f$.)

::: right
Right. The bin spacing $f_s/N$ must be at most {d} Hz: N ≥ {answer}.
:::

::: misses
- [d/fs] N is the sample count: the spacing $f_s/N$ must not exceed {d}.
- [any] Not yet. $N \ge f_s/\Delta f$.
:::
:::

::: check
kind: parts
given: N = 205 | 256 | 400

## A decoder checks 8 frequencies in each block of {N} samples.

::: part
answer: 8*N
tolerance: 0

### How many multiplications does Goertzel need per block?

::: misses
- [any] One per sample per frequency.
:::
:::

::: part
answer: N/2*log(N)/log(2)
tolerance: 0.5%

### How many complex multiplications would a radix-2 FFT of N points need? (Use the formula even if N isn't a power of 2.)

::: misses
- [any] $\frac N2\log_2N$.
:::
:::
:::

::: check
given: ar = 1 | 0.8; ac = 0.5 | 0.4 | 0.9
answer: 20*log(ac/ar)/log(10)
unit: dB
tolerance: 0.5%

## A key's row tone has amplitude {ar} and its column tone {ac}. What is the twist (column level relative to row), in dB?

::: right
Right. $20\log_{10}(a_c/a_r)$ = {answer} dB.
:::

::: misses
- [10*log(ac/ar)/log(10)] Amplitudes use 20 log, not 10.
- [any] Not yet. $20\log_{10}$ of the amplitude ratio.
:::
:::

::: check
kind: python

## Write `dtmf(key, fs=8000, n=205, a_row=1.0, a_col=1.0)`: the list of n samples of the key's two tones, $a_\text{row}\sin(2\pi f_\text{row}i/f_s) + a_\text{col}\sin(2\pi f_\text{col}i/f_s)$, for keys '0'–'9', '*', '#' and 'A'–'D'.

```python starter
def dtmf(key, fs=8000, n=205, a_row=1.0, a_col=1.0):
    return [0.0] * n
```

```python solution
import math

ROWS = [697, 770, 852, 941]
COLS = [1209, 1336, 1477, 1633]
KEYS = ['123A', '456B', '789C', '*0#D']

def dtmf(key, fs=8000, n=205, a_row=1.0, a_col=1.0):
    for r, line in enumerate(KEYS):
        if key in line:
            c = line.index(key)
            return [a_row * math.sin(2 * math.pi * ROWS[r] * i / fs) + a_col * math.sin(2 * math.pi * COLS[c] * i / fs) for i in range(n)]
    raise ValueError(key)
```

```python tests
import math
x = dtmf('5')
assert len(x) == 205, f"205 samples by default, got {len(x)}."
want = math.sin(2 * math.pi * 770 / 8000) + math.sin(2 * math.pi * 1336 / 8000)
assert abs(x[1] - want) < 1e-12, f"'5' is 770 Hz + 1336 Hz; sample 1 should be {want:.6f}, got {x[1]:.6f}."
y = dtmf('#', n=10)
want = math.sin(2 * math.pi * 941 * 3 / 8000) + math.sin(2 * math.pi * 1477 * 3 / 8000)
assert abs(y[3] - want) < 1e-12, "'#' is 941 Hz + 1477 Hz."
z = dtmf('A', n=4, a_row=0, a_col=2)
assert abs(z[2] - 2 * math.sin(2 * math.pi * 1633 * 2 / 8000)) < 1e-12, "'A' is in the 1633 Hz column; a_row and a_col scale each tone."
```

::: right
Right. Sixteen keys from eight frequencies.
:::
:::

::: check
kind: python

## Write `goertzel_power(x, f, fs)`: the Goertzel power of the samples x at frequency f.

```python starter
def goertzel_power(x, f, fs):
    return sum(v * v for v in x)
```

```python solution
import math

def goertzel_power(x, f, fs):
    c = 2 * math.cos(2 * math.pi * f / fs)
    s1 = s2 = 0.0
    for v in x:
        s1, s2 = v + c * s1 - s2, s1
    return s1 * s1 + s2 * s2 - c * s1 * s2
```

```python tests
import math, cmath
fs, N = 8000, 205
x = [math.sin(2 * math.pi * 770 * i / fs) + 0.5 * math.cos(2 * math.pi * 1336 * i / fs) for i in range(N)]
for k in (20, 34, 5):
    f = k * fs / N
    X = sum(x[n] * cmath.exp(-2j * math.pi * k * n / N) for n in range(N))
    p = goertzel_power(x, f, fs)
    assert abs(p - abs(X) ** 2) < 1e-6 * max(1, abs(X) ** 2), f"At bin {k} the Goertzel power should equal |X[k]|^2 = {abs(X) ** 2:.3f}, got {p:.3f}."
tone = [math.sin(2 * math.pi * 1000 * i / fs) for i in range(160)]
assert goertzel_power(tone, 1000, fs) > 100 * goertzel_power(tone, 1500, fs), "A 1 kHz tone should be far stronger at 1 kHz than at 1.5 kHz."
```

::: right
Right. One resonator, a handful of operations per sample, and exactly one DFT bin out.
:::
:::

::: check
kind: python

## Write `decode(x, fs=8000)`: return the key whose row and column frequencies have the largest Goertzel power in x.

```python starter
def decode(x, fs=8000):
    return '0'
```

```python solution
import math

ROWS = [697, 770, 852, 941]
COLS = [1209, 1336, 1477, 1633]
KEYS = ['123A', '456B', '789C', '*0#D']

def goertzel_power(x, f, fs):
    c = 2 * math.cos(2 * math.pi * f / fs)
    s1 = s2 = 0.0
    for v in x:
        s1, s2 = v + c * s1 - s2, s1
    return s1 * s1 + s2 * s2 - c * s1 * s2

def decode(x, fs=8000):
    r = max(range(4), key=lambda i: goertzel_power(x, ROWS[i], fs))
    c = max(range(4), key=lambda i: goertzel_power(x, COLS[i], fs))
    return KEYS[r][c]
```

```python tests
import math, random
ROWS_T = [697, 770, 852, 941]; COLS_T = [1209, 1336, 1477, 1633]; KEYS_T = ['123A', '456B', '789C', '*0#D']
def tone(key, n=205, fs=8000, ar=1.0, ac=1.0, detune=1.0):
    r = [i for i, l in enumerate(KEYS_T) if key in l][0]; c = KEYS_T[r].index(key)
    return [ar * math.sin(2 * math.pi * ROWS_T[r] * detune * i / fs) + ac * math.sin(2 * math.pi * COLS_T[c] / detune * i / fs) for i in range(n)]
got = ''.join(decode(tone(k)) for k in '0123456789*#ABCD')
assert got == '0123456789*#ABCD', f"Every key should decode to itself; got {got}."
random.seed(1)
assert decode([v + random.gauss(0, 0.5) for v in tone('7')]) == '7', "A '7' with noise of standard deviation 0.5 should still decode."
assert decode(tone('9', ac=0.5)) == '9', "A '9' with its column tone 6 dB low should still decode."
assert decode(tone('2', detune=1.015)) == '2', "Tones off by 1.5% (within the DTMF standard's limit) should still decode."
assert decode(tone('D', fs=16000, n=410), fs=16000) == 'D', "The decoder should work at other sample rates."
```

::: right
Right. That's a working DTMF receiver: the same idea runs in every phone exchange.
:::
:::

::: explain
## Why is Goertzel cheaper than an FFT for a DTMF decoder, even though the FFT is the "fast" algorithm?

::: model
The FFT is fast at computing all N bins of a DFT at once, about $\frac N2\log_2N$ multiplications for the whole set. A DTMF decoder needs only eight frequencies. Goertzel computes a single bin with one multiplication per sample, so eight bins cost 8N real multiplications, about 1,640 for N = 205, against roughly 4,000 for a 256-point FFT (1,024 complex multiplications of four real ones each). It also needs no buffer of N samples or power-of-two length: it runs as samples arrive and can be tuned to the exact DTMF frequencies instead of the nearest bins.
:::
:::

::: practice

::: check
given: f = 697 | 770 | 852 | 941 | 1209 | 1336 | 1477 | 1633
answer: 2*cos(2*pi*f/8000)
tolerance: 0.5%

## Goertzel coefficient for {f} Hz at 8 kHz?

::: misses
- [any] $2\cos(2\pi f/f_s)$.
:::
:::

::: check
given: N = 100 | 128 | 160 | 200 | 205 | 256 | 400
answer: 8000/N
unit: Hz
tolerance: 0.5%

## Bin spacing for N = {N} at 8 kHz?

::: misses
- [any] $f_s/N$.
:::
:::

::: check
given: f = 697 | 770 | 852 | 941 | 1209 | 1336 | 1477 | 1633; N = 205
answer: round(f*N/8000)
tolerance: 0

## Nearest bin to {f} Hz for N = {N} at 8 kHz?

::: misses
- [any] Round $fN/f_s$.
:::
:::
:::
