TExcelTAD
Home › Fourier Analysis & Signals › Mini Project: A Touch-Tone Decoder

Mini Project: A Touch-Tone Decoder

Press a key on a phone and it sends two tones at once: one from a group of four low frequencies (the row) and one from four high frequencies (the column). This is DTMF (dual-tone multi-frequency) signalling, still used by phone menus and alarm systems. In this project you generate a DTMF sequence, analyse it with windowed FFTs, detect tones efficiently with the Goertzel algorithm, and decode a noisy recording back to the keys.

What we are building:

Step Part Course topics
1. Generate the signal synthesis sinusoids, sampling, seeded noise
2. Look at one key's spectrum analysis windows, FFT, bin frequencies
3. The Goertzel algorithm detection a two-pole IIR resonator evaluating one DFT bin
4. Decode the whole sequence segmentation frame energy, thresholds, STFT thinking
5. Stress test with noise robustness SNR, power

Note: Each step is a complete program (the playground does not share variables between runs), so the signal generator is repeated where needed.

The keypad frequencies (Hz):

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

Step 1: Generate the signal

Each key is a 50 ms tone burst followed by 50 ms of silence, sampled at 8000 Hz (telephone quality). We add a little noise from a seeded generator so the output is reproducible.

python · try it yourself
import numpy as np

fs = 8000
LOW = [697, 770, 852, 941]
HIGH = [1209, 1336, 1477, 1633]
KEYS = ["123A", "456B", "789C", "*0#D"]

def key_freqs(key):
    for r, row in enumerate(KEYS):
        if key in row:
            return LOW[r], HIGH[row.index(key)]
    raise ValueError(key)

def dtmf(keys, tone=0.05, gap=0.05, noise=0.05, seed=1):
    rng = np.random.default_rng(seed)
    t = np.arange(int(tone * fs)) / fs
    parts = []
    for k in keys:
        fl, fh = key_freqs(k)
        parts.append(0.5 * np.sin(2 * np.pi * fl * t) + 0.5 * np.sin(2 * np.pi * fh * t))
        parts.append(np.zeros(int(gap * fs)))
    x = np.concatenate(parts)
    return x + noise * rng.normal(size=x.size)

x = dtmf("5551234#")
print("samples:", x.size, " duration:", x.size / fs, "s")
print("key 5 uses", key_freqs("5"), "Hz;  key # uses", key_freqs("#"), "Hz")
print("RMS during a tone:", round(float(np.sqrt(np.mean(x[:400] ** 2))), 3), " during a gap:", round(float(np.sqrt(np.mean(x[400:800] ** 2))), 3))
samples: 6400  duration: 0.8 s
key 5 uses (770, 1336) Hz;  key # uses (941, 1477) Hz
RMS during a tone: 0.499  during a gap: 0.053

Each tone has RMS 0.25/2+0.25/2=0.5\sqrt{0.25/2 + 0.25/2} = 0.5 plus a little noise, and the gaps contain only the noise of RMS 0.05.

Step 2: Look at one key's spectrum

Take the first tone (400 samples), apply a Hann window, and find the two strongest peaks. With 400 samples the bin spacing is 20 Hz, so we zero-pad to 4096 to read the peaks more precisely (Zero Padding).

python · try it yourself
import numpy as np

fs = 8000
t = np.arange(400) / fs
rng = np.random.default_rng(1)
frame = 0.5 * np.sin(2 * np.pi * 770 * t) + 0.5 * np.sin(2 * np.pi * 1336 * t) + 0.05 * rng.normal(size=400)

w = 0.5 - 0.5 * np.cos(2 * np.pi * np.arange(400) / 400)
A = np.abs(np.fft.rfft(frame * w, 4096))
f = np.fft.rfftfreq(4096, 1 / fs)
low_band, high_band = (f > 600) & (f < 1050), (f > 1100) & (f < 1750)
f_low = f[low_band][np.argmax(A[low_band])]
f_high = f[high_band][np.argmax(A[high_band])]
print(f"strongest low tone near {f_low:.1f} Hz, strongest high tone near {f_high:.1f} Hz")
print(f"bin spacing without padding: {fs / 400:.0f} Hz, with padding: {fs / 4096:.2f} Hz")
strongest low tone near 769.5 Hz, strongest high tone near 1335.9 Hz
bin spacing without padding: 20 Hz, with padding: 1.95 Hz

