TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Applications: Audio, Sensor Filtering and Communications

Applications: Audio, Sensor Filtering and Communications

The earlier lessons each solved one problem. Real products chain them: a sensor, an anti-alias filter, an ADC, a decimator, a filter, a feature such as a level or a spectrum, and a decision. This lesson walks through three short case studies that use the whole toolkit: cleaning an audio recording and metering it, rejecting spikes and noise in an industrial sensor, and detecting digital data in noise, a preview of the Communications course. Each one starts from a requirement and ends with numbers you could check on a bench.

sensor mic, accel. anti-alias analog LPF ADC fs, bits decimate CIC, FIR filter FIR / IIR features rms, PSD decision output sampling and conversion -> multirate -> filter design -> spectral analysis and detection

Case 1: audio clean-up and level metering

Requirement. A 48 kSa/s48\ \text{kSa/s} voice recording has a DC offset from the interface, low-frequency rumble (handling noise near 20 Hz20\ \text{Hz}) and 50 Hz50\ \text{Hz} hum. Remove the offset and rumble with a high-pass filter that leaves speech (above about 100 Hz100\ \text{Hz}) within 1 dB1\ \text{dB}, notch the hum, and report the level in dBFS (decibels relative to a full-scale sine, so a full-scale sine is 0 dBFS0\ \text{dBFS} rms by the common AES convention).

Design. A 4th-order Butterworth high-pass at 60 Hz60\ \text{Hz} in second-order sections (Biquads) and a notch at 50 Hz50\ \text{Hz} (Poles and Zeros). Run them with sosfilt in blocks, the way a real-time plug-in would (Real-Time DSP).

python · try it yourself
import numpy as np
from scipy.signal import butter, iirnotch, sosfilt, tf2sos, sosfreqz

fs = 48000.0
t = np.arange(int(1.0 * fs)) / fs
rng = np.random.default_rng(2)
voice = 0.2 * np.sin(2 * np.pi * 220 * t) + 0.1 * np.sin(2 * np.pi * 1200 * t)   # stand-in for speech
x = voice + 0.05 + 0.1 * np.sin(2 * np.pi * 20 * t) + 0.03 * np.sin(2 * np.pi * 50 * t) + 1e-3 * rng.standard_normal(len(t))

sos = np.vstack([butter(4, 60, btype="highpass", fs=fs, output="sos"),
                 tf2sos(*iirnotch(50, Q=10, fs=fs))])
_, H = sosfreqz(sos, worN=[20.0, 50.0, 100.0, 220.0, 1200.0], fs=fs)
print("chain gain (dB) at 20/50/100/220/1200 Hz:", " ".join(f"{20 * np.log10(max(abs(h), 1e-12)):.1f}" for h in H))

y, zi = np.zeros_like(x), np.zeros((sos.shape[0], 2))
for k in range(0, len(x), 256):                             # 256-sample blocks, state carried over
    y[k:k + 256], zi = sosfilt(sos, x[k:k + 256], zi=zi)

def dbfs(sig):                                              # rms relative to a full-scale sine (amplitude 1)
    return 20 * np.log10(np.sqrt(np.mean(sig**2)) / (1 / np.sqrt(2)))
def tone(sig, f):                                           # amplitude of one component (whole periods in 0.5 s)
    return 2 * abs(np.mean(sig * np.exp(-2j * np.pi * f * t[late])))
late = slice(int(0.5 * fs), None)                           # after the filters have settled
print(f"level: input {dbfs(x[late]):.1f} dBFS, output {dbfs(y[late]):.1f} dBFS, voice alone {dbfs(voice[late]):.1f} dBFS")
print(f"DC {np.mean(x[late]):.3f} -> {np.mean(y[late]):.5f}; 20 Hz {tone(x[late], 20):.4f} -> {tone(y[late], 20):.4f}; "
      f"50 Hz {tone(x[late], 50):.4f} -> {tone(y[late], 50):.5f}")
chain gain (dB) at 20/50/100/220/1200 Hz: -38.2 -209.4 -0.1 -0.0 -0.0
level: input -11.8 dBFS, output -13.0 dBFS, voice alone -13.0 dBFS
DC 0.050 -> 0.00000; 20 Hz 0.1000 -> 0.0012; 50 Hz 0.0300 -> 0.00000

