Anti-noise must reach your ear at the same moment as the noise. Slide the loop delay and hear silence turn into a louder hum.
Learn why a few dozen microseconds decide whether noise cancelling works, where every microsecond of an MCU audio path goes, and how block size, filters and microphone arrays fit inside that budget.
Press the Play the sound button, switch to With ANC, then drag the loop delay from 25 µs up to 300 µs. Watch each hum tone turn from green (quieter) to red (louder). Then we build the whole path, piece by piece: sound travel time, the phase arithmetic, the latency budget, blocks against single samples, the adaptive filter, the beamformer and the echo canceller.
You need to know that a sound is a wave with a frequency and a little C. We build the rest from zero.
Part of the series Firmware from Zero to Expertise, audio track. Every number is traced to a source in the Field Guide at the end.
Model, not a recording. The hum is four tones (150, 400, 900 and 1,800 Hz, relative strength 1, 0.8, 0.6, 0.4). The ear sits 2 cm behind the reference microphone, so the noise itself needs 58 µs to arrive (343 m/s). The anti-noise is a perfect inverted copy, late by whatever the loop delay exceeds that gap; the leftover is 2 sin(πfτ) per tone. Presets: 5.2 µs and 25 µs are the Renesas DA7413 fast and DSP paths; 21 µs is one sample at 48 kHz; 333 µs is 16 samples at 48 kHz. All are electronics only; speaker to ear adds more. Real earbuds also lose cancellation to fit and leakage.
Chapter 0
See how a copy of a sound that arrives a hair late can make the sound louder, and why that sets the speed limit for firmware
You sit on a train. An engine hum fills the carriage. You press an earbud into your ear and the hum fades. Nothing blocked it. A small program inside the earbud listened to the hum and played an opposite sound that cancelled it.
That program has a hard deadline. It is not the usual kind, such as “finish before the next frame”. It is a deadline measured in microseconds, millionths of a second. One microsecond is written 1 µs. A blink lasts about 300,000 µs. The earbud has about 58 µs.
Sound is a wave of air pressure. The pressure rises and falls many times per second. The number of rises per second is the frequency, measured in hertz (Hz). A 150 Hz hum rises and falls 150 times each second.
Now play a second wave that is the exact opposite: it falls when the first rises. The two add to zero. This is destructive interference, like two people pushing a door from opposite sides with the same force. The door does not move. The opposite wave is called anti-noise.
The trick only works if the two waves line up in time. Shift the anti-noise a little and the two no longer fall and rise together. Part of the noise survives. Shift it a lot and the two push the same way, so the result is louder than the noise alone.
Sound travels in air at about 343 metres per second (dry air at 20 °C). That sounds fast, but it is slow for a chip. In 29 µs sound moves one centimetre. A chip that runs at 168 MHz does about 4,900 clock cycles in the same 29 µs.
The earbud has a microphone on the outside, the reference microphone. It hears the hum first. The sound then travels a few centimetres to your ear. That travel is the time the firmware has. The firmware must listen, compute and play the anti-noise inside that gap.
Everything in the path costs time. The microphone chip needs time to turn air pressure into numbers. The firmware needs time to collect numbers and calculate. The speaker chip needs time to turn numbers back into pressure. Each stage is a latency: the delay between something going in and the result coming out. Add the latencies and you get the loop delay.
Try the instrument at the top of this page once more. A loop delay of 25 µs cancels the whole hum. A loop delay of 300 µs makes the two highest tones louder than they were. The only thing that changed is time.
Pick how many samples your firmware collects before it starts to work (a block). The blue bar is how far sound travels during that wait. The tick marks show the 2 cm gap of an earbud.
Arithmetic, not a measurement: block time = samples / 48,000 per second; distance = block time × 343 m/s. A block of 1 sample is the “sample-by-sample” case. The ruler has a fixed 0 to 25 cm scale.
The ruler shows the problem. A block of 16 samples at 48,000 samples per second (48 kHz) takes 333 µs to fill. Sound travels 11.4 cm in that time. The earbud only has 2 cm. The block size alone is already too slow.
By the end you can add up the microseconds of an audio path from microphone to speaker and say whether noise cancelling can work. You can choose between sample-by-sample and block processing. You can place a delay line inside a beamformer. You can measure the loop on a real board.
The rules in this lesson come from two older ideas. The first is the causality constraint of feedforward noise control, described by Kuo and Morgan in their 1999 review. The second is the latency budget: write every stage of a path in a table, give each a number, and compare the sum with the limit.
Chapter 1
Turn the distance between two microphones into microseconds, and see why the direction of the noise changes your deadline
Picture a goalkeeper facing a penalty kick. The kicker swings. The ball needs 0.4 seconds to arrive. The keeper has exactly that long to read the kick and move. If the keeper could only start moving after the ball arrived, there would be nothing to do.
A noise cancelling earbud is that keeper. The noise is the ball. The reference microphone sees the noise first. The keeper must finish before the noise passes your eardrum.
Engineers give the two journeys names. The primary path is the route the noise takes from the reference microphone to your ear. It is air, plus the earbud body. Its delay is set by physics. The secondary path is the route the anti-noise takes: from the firmware, through the converter and amplifier, out of the speaker and across the ear canal to your eardrum.
Both end at the same place, your eardrum. For the two waves to meet there in step, the anti-noise must start its journey early enough. Written as one rule:
This rule is the causality constraint. “Causal” means the effect (the anti-noise) comes after its cause but before the thing it must cancel. Kuo and Morgan’s 1999 tutorial review of active noise control states the idea for feedforward systems. A 2014 study in Applied Acoustics examines it for a feedforward headset, with noise coming from different directions. The same constraint governs this whole lesson.
Take a reference microphone 2 cm from the ear along the sound’s path, with noise straight ahead (θ = 0). Then Tgap = 0.02 m / 343 m/s = 58.3 µs. Move the microphone to 5 cm and Tgap = 0.05 / 343 = 145.8 µs. A bigger gap gives the firmware more time. But a microphone far from the ear hears a different sound from the one at the ear, so the design trades one against the other.
Now turn the noise to come from the side, θ = 90°. Then cosθ = 0 and Tgap = 0. The noise reaches the microphone and the ear at the same moment. No electronics can win that race. Try all three values below.
The ear is on the right, the reference microphone on the left. Change the distance, the angle the noise comes from, and your loop delay. The blue bar is the time the noise needs. The yellow bar is your loop. You win when yellow is shorter.
Geometry only: Tgap = d cosθ / 343 m/s. A real head is not free field, so a real gap differs. 0° means the noise travels along the line from the microphone toward the ear.
Symptom. A tester says the earbuds hush a passing train, but a fan on the left side of the desk sounds worse than with ANC off. Measurement. You place a speaker at several angles and record at the ear. Front and back sources drop by many decibels. A source at 90° drops by almost nothing, and above a few kilohertz it grows. That matches the model: the gap at 90° is near zero, so the loop is late for every frequency that matters.
Fix. You cannot change the physics of side noise, but you can change the geometry. Move the reference microphone forward along the stem so that the noise from most directions has a positive gap. Add a second reference microphone on the other side, and let the firmware use whichever one hears each sound first. Last, cut the loop delay with the budget of Chapter 3, because every microsecond saved lifts the highest frequency that still cancels.
At 2 cm and 0°, you have 58 µs. At 60° the budget halves to 29 µs, because cos 60° = 0.5. This is why a headset cancels noise from the front or back better than noise from the side. It also explains why designers put the reference microphone as far in front of the speaker as the shape of the product allows.
Another design avoids the race. A feedback system puts a microphone next to the speaker, inside the ear cup. It listens to what is left after cancelling and adjusts. It never needs to predict, so it has no gap. But it must wait to see its own mistake, so delay limits it in a different way: it works well at low frequencies only, and too much delay can make the loop ring. Many products use a hybrid: one feedforward path plus one feedback path. The Renesas DA7413 product page lists support for hybrid, feedforward and feedback topologies.
Chapter 2
Derive how much noise survives a late copy, and find the exact frequency where cancelling turns into boosting
Imagine two choirs singing the same note. One choir starts a tiny moment after the other. At a low note, a tiny moment is a small fraction of the note’s cycle, and the two choirs still sound together. At a very high note, the same moment is a big fraction of the cycle, and the choirs are clearly out of step.
A late anti-noise behaves the same way. The same delay is harmless at low frequency and harmful at high frequency. To see exactly where, we need one line of trigonometry.
A pure tone is a cosine: cos(2πft). One full cycle lasts a period, T = 1/f. A delay of τ seconds shifts the tone by a fraction τ/T of a cycle. In angle units this shift is the phase φ = 2πfτ radians. A full cycle is 2π radians, or 360°.
At the ear, the noise is cos(2πft). The ideal anti-noise is its negative. If the anti-noise is late by τ, it is −cos(2πf(t − τ)). What you hear is the sum. Use the identity cos A − cos B = −2 sin((A+B)/2) sin((A−B)/2) and the sum becomes a new tone of the same frequency with a new strength:
The change in decibels is 20 log10(R). Check three cases at 1,000 Hz. With τ = 50 µs, πfτ = 0.157 rad and R = 2 sin(0.157) = 0.313. That is −10.1 dB: the tone is about a third as strong. With τ = 100 µs, R = 0.618, or −4.2 dB. With τ = 250 µs, a quarter of the period, R = 1.414 and the tone is louder by 3.0 dB.
Where does R cross 1? Set 2 sin(πfτ) = 1. Then sin(πfτ) = 1/2, so πfτ = π/6 and fτ = 1/6. The delay equals one sixth of the period, 60° of phase. Past that, anti-noise adds to the noise. For a timing error τ, the highest frequency that still cancels is:
fmax = 1 / (6τ) τ = 50 µs → 3,333 Hz τ = 100 µs → 1,667 Hz τ = 300 µs → 556 Hz
That is the sentence behind the hero. With a loop delay of 300 µs, the timing error is 300 − 58 = 242 µs. Then fmax = 1/(6 × 242 µs) = 689 Hz. The 900 Hz and 1,800 Hz tones are past it, so they grow.
Cancelling by 20 dB means R = 0.1. Solve 2 sin(x) = 0.1 and x = 0.05 rad, so the phase error is 2x = 0.1 rad = 5.7°. Cancelling by 40 dB means R = 0.01 and a phase error of 0.57°. At 200 Hz, 0.57° is a timing error of 0.005 / (π × 200) = 8 µs. The Renesas DA7413 product page quotes 40 dB of cancellation at 200 Hz. A loop that does this must hold its timing to a few microseconds at that frequency, and its gain equal within about 0.1 dB.
Gain matters too. Suppose the anti-noise has strength g compared with the noise, besides the delay. The leftover becomes |1 − g e−jφ|, so R2 = 1 − 2g cosφ + g2. With perfect timing (φ = 0) this is |1 − g|. A gain 1 dB too high (g = 1.122) leaves R = 0.122, only −18.3 dB. Timing and level errors both set the floor.
The curve is the leftover loudness at each frequency, compared with no ANC. Below the grey line it cancels. Above it, it boosts. Drag the timing error, then add a level error.
Exact for one pure tone and one delay, from R2 = 1 − 2g cosφ + g2. Real earbuds also have a frequency-dependent secondary path and leakage, so measured curves differ. The curve is clipped at −40 dB.
The curve dips deepest at low frequency and rises as frequency climbs. Drag the timing error up and the dip narrows and the crossing to boost slides left. Add a level error and the dip stops reaching the floor: even at the lowest frequency, the leftover is |1 − g|.
Chapter 3
Add up each stage from microphone to eardrum, and see which choices you can still afford
A courier has a deadline. You do not ask “is the courier fast?” You write the route as a list: drive to the depot, wait for the sorting belt, load the van, drive to the door. You give each leg a time. Then you add the legs and compare the sum with the deadline.
That list is a latency budget. It is the method to use for any real-time path. Write every stage. Put a number on each. Add them. Compare with the limit. A later lesson in this series, on real-time latency budgets (planned, not yet written), teaches the method in general. Here we apply it to one path: sound in at the reference microphone, anti-noise out at your ear.
Follow one pressure change from the air to your eardrum.
One sample period is 1/fs. At 48 kHz it is 20.8 µs. At 96 kHz it is 10.4 µs. At 192 kHz it is 5.2 µs. Every stage that works in whole samples costs a multiple of that number. This is why noise cancelling chips run fast sampling rates, even though the noise they cancel is below a few kilohertz. The Renesas DA7413 product page lists a 192 kHz low-delay ANC DSP.
The same page gives two figures for the DA7413 codec: 5.2 µs from microphone input to headphone output through its dedicated fast equalization path, and 25 µs through its DSP. Add 29 µs of air from speaker to ear and the totals are 34 µs and 54 µs. Both fit inside a 58 µs gap at 2 cm, but barely. A general-purpose MCU path adds more stages.
An MCU handles each sample as it arrives (no block), at 48 kHz, with converters that each hold a signal for one sample period. Microphone converter: 20.8 µs. Processing in the interrupt and writing the result before the next frame: about one sample period, 20.8 µs. Speaker converter: 20.8 µs. Air: 29.2 µs. Total: 91.7 µs. The gap at 2 cm is 58.3 µs. The loop is 33.4 µs late, so tones above 1/(6 × 33.4 µs) = 4.99 kHz are the only ones that turn to boost; everything below still cancels, though weakly near the limit.
Now raise fs to 96 kHz. Every converter and the buffering stage halve. The total is 3 × 10.4 + 29.2 = 60.4 µs. That is 2 µs late, nearly inside the gap. The tool for fitting the budget is the sampling rate, not the processor speed.
Choose where the filter runs, then the sampling rate, block size and gap. Each coloured piece is one stage. The dashed line is the acoustic gap. Your goal: the stack ends before the line.
Codec figures are the Renesas DA7413 product-page numbers (5.2 µs fast path, 25 µs DSP path, microphone input to headphone output). The MCU rows are a model: each converter holds the signal for one sample period (a fast-filter assumption; read your codec’s group delay), a per-sample interrupt answers within one period, and a ping-pong block path adds two block times. Speaker to ear is 1 cm of air, 29.2 µs, illustrative.
Try the MCU block path at 48 kHz with 16 samples. Buffering alone is 667 µs. The stack is more than four times the 146 µs gap of the 5 cm design. No amount of clever filtering inside that block can fix it, because the sample must wait for the block to fill.
Chapter 4
Trade latency against processor load, and learn the cycle budget that decides which one your firmware can afford
A post office sorts letters. One clerk can walk each letter to its slot the moment it arrives. Or the clerk can wait until 16 letters are in the tray, then sort them all in one trip. The tray method wastes less walking. But the first letter in the tray waits for the other 15.
Audio firmware makes the same choice. Sample-by-sample processing runs your code once for every new sample, in an interrupt. Block processing collects B samples, then runs your code once on all of them. The choice sets two numbers: how late the output is, and how busy the processor is.
A DMA engine (direct memory access) moves samples between the audio port and memory without using the CPU. You give it a buffer twice as long as the block. It fills the first half, then raises an interrupt, then fills the second half while your code works on the first. This is double buffering, or ping-pong. On STM32 parts the HAL library names the two interrupts in its I2S driver, for example HAL_I2S_RxHalfCpltCallback for the half-full event and HAL_I2S_RxCpltCallback for the full event. The full-duplex versions are HAL_I2SEx_TxRxHalfCpltCallback and HAL_I2SEx_TxRxCpltCallback.
Count the wait. A sample arrives at the start of a block. It sits until the block is full: B sample periods. Your code then runs, and the result goes into the output half. That half plays only after the half that is playing now has finished: another B sample periods. So a ping-pong path adds two blocks of latency. A per-sample interrupt reads the sample at the frame edge and writes the answer before the next edge, one period.
latencyper sample = 1 / fs latencyblock = 2B / fs at 48 kHz, B = 16: 667 µs
The cost side is the cycle budget: how many clock cycles you have before the next sample arrives. It is fCPU / fs. A Cortex-M4 at 168 MHz has 3,500 cycles per sample at 48 kHz, 1,750 at 96 kHz and 875 at 192 kHz. The M4 has single-cycle dual 16-bit multiply-accumulate instructions, so a small filter fits easily. But the budget shrinks as you raise the sampling rate to save latency.
Every call also pays fixed costs. The processor spends 12 cycles to enter an interrupt on a Cortex-M4 with zero-wait-state memory (Arm’s blog on interrupt latency lists 12 for the M3 and M4). Leaving the interrupt takes a similar number of cycles. Your code adds its own setup. In this lesson’s model, one call costs 22 cycles for entry and return (the 12 is Arm’s figure; the 10 for return is an assumption) plus 60 cycles of setup, 82 cycles in total. The return and setup numbers are illustrative. Measure yours (Chapter 8).
A sample-by-sample handler pays 82 cycles every sample. A block handler pays 82 cycles once per block, which is 82/B per sample. At B = 16 that is 5 cycles per sample. Blocks also let CMSIS-DSP functions such as arm_fir_q15 loop over many samples with the loop overhead paid once, and they let the CPU sleep between blocks to save power.
A filter costs 600 cycles per sample. At 48 kHz, 168 MHz, B = 1: busy = 600 + 82 = 682 cycles of 3,500, a load of 19.5%. Latency is one period, 20.8 µs. At B = 16: busy = 16 × 600 + 82 = 9,682 cycles of 56,000, a load of 17.3%. Latency is 667 µs. The block saved 2.2 points of load and cost 646 µs. For noise cancelling, that is a terrible trade. For a music player with a 30 ms buffer, it is a great one.
Top: one stretch of time. Purple bars are your code running, grey is idle. Bottom: every block size on one curve, latency across and load up. Drag block size and the filter cost.
Model for a 168 MHz Cortex-M4. Block sizes are 1, 2, 4, 8, 16, 32 and 64 samples. One call costs 82 cycles (22 for interrupt entry and exit from Arm’s figures, 60 of illustrative setup). Block latency is 2B sample periods; the per-sample case is one period. Load over 100% means the code cannot keep up and audio drops out.
DWT->CYCCNT and read it at callback entry and exit. Run block sizes 1, 16 and 64. Compare your measured cycles per call with the 82-cycle model and your own fixed cost. Check the load stays below 100%.Push the filter cost to 2,000 cycles at 192 kHz. The budget is 875 cycles. The per-sample row turns red. A bigger block does not rescue it, because the load per sample hardly changes. The filter itself is too heavy for that rate.
c// per sample: the audio interrupt calls this once per frame; must finish within 1/fs int16_t on_sample(int16_t x) { return anc_step(x); // 600 cycles at 168 MHz = 3.6 us } // per block: DMA half and full callbacks, ping-pong halves of rx[] and tx[] #define B 16 static int16_t rx[2 * B], tx[2 * B]; static void process(const int16_t *in, int16_t *out) { for (int i = 0; i < B; i++) out[i] = anc_step(in[i]); } void HAL_I2SEx_TxRxHalfCpltCallback(I2S_HandleTypeDef *h) { process(&rx[0], &tx[0]); } void HAL_I2SEx_TxRxCpltCallback(I2S_HandleTypeDef *h) { process(&rx[B], &tx[B]); }
Chapter 5
Watch a filter learn the anti-noise on its own, and see why delay forces it to learn slowly or give up
You step into a shower you have never used. You turn the tap. Nothing changes. Three seconds later the water runs cold. You turn it back, too far, and three seconds later it is scalding. The pipe is long, so every move shows up late. The only safe way to find the right setting is to turn the tap in small steps and wait.
An adaptive noise filter lives in that shower. It turns a tap (its own numbers), and the result reaches the error microphone late. Move too fast and it overshoots. Chapter 5 shows why, and what delay does to what the filter can learn at all.
Chapter 2 assumed the anti-noise was a perfect inverted copy. A real earbud does not know the copy. The noise changes the shape on its way to the ear (the primary path), and the speaker changes the shape of anything it plays (the secondary path). So the firmware needs a filter that turns the reference signal into the right anti-noise, for this ear and this fit.
A FIR filter (finite impulse response) does it with a short list of numbers called weights. Each output is a weighted sum of the last L reference samples. An adaptive filter changes its weights while it runs, to make the leftover sound smaller. The leftover is measured by a second microphone, the error microphone, placed inside the ear cup.
The standard method for this is FxLMS, the filtered-x least mean squares algorithm, described in Kuo and Morgan’s 1999 review. The idea of LMS is to roll downhill on the error: after each sample, nudge every weight a little in the direction that makes the squared error smaller. Three lines give the full loop:
One sample of this loop costs about 3L multiply-accumulates: L for the output, L for the filtered reference, L for the weight update. With L = 32 that is about 100 multiply-accumulates, which a Cortex-M4 can do in a few hundred cycles. The cost is small compared with the delay problem.
Delay appears twice. First, the secondary path delay Δ (in samples) is how long a weight change takes to show up in e. Like the shower pipe, a larger Δ means the safe step size is smaller. Too large a step and the filter overshoots forever: it diverges.
Second, causality returns. The filter can only use reference samples it already has. If the noise reaches the ear d samples after the reference microphone, and the speaker path adds Δ samples, a broadband filter needs Δ ≤ d. If not, the filter would need a reference sample from the future. A predictable noise, such as a steady hum, lets the filter guess the future from the past. Random rumble cannot be guessed.
The device below runs the real algorithm. It uses 16 weights at 16,000 samples per second. The noise reaches the ear 4 samples (250 µs) after the reference. You set the secondary path delay Δ and the step size.
The curve is the leftover noise power over time, in dB compared with no ANC. Falling is learning. A curve that shoots up has diverged. Pick a noise, then move the delay and the step size.
A real run of the algorithm in your browser, not a drawing: 16 weights, 16 kHz, a seeded noise source, noise path = pure 4-sample delay, speaker path = pure delay with a perfect model. The hum is 300 Hz plus 700 Hz; the rumble is smoothed random noise. The step size is relative: μ = value / (16 × reference power). Real paths have gain and ringing, which makes learning harder. Results are capped at −60 dB.
Start with the hum, delay 0, step 0.10: the leftover falls to about −51 dB. Raise the delay to 8 samples (500 µs, twice the 250 µs noise delay): it still learns, to −38 dB, just more slowly. A pure hum can be predicted. Now switch to rumble. With the delay at 4 samples, equal to the noise path, the leftover falls to −45 dB. At 6 samples the filter gains nothing; the result is +2.8 dB, slightly worse than no ANC. At 8 samples it is +6.3 dB.
Last, try step 0.30 with the hum and delay 4. The curve climbs and the state chip says it diverged. The same step size was fine at delay 0. More delay means a smaller safe step.
c// one FxLMS step, float, L weights; sh[] is a model of the speaker path (here 1 tap) float fxlms_step(float x, float e) { push(xbuf, x); // newest reference sample push(xfbuf, dot(sh, xbuf, SH_LEN)); // x' = sh * x, the filtered reference for (int i = 0; i < L; i++) w[i] -= MU * e * xfbuf[i]; // step against the error return dot(w, xbuf, L); // y: send to the speaker }
Chapter 6
Turn the arrival times of a sound at four microphones into delay lines, and see what rounding them to whole samples costs
Four friends stand in a line on a beach. A wave rolls in at an angle. It reaches the first friend, then the second, then the third, then the fourth, each a moment later. Ask all four to raise a flag at the instant the wave touches them, but make the first friend wait a little, and the second a little less, so that the four flags go up together. Now the flags carry a message: the wave came from that direction.
That is a delay-and-sum beamformer. A line of microphones hears a sound from a given direction with small timing differences. The firmware delays each microphone’s signal so the copies line up for one chosen direction, then adds them. Sound from the chosen direction adds up. Sound from other directions arrives out of step and partly cancels. The microphone arrays and beamforming lesson develops the theory. This chapter is about the firmware side: where do the delays come from, and what do they cost?
Put M microphones on a line, spacing d apart. A plane wave comes from angle θ, measured from the line. It reaches microphone m earlier than microphone 0 by (m d cosθ) / c seconds. To steer to angle θ0, delay microphone m by:
Take four microphones 5 cm apart, listening along the line (θ0 = 0). Then τ1 = 0.05 / 343 = 145.8 µs, τ2 = 291.5 µs and τ3 = 437.3 µs. At 16 kHz one sample is 62.5 µs. The delays are 2.33, 4.66 and 7.00 samples. Only the last is a whole number.
A delay line in firmware is an array. Reading three places back is a delay of exactly 3 samples. Reading 2.33 places back is not defined. You have three choices.
Round. Use 2 samples for 2.33. It costs nothing. The timing error is up to half a sample, 31 µs at 16 kHz. Chapter 2 tells us what a timing error does: at frequency f the phase error is 2πf times the error. The sum loses a little gain, and the beam points slightly off target.
Interpolate. Compute a value between two samples with a short FIR filter (a fractional-delay filter). It costs multiply-accumulates for every microphone and adds its own group delay of half its length. A 16-tap filter adds about 7.5 samples, 469 µs at 16 kHz.
Go to the frequency domain. Take a block FFT, turn each delay into a phase shift per frequency bin, add, and transform back. Fractional delays are free. The price is one frame of latency: a 256-sample frame at 16 kHz is 16 ms. That is fine for speech pickup and far too slow for noise cancelling, where Chapter 3 gave you tens of microseconds.
The lesson for ANC: use a time-domain beamformer with exact integer delays if you can arrange the geometry or the sampling rate, and a short interpolator if you cannot. Use FFT beamformers where milliseconds are fine, like voice pickup for a call.
The half circle shows how loudly the array hears each direction, 0 dB at the edge and −30 dB at the centre. The line of microphones lies along the flat bottom. Steer the beam, change the tone, then round the delays.
Free-field plane wave, four omnidirectional microphones on a line, equal gains, one tone at a time. Gain = |sum of ej(phase of the wave − phase of the applied delay)| / 4. Rounded delays use the nearest whole sample at the chosen rate. Real arrays add microphone mismatch and the case of the device.
Set the spacing to 5 cm and the tone to 2 kHz. The beam is clean. Raise the tone and extra lobes appear. This is spatial aliasing: when the spacing is more than half a wavelength, two different directions can give the same set of phase steps. Below f = c / 2d = 343 / 0.10 = 3,430 Hz (for 5 cm) no steering angle can cause it. Steered across the line (90°) the array stays clean to a higher tone. Shrink the spacing to 2 cm and the limit moves to 8.6 kHz, but the beam gets wider at low frequency.
Chapter 7
Size an echo canceller so its window starts where the echo starts, and count what that costs the processor
You call a friend on a speakerphone. You say hello. Your voice comes out of the phone’s speaker, bounces around the room and goes back into the phone’s microphone. Your friend hears you again, a fraction of a second later. That second copy is an echo.
An acoustic echo canceller (AEC) removes it. The firmware knows exactly what it just sent to the speaker. It learns how the room changes that sound on the way back into the microphone. Then it predicts the echo and subtracts it. The acoustic echo cancellation lesson explains the adaptive filter, double talk and residual suppression. Its chapter on delay and drift is the starting point for this one.
The room is a filter. A hand clap in the room makes a short sound at the microphone, then a long fading tail. We call that shape the impulse response of the echo path. It starts after a pause: the time for the sound to travel from the speaker to the microphone, and every millisecond your firmware spent before it. The firmware part is the same list as Chapter 3: DMA buffers, block size, converter filters. A 20 ms output buffer adds 20 ms to the pause.
After the pause comes the fading tail. Engineers describe it with T60: the time the echo takes to fall by 60 dB. A small office has a T60 near 0.2 s. A big hall can reach several seconds.
The echo canceller uses an adaptive FIR filter, like the one in Chapter 5. A FIR filter with N weights can reproduce an echo path that is N samples long. Which N? If the filter starts at the moment the speaker sample leaves the processor, the first part of the filter covers the pause. Those weights learn zeros. They cost multiply-accumulates and add nothing.
The remedy is a bulk delay. The firmware measures the pause once, for example by cross-correlating the speaker signal with the microphone signal. It then delays the speaker reference by that amount, minus a small safety margin. Now the adaptive filter starts right where the echo starts. Every weight covers the tail.
Drift breaks this. If the speaker clock and the microphone clock differ by a few parts per million, the pause moves slowly. The DMA and clock drift lesson shows why. The margin has to cover it, and the delay estimate has to be repeated.
Model the tail as a straight fall in decibels: 60 dB over T60 seconds. The filter covers a window of time. Everything inside the window can be cancelled in principle. Everything after the window stays. The energy that remains falls 60 dB per T60 as the window grows past the start of the echo. So:
Take 2,048 weights at 16 kHz: a window of 128 ms. The pause is 24 ms and T60 is 250 ms. With no alignment, the window ends at 128 ms and covers only 104 ms of tail. ERLEmax = 60 × 0.104 / 0.250 = 25 dB. With alignment the window starts 2 ms before the echo and covers 126 ms of tail: 30 dB. Same weights, five more decibels.
Each sample, an LMS echo canceller computes N multiply-accumulates for the output and N for the weight update. At 16 kHz that is 2 × 2,048 × 16,000 = 65.5 million multiply-accumulates per second. A 168 MHz Cortex-M4 that completes one per cycle (the best case) spends 39% of its time on this. Double the tail or the sampling rate and the load doubles. Production code uses block frequency-domain filters to cut this, but the trend stays.
The blue curve is the echo path: a pause, then a fading tail. The purple bar is the span your filter covers. Compare the two, then read the best echo reduction and the load.
Model: echo level falls linearly in decibels, 60 dB per T60, after the pause; filter perfectly adapted inside its window. Load assumes one multiply-accumulate per cycle on a 168 MHz Cortex-M4, 2N per sample (filter plus update); real code is slower, and long filters use frequency-domain blocks. Alignment starts the window 2 ms before the echo.
Slide the pause up to 80 ms with alignment off. The 128 ms window now covers 48 ms of tail and the echo reduction falls to 12 dB. Turn alignment on and it returns to 30 dB at the same load. Alignment is the cheapest decibel you can buy.
Chapter 8
Turn the budget table into measurements, and learn why the worst case, not the average, decides whether the loop is causal
A tailor draws a pattern from a measurement and cuts the cloth. Then the customer stands in front of the mirror. The numbers on the pattern were a plan. The mirror is the truth. A latency budget is a pattern. Until you put the board on the bench and measure, it is only a plan.
Three tools make the measurement. Each answers one question. A pin and an oscilloscope tell you the total loop delay. A cycle counter tells you the compute stage. A histogram of many runs tells you the jitter.
Connect a signal generator to the microphone input, or to the ADC pin if you test without a microphone. Send a sharp pulse. Connect the scope to the generator output on channel 1 and to the DAC output on channel 2. Trigger on channel 1. The gap between the two edges is the loop delay of the converters plus your firmware. It is the one number the ear cares about.
To split that number into stages, add a GPIO pin. Set the pin high when the audio interrupt starts. Set it low when the code has written the output sample. Look at the pin on channel 3. Now you see how long the code ran, and how long after the pulse the interrupt began. Pins are cheap. They add a couple of cycles and no disturbance.
Cortex-M3, M4 and M7 parts have a small block called the DWT (data watchpoint and trace) with a 32-bit counter, CYCCNT, that goes up by one at every CPU clock. Turn it on by setting the trace-enable bit in CoreDebug->DEMCR, then the cycle-counter-enable bit in DWT->CTRL. Cortex-M0 and M0+ parts do not have this cycle counter, so use a hardware timer there. At 168 MHz the counter wraps after 232 / 168 MHz = 25.6 s, long enough for short tests.
c// enable the cycle counter once at start-up (Cortex-M3, M4, M7) CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; volatile uint32_t worst = 0; void audio_isr(void) { uint32_t t0 = DWT->CYCCNT; process_one_sample(); uint32_t dt = DWT->CYCCNT - t0; // unsigned subtraction survives one wrap if (dt > worst) worst = dt; // keep the maximum, not the average }
Divide cycles by the clock to get time: 600 cycles at 168 MHz is 3.6 µs. Compare the worst value with the cycle budget of Chapter 4. Keep the maximum, not only the mean. The next section shows why.
Run the pulse test hundreds of times and write each delay in a list. Plot a histogram. A healthy path shows one narrow bump. A path with trouble shows a bump with a tail: most events are fast, a few are late.
Late events have many causes. The interrupt waits behind another interrupt of equal or higher priority. The code runs from flash and a cache miss adds wait states. A DMA transfer holds the bus. Arm lists 12 cycles as the interrupt entry latency of a Cortex-M4 with zero-wait-state memory and no competing exceptions. Anything outside those conditions adds to it.
Use the worst case, not the mean, because the loop must be causal on every sample. Chapter 2 gives the cost: a timing error of τ turns tones above 1/(6τ) to boost. A path that is 50 µs on average but 85 µs once in a hundred events is 27 µs late against a 58 µs gap on those events. For that moment, tones above 6.2 kHz are boosted, and a click may be audible.
Each bar counts how many of 400 simulated pulse tests took that long. The dashed line is the 58 µs gap. Turn on the trouble sources, then give the audio interrupt top priority.
Simulated, seeded data, not a recording. Flash waits add 0 to 4 µs (exponential-looking tail). The other interrupt blocks the audio one for 5 to 45 µs in 3% of events, unless the audio interrupt has top priority, which also removes it. Bus contention adds 0 to 2 µs. The 58.3 µs gap is the 2 cm earbud of Chapter 1.
With the typical delay at 48 µs and nothing switched on, all 400 events are inside the gap. Switch on Another interrupt in the way. The mean barely moves, but about twelve events land far to the right. Give the audio interrupt top priority and the tail disappears.
Symptom. The earbuds cancel well, but every few seconds you hear a short crackle, mostly when the phone syncs over Bluetooth. Measurement. You log the worst interrupt time with CYCCNT and see 14,000 cycles, which is 83 µs at 168 MHz, once every few seconds. The scope shows the audio interrupt starting late at the same moments. Fix. The radio stack’s interrupt had the same priority as the audio one. Give the audio interrupt the highest priority, keep the radio handler short, and place the audio code in fast memory. Measure again: the tail should vanish.
Chapter 9
Keep the numbers, the checklist and the code, and find the sources behind every claim
You can now answer a question that sounds odd: how late is too late for a sound? The answer is a number you can compute. Sound needs a known time to cross the gap between the reference microphone and the ear. Your loop must finish inside it. If it does not, the leftover is 2|sin(πfτ)| of the noise, and every tone above 1/(6τ) gets louder.
A feedforward noise canceller works only if the loop delay (converters, buffers, compute, speaker, air) is no longer than the acoustic gap d cosθ / 343. The stages are whole sample periods, so a higher sampling rate and a per-sample or tiny-block design shorten them. A block path pays two blocks of latency. An adaptive FxLMS filter learns the anti-noise but needs a smaller step as the speaker path delay grows, and it cannot predict random noise past the gap. A delay-and-sum beamformer needs delays that are fractions of a sample, and the method for them (round, interpolate, FFT) sets its latency. An echo canceller turns the same delay into a filter length, so align the reference first. Measure with a pin, a scope and the cycle counter, and judge the worst case.
| What | Number | Why it matters |
|---|---|---|
| Speed of sound, dry air, 20 °C | 343 m/s, so 29.2 µs per cm | Turns distance into a time budget |
| Acoustic gap, mic ahead of ear | 2 cm: 58.3 µs; 5 cm: 145.8 µs | The deadline of the loop |
| Gap for noise at angle θ | d cosθ / c; 0 at 90° | Side noise cannot be cancelled causally |
| Leftover after a late copy | R = 2|sin(πfτ)| | Cancelling or boost, per frequency |
| Boost limit | f > 1/(6τ): τ = 100 µs gives 1,667 Hz | The one-sixth rule |
| Depth needs precision | 20 dB: 5.7°; 40 dB: 0.57°; 40 dB at 200 Hz: 8 µs | Timing and level errors both set the floor |
| Renesas DA7413 codec | 5.2 µs fast path; 25 µs DSP path; 192 kHz ANC DSP; 40 dB at 200 Hz | What a dedicated part achieves |
| Sample period | 20.8 / 10.4 / 5.2 µs at 48 / 96 / 192 kHz | Each stage costs whole periods |
| Latency, one sample or one block | 1/fs or 2B/fs; B = 16 at 48 kHz: 667 µs | Blocks are too slow for ANC |
| Cycle budget, 168 MHz | 3,500 / 1,750 / 875 per sample at 48 / 96 / 192 kHz | The price of a high rate |
| Cortex-M4 interrupt entry | 12 cycles (zero wait states); tail-chain 6 | Fixed cost per call |
| FxLMS cost | about 3L multiply-accumulates per sample | Small next to the delay |
| Beamformer delays, 4 mics, 5 cm, endfire | 145.8, 291.5, 437.3 µs = 2.33, 4.66, 7.00 samples at 16 kHz | Fractional delays |
| Spatial aliasing limit | f = c / 2d: 3,430 Hz at 5 cm | Choose the spacing for the band |
| Echo canceller | ERLEmax = 60 × Tcov / T60; 2,048 weights at 16 kHz = 65.5 M MAC/s | Align, then size |
| DWT cycle counter, 168 MHz | wraps after 25.6 s | Measure compute in cycles |
CYCCNT for compute, a histogram for jitter.c#include <math.h> // the whole lesson in three functions static float gap_us(float d_cm, float theta_deg) { // Ch 1: time the noise needs return d_cm * 0.01f * cosf(theta_deg * 0.0174533f) / 343.0f * 1e6f; } static float residual_db(float f_hz, float late_us) { // Ch 2: leftover of a late copy float r = 2.0f * fabsf(sinf(3.14159265f * f_hz * late_us * 1e-6f)); return 20.0f * log10f(fmaxf(r, 1e-6f)); } static float loop_us(float fs, int block, float conv_samples) { // Ch 3, 4: converters + buffering + 1 cm of air float T = 1e6f / fs; float buf = (block == 1 ? 1.0f : 2.0f * block) * T; return 2.0f * conv_samples * T + buf + 29.2f; } // causal if loop_us(...) <= gap_us(...); else boost starts above 1e6f / (6 * (loop - gap)) Hz
This lesson closes the audio track’s timing story. Digital audio on the wire showed how samples cross a link. DMA ping-pong and clock drift showed how they sit in buffers. Codecs and the analog front end showed the converters. Real-time DSP on Cortex-M showed the filters and the cycle count. Here you added them all into one deadline. Product pages describe the same architecture: Apple’s support text for AirPods Pro says outward-facing microphones detect outside sound and the earbuds counter it with anti-noise (Apple Support article 108918). A planned lesson on real-time latency budgets will teach the general method on its own.
stm32f4xx_hal_i2s.c: opened. Callback names HAL_I2S_RxHalfCpltCallback, HAL_I2S_RxCpltCallback and the HAL_I2SEx_TxRx*Callback defaults.Now press Present or Teach and explain the loop out loud from memory: why the gap is a time, what a late copy does to a tone, where the microseconds go, why a block is slow, and how you would measure it. Then go back to the hum and find the delay where the highest tone turns to boost.