The DTMF frequencies were chosen so that no tone is a harmonic of another and the closest pair (697 and 770 Hz) is 73 Hz apart, comfortably more than the roughly 2⋅20=402 \cdot 20 = 40 Hz resolution of a 50 ms Hann-windowed frame.

Step 3: The Goertzel algorithm

We only need the energy at 8 known frequencies, not a whole spectrum. The Goertzel algorithm computes a single DFT value with a two-pole IIR resonator whose poles sit on the unit circle at the target frequency (Poles, Zeros and Stability):

s[n]=x[n]+2cos⁡(ω0) s[n−1]−s[n−2],∣X(ω0)∣2=s[N−1]2+s[N−2]2−2cos⁡(ω0) s[N−1]s[N−2]s[n] = x[n] + 2\cos(\omega_0)\, s[n-1] - s[n-2], \qquad \lvert X(\omega_0) \rvert^2 = s[N-1]^2 + s[N-2]^2 - 2\cos(\omega_0)\, s[N-1] s[N-2]

It costs one multiplication per sample per frequency, so 8 frequencies are much cheaper than an FFT, and it needs no buffer of the whole frame.

python · try it yourself
import numpy as np

fs = 8000

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

t = np.arange(400) / fs
frame = 0.5 * np.sin(2 * np.pi * 770 * t) + 0.5 * np.sin(2 * np.pi * 1336 * t)

for f in (697, 770, 852, 941, 1209, 1336, 1477, 1633):
    p = goertzel_power(frame, f)
    dft = abs(np.sum(frame * np.exp(-2j * np.pi * f / fs * np.arange(400)))) ** 2
    print(f"{f:5d} Hz: Goertzel {p:9.1f}   direct |X|^2 {dft:9.1f}")
  697 Hz: Goertzel      72.9   direct |X|^2      72.9
  770 Hz: Goertzel   10083.9   direct |X|^2   10083.9
  852 Hz: Goertzel       6.8   direct |X|^2       6.8
  941 Hz: Goertzel       6.4   direct |X|^2       6.4
 1209 Hz: Goertzel      17.8   direct |X|^2      17.8
 1336 Hz: Goertzel   10046.7   direct |X|^2   10046.7
 1477 Hz: Goertzel       0.8   direct |X|^2       0.8
 1633 Hz: Goertzel       1.1   direct |X|^2       1.1

Goertzel matches the direct evaluation of the DFT sum at each frequency, and the energy at 770 and 1336 Hz dwarfs the others.

Step 4: Decode the whole sequence

Slide over the signal in 10 ms hops, mark frames whose energy is well above the noise as "tone", and for each run of tone frames use Goertzel on the whole burst to pick the strongest low and high frequency.

python · try it yourself
import numpy as np

fs = 8000
LOW = [697, 770, 852, 941]
HIGH = [1209, 1336, 1477, 1633]
KEYS = ["123A", "456B", "789C", "*0#D"]

def dtmf(keys, tone=0.05, gap=0.05, noise=0.05, seed=1):
    rng = np.random.default_rng(seed)
    t = np.arange(int(tone * fs)) / fs
    parts = []
    for k in keys:
        r = next(i for i, row in enumerate(KEYS) if k in row)
        c = KEYS[r].index(k)
        parts += [0.5 * np.sin(2 * np.pi * LOW[r] * t) + 0.5 * np.sin(2 * np.pi * HIGH[c] * t), np.zeros(int(gap * fs))]
    x = np.concatenate(parts)
    return x + noise * rng.normal(size=x.size)

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

def decode(x, hop=80):
    energy = np.array([np.mean(x[i:i + hop] ** 2) for i in range(0, len(x) - hop + 1, hop)])
    active = energy > 0.05                       # tones have power 0.25, gaps about 0.0025
    keys, i = [], 0
    while i < len(active):
        if active[i]:
            j = i
            while j < len(active) and active[j]:
                j += 1
            burst = x[i * hop:j * hop]
            r = int(np.argmax([goertzel_power(burst, f) for f in LOW]))
            c = int(np.argmax([goertzel_power(burst, f) for f in HIGH]))
            keys.append(KEYS[r][c])
            i = j
        else:
            i += 1
    return "".join(keys)