Check against the requirement. DC, rumble and hum are gone (the −209 dB-209\ \text{dB} at 50 Hz50\ \text{Hz} is the exact zero of the notch, limited by rounding), and the output level equals the voice alone. The chain is −0.1 dB-0.1\ \text{dB} at 100 Hz100\ \text{Hz}, inside the 1 dB1\ \text{dB} allowance, because a notch with Q=10Q = 10 is only 5 Hz5\ \text{Hz} wide. A wider notch (Q=2Q = 2, more tolerant of a drifting hum frequency) costs 0.5 dB0.5\ \text{dB} at 100 Hz100\ \text{Hz}: still within the budget, but half the margin is gone (and with the high-pass moved to 80 Hz80\ \text{Hz} as well, the chain is −1.1 dB-1.1\ \text{dB} and fails). Reading the requirement against the response of the whole chain, not the design intent of each filter, is the habit this course aims to build.

Case 2: industrial sensor with spikes

Requirement. A pressure transmitter sampled at 100 Sa/s100\ \text{Sa/s} shows occasional one-sample spikes from a nearby contactor, plus white noise. The control loop needs the step response to settle within 0.1 s0.1\ \text{s} and spikes reduced below 2 %2\,\% of full scale.

Design. A linear filter spreads a spike out instead of removing it (Discrete Convolution). A median filter, a non-linear filter, removes isolated outliers entirely and keeps steps sharp, then a short moving average reduces the noise.

python · try it yourself
import numpy as np
from scipy.signal import medfilt, lfilter

rng = np.random.default_rng(4)
n = np.arange(200)
p = np.where(n >= 80, 60.0, 40.0)                          # % of full scale: step from 40 % to 60 %
x = p + 0.3 * rng.standard_normal(len(n))
spikes = [30, 120, 150]
x[spikes] += [25.0, -30.0, 20.0]                           # contactor spikes

y_ma = lfilter(np.ones(9) / 9, 1, x)                       # 9-sample moving average only
y_med = lfilter(np.ones(3) / 3, 1, medfilt(x, 5))          # 5-point median, then 3-sample average

def worst_spike(y):
    return max(abs(y[k:k + 10] - p[k:k + 10]).max() for k in spikes)
def settle(y, tol=0.5):                                    # samples after the step until within tol of 60 %
    bad = np.where(np.abs(y[80:] - 60) > tol)[0]
    return int(bad[bad < 30].max()) + 1 if np.any(bad < 30) else 0
for name, y in (("moving average 9", y_ma), ("median 5 + avg 3", y_med)):
    print(f"{name:17s}: worst spike residue {worst_spike(y):5.2f} %FS, settles in {settle(y)} samples, "
          f"noise {np.std(y[160:200] - 60):.3f} %FS")
moving average 9 : worst spike residue  3.32 %FS, settles in 8 samples, noise 0.072 %FS
median 5 + avg 3 : worst spike residue  0.28 %FS, settles in 2 samples, noise 0.102 %FS

The moving average leaves spikes of 3.3 %3.3\,\% (a 30 %30\,\% spike divided by 9) and fails the 2 %2\,\% requirement; the median-based chain removes them (0.28 %0.28\,\% is noise) and settles faster (22 samples instead of 8, both well inside 0.1 s0.1\ \text{s}), at the cost of a little more noise (0.100.10 against 0.07 %0.07\,\% of full scale, since 3 samples are averaged instead of 9). The median filter is not linear, so it has no frequency response: test it with the signals it will meet, as here.

Case 3: detecting bits in noise

Requirement. Send binary data at 1 kbit/s1\ \text{kbit/s} as ±1 V\pm 1\ \text{V} rectangular pulses (binary phase-shift keying at baseband), sampled at 88 samples per bit, through a channel adding white noise, and estimate the bit error rate (BER) at Eb/N0=6 dBE_b/N_0 = 6\ \text{dB}.

Design. The receiver is a matched filter (an 8-sample sum for a rectangular pulse) sampled at the end of each bit, followed by a sign decision. Theory gives BER=Q(2Eb/N0)\text{BER} = Q\big(\sqrt{2E_b/N_0}\big), with QQ the Gaussian tail probability.

python · try it yourself
import numpy as np
from scipy.special import erfc

rng = np.random.default_rng(9)
nbits, sps = 200000, 8
ebn0_db = 6.0
bits = rng.integers(0, 2, nbits)
sym = 2.0 * bits - 1.0
tx = np.repeat(sym, sps)                                   # rectangular pulses, 1 V per sample
Eb = sps * 1.0                                             # energy per bit (sum of squares)
N0 = Eb / 10 ** (ebn0_db / 10)
rx = tx + np.sqrt(N0 / 2) * rng.standard_normal(len(tx))   # white noise, variance N0/2 per sample
mf = rx.reshape(nbits, sps).sum(axis=1)                    # matched filter sampled once per bit
ber = np.mean((mf > 0) != (bits == 1))
theory = 0.5 * erfc(np.sqrt(10 ** (ebn0_db / 10)))         # Q(sqrt(2 Eb/N0))
print(f"Eb/N0 = {ebn0_db:.0f} dB: simulated BER {ber:.2e} ({int(ber * nbits)} errors in {nbits} bits), theory {theory:.2e}")
naive = np.mean((rx[sps // 2::sps] > 0) != (bits == 1))    # one sample per bit, no filter
print(f"without the matched filter (one sample per bit): BER {naive:.2e}")
Eb/N0 = 6 dB: simulated BER 2.32e-03 (464 errors in 200000 bits), theory 2.39e-03
without the matched filter (one sample per bit): BER 1.60e-01

The matched filter collects the energy of all 8 samples (9 dB9\ \text{dB} of processing gain) and meets the theory; deciding from one sample per bit wastes it and gives an error rate about 70 times worse. With 464 errors the simulated BER is uncertain by about ±5 %\pm 5\,\% (1/4641/\sqrt{464}), enough to agree with 2.39×10−32.39 \times 10^{-3}; count at least 100 errors before trusting a BER estimate. Pulse shaping, bandwidth, synchronisation and coding are the subject of the communications course.

Guided lab: an end-to-end audio measurement

Hand calculation. For the Case 1 chain: −38 dB-38\ \text{dB} at 20 Hz20\ \text{Hz}, a null at 50 Hz50\ \text{Hz}, −0.1 dB-0.1\ \text{dB} at 100 Hz100\ \text{Hz}, flat above.

Simulation. In Case 1, change the notch's Q to 2, then raise the high-pass corner to 80 Hz80\ \text{Hz}, and read the gains at 2020 and 100 Hz100\ \text{Hz} each time: the requirement trade-off in numbers.

What you would measure. Play a stepped sine sweep (20 Hz to 2 kHz) from a computer's audio output into a USB audio interface's line input through a cable (no loudspeaker needed), record at 48 kSa/s48\ \text{kSa/s}, run the chain on the recording and compare the per-frequency level before and after. Expect agreement with sosfreqz within about 0.2 dB0.2\ \text{dB} in the passband (the interface's own response is flat there to roughly that level); the notch depth is limited by the sweep's frequency accuracy and by the interface's noise floor (roughly −90-90 to −110 dBFS-110\ \text{dBFS} wideband, depending on the interface), not by the filter's exact null.

Hazards and safe setup. Line-level audio only (about 1 V1\ \text{V}); start with the output volume low; no mains-powered equipment is opened, and headphones, if used, are kept at a comfortable level.

Pitfalls

  • Specifying filters by their design parameters and never checking the cascade against the requirement.
  • Using a linear filter on impulsive interference: medians or clipping first, linear smoothing after.
  • Judging a BER from a handful of errors.
  • Metering dBFS with inconsistent references (AES17 calls a full-scale sine 0 dBFS0\ \text{dBFS}, so a full-scale square wave reads +3.01 dBFS+3.01\ \text{dBFS}, but some meters show the full-scale sine as −3.01 dBFS-3.01\ \text{dBFS}; state the convention).

Practice

  1. A full-scale sine has amplitude 1. What is the level in dBFS of a sine of amplitude 0.1?
  2. A 5-point median filter removes one-sample spikes. Does it also remove two-sample bursts of the same size next to each other, and three-sample ones?
  3. At Eb/N0=9.6 dBE_b/N_0 = 9.6\ \text{dB}, BPSK has a BER of about 10−510^{-5}. How many bits must you simulate to see about 100 errors?
Answer
  1. 20log⁡100.1=−20 dBFS20\log_{10}0.1 = -20\ \text{dBFS}.
  2. A 5-point median ignores up to 2 outliers in its window, so a 2-sample burst is also removed; a burst of 3 or more samples is not. (A 3-point median would fail on the 2-sample burst.)
  3. About 100/10−5=107100/10^{-5} = 10^7 bits.

Test yourself

Why is a median filter preferred to a moving average for isolated spikes?

  1. it is linear
  2. it removes outliers instead of spreading them, and keeps steps sharp
  3. it has a narrower passband
  4. it needs no memory

The bit error rate of BPSK with a matched filter in white noise is

  1. Q(Eb/N0)Q(E_b/N_0)
  2. Q(2Eb/N0)Q(\sqrt{2E_b/N_0})
  3. e−Eb/N0e^{-E_b/N_0}
  4. independent of noise

A filter chain meets its design targets individually but fails the requirement at 100 Hz. The best next step is

  1. ignore it
  2. check the cascade's response against the requirement and move corners or Q
  3. add more filters
  4. raise the sampling rate

A one-second recording at 48 kSa/s is processed in 256-sample blocks with sosfilt. To get the same output as one call on the whole signal you must

  1. reset the filter state for each block
  2. carry the filter state zi from block to block
  3. overlap blocks by 50 %
  4. use filtfilt