sent = "5551234#"
print("sent:   ", sent)
print("decoded:", decode(dtmf(sent)))
sent:    5551234#
decoded: 5551234#

Step 5: Stress test with noise

How much noise can the decoder take? Decode a longer random-looking (but seeded) key string at increasing noise levels and count the errors. The SNR is computed from the tone power 0.25 and the noise variance.

python · try it yourself
import numpy as np

fs = 8000
LOW = [697, 770, 852, 941]
HIGH = [1209, 1336, 1477, 1633]
KEYS = ["123A", "456B", "789C", "*0#D"]

def dtmf(keys, noise, seed):
    rng = np.random.default_rng(seed)
    t = np.arange(400) / fs
    parts = []
    for k in keys:
        r = next(i for i, row in enumerate(KEYS) if k in row)
        c = KEYS[r].index(k)
        parts += [0.5 * np.sin(2 * np.pi * LOW[r] * t) + 0.5 * np.sin(2 * np.pi * HIGH[c] * t), np.zeros(400)]
    x = np.concatenate(parts)
    return x + noise * rng.normal(size=x.size)

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

def decode_known_timing(x, n_keys):           # we know where the bursts are, to isolate the frequency decision
    out = []
    for k in range(n_keys):
        burst = x[800 * k:800 * k + 400]
        r = int(np.argmax([goertzel_power(burst, f) for f in LOW]))
        c = int(np.argmax([goertzel_power(burst, f) for f in HIGH]))
        out.append(KEYS[r][c])
    return "".join(out)

rng = np.random.default_rng(42)
sent = "".join(rng.choice(list("0123456789*#ABCD"), size=40))
for noise in (0.1, 0.5, 1.0, 2.0, 3.0):
    got = decode_known_timing(dtmf(sent, noise, seed=7), len(sent))
    errors = sum(a != b for a, b in zip(sent, got))
    snr = 10 * np.log10(0.25 / noise ** 2)
    print(f"noise std {noise:3.1f} (SNR {snr:6.1f} dB): {errors:2d} errors in {len(sent)} keys")
noise std 0.1 (SNR   14.0 dB):  0 errors in 40 keys
noise std 0.5 (SNR    0.0 dB):  0 errors in 40 keys
noise std 1.0 (SNR   -6.0 dB):  0 errors in 40 keys
noise std 2.0 (SNR  -12.0 dB):  4 errors in 40 keys
noise std 3.0 (SNR  -15.6 dB): 17 errors in 40 keys

Even at an SNR well below 0 dB, where the noise is louder than the tones, most keys decode correctly: each Goertzel sum gathers the tone's energy coherently over 400 samples while the noise adds up incoherently, the same processing gain we saw in the intro. Real decoders also check that the second-strongest frequency is clearly weaker, that the tone lasts at least 40 ms, and that the two tones' powers are similar (the "twist").

Where to go next

  • Replace the fixed energy threshold in Step 4 by one estimated from the quietest frames, and test with different noise levels.
  • Add the real-world checks above (minimum duration, twist limits, rejecting speech that happens to contain a DTMF frequency) and test with a recorded voice.
  • Detect a 1000 Hz tone in a stream with a single Goertzel filter updated every sample (a sliding DFT).
  • Build a spectrogram of the whole sequence with the STFT and plot it as an image.
  • Continue with SciPy Signal Filters for production-quality filter design, with Differential Equations for the continuous-time systems behind analog filters, and with Math for Deep Learning for learned convolutions.

Test yourself

A DTMF key is identified by…

  1. one tone
  2. one low-group and one high-group tone played together
  3. the loudness of the tone
  4. the duration only

Why is the Goertzel algorithm preferred over a full FFT here?

  1. it is more accurate
  2. only 8 frequencies are needed, and each costs one multiplication per sample
  3. it works without sampling
  4. the FFT cannot handle 8000 Hz

The decoder still works below 0 dB SNR because…

  1. the noise is filtered out before sampling
  2. each tone's energy accumulates coherently in its frequency while noise spreads over all frequencies
  3. the tones are louder than 0 dB
  4. Goertzel removes noise