Real-Time DSP on a Cortex-M

A 168 MHz Cortex-M4 has 3,500 cycles to spend on every audio sample at 48 kHz. Learn to spend them well: Q15 maths, filters, the FFT, SIMD and the budget of each block.

See what fixed-point numbers, packed multiply-accumulate instructions and block size do to the one thing that decides whether audio firmware works: finishing before the next block arrives.

Pick Naive C, then slide the filter length up until the block misses its deadline. Switch to CMSIS-DSP style and watch the same filter fit. Then we build every piece from zero.

You need the idea that audio is a stream of numbers, one per tick of a clock, and a little C. We build fixed-point numbers, filters and the cycle budget from zero.

Series: Firmware from Zero to Expertise, audio track. Built from the Arm CMSIS-DSP documentation, the Arm CMSIS Core SIMD intrinsics reference and the Cortex-M4 Technical Reference Manual timing notes. Listed in full in the Field Guide.

Fill the block period

256 taps
32 samples

A model, not a measurement. The core is an STM32F407 at 168 MHz. The chain is two biquads and one FIR per sample. Cycle costs come from the instruction counts in Chapter 7 and are illustrative: measure your own build with the cycle counter (Chapter 7).

Chapter 0

Why Audio Firmware Lives on a Budget

See how a fixed number of clock ticks per sample sets every choice in this lesson, from number format to block size

You are building a small speaker that removes hiss from a microphone. A tiny chip sits on the board. Sound arrives as numbers, one number every 20.8 microseconds. Each number must be filtered and sent on before the next one lands. If you are late, the listener hears a click.

That is the whole problem. The maths of filters is old and simple. The hard part is doing it on a chip with no spare time. This lesson teaches the maths that fits such a chip.

Three words before we start

A sample is one number that says how loud the air pressure was at one instant. Audio at 48 kHz has 48,000 samples each second. A sample is a bit like one frame of a film, but for sound.

A cycle is one tick of the chip’s clock. A chip at 168 MHz ticks 168 million times each second. Each instruction takes one or more cycles. Cycles are the money you spend. You cannot borrow any.

DSP means digital signal processing: doing arithmetic on a stream of samples to change it. A filter that removes hiss is DSP. So is a spectrum analyser. The rest of this lesson is DSP on a small chip, which we call real-time because a late answer is a wrong answer.

The budget, worked out

The chip in our examples is the STM32F407. It has an Arm Cortex-M4 core that runs at up to 168 MHz and a hardware floating-point unit. Divide the clock by the sample rate and you get the budget.

168,000,000 cycles per second ÷ 48,000 samples per second = 3,500 cycles per sample

That is 3,500 cycles for each sample, for everything: filtering, the spectrum, the volume, the code that copies data. A 64-tap filter that costs 7 cycles per tap uses 448 of them. That sounds fine. Now put in a second microphone, an echo canceller and a radio that steals the chip for 250 microseconds every 7.5 ms. The cycles vanish quickly.

Blocks, not single samples

The chip does not wake up for every sample. A DMA engine (a small helper that copies data without the processor) fills a buffer of B samples. When the buffer is half full, it raises an interrupt, a signal that makes the processor stop what it does and run a short function. That function processes one block of B samples. The previous lesson built this ping-pong buffer in full. Here we only need its rule: the block must be finished before the next one is ready.

Block size is a trade. Large blocks spread the fixed cost of an interrupt over more samples, and they let loops run tight. Large blocks also add delay, because audio waits for a whole block before work starts. Try it.

Trade interrupt cost for delay

The bar is the cycle budget of one sample. The purple slice is what the interrupt costs per sample. Drag the block size and watch the slice shrink while the delay grows.

32 samples

The 75 cycles per interrupt is a model (about 12 cycles to enter and 12 to leave, plus clearing the flag and calling the filter code), illustrative and not measured. The 12-cycle entry is the commonly quoted figure for a Cortex-M4 with zero-wait-state memory. The delay counts two blocks, one waiting in and one waiting out.

Notice what the device shows. On a fast chip at 48 kHz, the interrupt is cheap even for blocks of one sample. On a 48 MHz chip at 96 kHz you get only 500 cycles per sample, and every cycle counts. The same code can be fine on one board and impossible on another.

What this lesson teaches

Small chips have a hard way of doing arithmetic. They often skip floating point and use whole numbers that stand for fractions. We call this fixed point. It is fast and exact in its own way, and it fails in sharp ways you can hear. Learning where it fails is the first half. The second half is the speed: how a chip does two multiplications in one cycle, and how you add up the cost of a whole chain.

We follow one thread: take the 3,500-cycle budget, and spend it on real filters. At the end you can look at a chain of filters, count its cycles, and say if it fits.

  1. Numbers without a point: Q15 and Q31, the fixed-point formats.
  2. Overflow you can hear: wrap against saturate.
  3. Multiply and accumulate: the accumulator, guard bits and headroom.
  4. FIR filters: the delay line, the taps and their cost.
  5. Biquads: recursive filters and why their coefficients are fragile.
  6. The FFT: a spectrum in Q15, and the scaling that protects it.
  7. SIMD: two multiplies in one instruction, and a cycle count you can check.
  8. The cycle budget per block: put the chain together and find the missed deadline.
  9. Field Guide: numbers, checklist, core code, sources.
A chip runs at 96 MHz and processes audio at 48 kHz. How many cycles does it have for each sample?

Chapter 1

Numbers Without a Point

Learn how a chip with only whole numbers stores fractions, and how to multiply them without losing the scale

Picture a volume knob that goes from 0 to 1. Half way is 0.5. A quarter is 0.25. Now picture a chip that knows only whole numbers: 0, 1, 2, 3 and so on. It has no way to write 0.5. How does it hold the knob?

The trick is an agreement. You decide that every whole number is a count of tiny steps. If one step is 1/32768 of the full range, then 16384 steps means half. The chip stores 16384. You remember that it means 0.5. The chip never learns about the scale. You hold it in your head and in your code.

This is fixed-point arithmetic. The “point” is the decimal point, and in fixed point it sits at a fixed place that you chose. In floating point the point moves with the number. Fixed point is simpler, so it needs fewer cycles and less energy.

What Q15 means

A Q-format names the agreement. Q15 (Arm writes it 1.15) uses a 16-bit signed whole number. One bit is the sign. The other 15 bits count steps of 2−15. The stored integer n stands for the value n ÷ 32768.

x
The number you mean, between −1 and just under +1. This is the audio sample as a fraction of full scale.
n
The whole number the chip stores, from −32768 to 32767. In C this is a plain int16_t.
215
The scale, 32768. One step is 1/32768, about 0.0000305. The scale never appears in memory.

Look at the edges. The largest n is 32767, which means 0.999969482421875. The smallest is −32768, which means exactly −1. There is no n for +1.0. The range has one more negative value than positive, because zero takes one of the positive slots. This lopsidedness causes a famous bug in Chapter 2.

The Arm CMSIS-DSP library names these types q15_t, a 16-bit signed integer, and q31_t, a 32-bit one. Its documentation describes the formats as 1.15 and 1.31. Q31 works the same way with 31 fraction bits. It has much finer steps (2−31), takes twice the memory, and fits one value per 32-bit register instead of two.

0.5 → 0.5 × 32768 = 16384 = 0x4000    0.25 → 8192 = 0x2000    −0.5 → −16384 = 0xC000

Why a 16-bit audio sample is already Q15

A CD-quality sample is a 16-bit signed integer. That is exactly a Q15 number. The microphone codec hands your chip these integers over I2S, as the wire lesson showed. You can use them as Q15 with no conversion. One step of 16-bit audio is 3.05 × 10−5 of full scale, which is 90.3 dB below the loudest sound. That floor is the quantisation noise, the small error from rounding every value to a step.

Multiplying two Q15 numbers

Now the part that is easy to get wrong. You want to multiply 0.5 by 0.25. Multiply the stored integers: 16384 × 8192 = 134,217,728. That number does not fit in 16 bits. It needs 32.

What scale does it carry? Each factor carried a scale of 215. The product carries 215 × 215 = 230. So the 32-bit result is in Q30. To get back to Q15, shift right by 15 bits. That throws away the low 15 bits.

16384 × 8192 = 134,217,728 (Q30)  →  >> 15  →  4096 (Q15) = 4096 ÷ 32768 = 0.125  ✓

This is the rule for every multiply on this page: multiply into a wider register, then shift to put the point back. In C it is (int32_t)a * b >> 15. The shift is an arithmetic shift, which copies the sign bit, so negative numbers stay negative. Addition needs no shift, because two Q15 numbers already share a scale.

The shift truncates: it drops the low bits and always rounds toward minus infinity. On average it makes the result about half a step too low. A rounding multiply adds half a step (0x4000) before the shift to remove that bias. CMSIS functions choose one or the other, so read each function’s documentation.

Turn fractions into 16-bit words

Each row is the 16-bit word the chip stores. Teal cells are 1 bits and the left cell is the sign. Drag a value past ±1 to see what the format cannot hold. The last line is the multiply from the worked example.

0.500
0.250

Exact integer arithmetic, as a 16-bit word and a 32-bit product would do it. The multiply truncates (arithmetic shift, no rounding), and the one overflowing case, −1 × −1, is saturated to 32767 as CMSIS does.

Try a = 1.2. The chip cannot store it. It saturates to 32767, which means 0.99997. Try −1 × −1: the true answer is +1, which also does not exist. Fixed point has hard walls. Staying away from them is the main craft of this lesson.

Why not just use floating point?

A Cortex-M4 can have a hardware floating-point unit, and the STM32F407 does. Cortex-M0, M0+ and M3 have none, and there a float multiply runs as many instructions of software. Even where the unit exists, the Q15 SIMD instructions you meet in Chapter 7 do two multiplies per instruction. Fixed-point code also has the same timing on every input. Real-time work values that.

It is a trade. Floats protect you from overflow and scaling with a wide range. Fixed point gives speed and predictability, and asks you to track the scale of every value yourself. The next chapters show how.

On real hardware. On an STM32 Nucleo-F411RE (also a Cortex-M4F), convert a float to Q15 with arm_float_to_q15(), print the integers over the serial port, and check them against the table above. Then call arm_mult_q15() on 16384 and 8192 and confirm 4096. Repeat with −32768 twice and note the answer.

You multiply two Q15 numbers as 32-bit integers. What format does the raw product have, and what do you do to return to Q15?

Chapter 2

Overflow You Can Hear

Hear what happens when a number leaves the Q15 range, and learn the two ways a chip can fail and the one way to avoid both

A singer is loud and you turn up the gain by 2 to bring out a quiet verse. On the loud notes the speaker does not just sound harsh. It crackles, like frying oil. The same code on a quiet song sounds perfect. You have just heard an overflow.

Chapter 1 showed the walls of Q15. The largest value is 32767 and the smallest is −32768. An overflow happens when a result needs more room than 16 bits give. The chip must do something with it. There are two choices, and they sound very different.

Wrap against saturate

Wraparound is what plain integer arithmetic does. The number goes past 32767 and comes out at the bottom. 32767 + 1 becomes −32768, like a car odometer that rolls from 99999 to 00000. C code such as (int16_t)(a * 2) wraps.

Saturation is the other choice. A result above the top stays at the top. A result below the bottom stays at the bottom. It clamps, like a volume limiter. Arm Cortex-M4 and M7 have instructions that do this in hardware. __QADD16 adds two pairs of 16-bit values and saturates each result. __SSAT(x, 16) clamps a 32-bit value to 16 bits. CMSIS-DSP functions such as arm_mult_q15 and the standard arm_fir_q15 end by saturating to 1.15.

One sample, both ways

Take a loud sample of 30000. That is 0.916 of full scale. You apply a gain of 1.5. The true answer is 45000, which is 1.373 of full scale and does not fit.

wrap: 45000 − 65536 = −20536 (−0.627)    saturate: 32767 (0.99997)    truth: 1.373

Wrap flips the sign. A sample that should be the loudest positive peak turns into a loud negative one, an error of 2.0 full scales (65,536 steps). Saturation is wrong too, but it is wrong by only 0.37 and in the right direction. One is a spike. The other is a flat top.

Why does a spike sound so bad? A sudden jump contains energy at every frequency, which the ear hears as a click. A flat top is smooth. It still adds harmonics, copies of the tone at 2, 3, 4 times its frequency, but they are fewer and weaker. Both are distortion, sound that was not in the input. Press play on the device and compare.

Push a sine past the wall

A 375 Hz sine at 0.6 of full scale goes through a gain stage. Choose how the chip handles the overflow, then press Hear it. Keep your volume low: the wrap case is harsh.

2.00

The wave is computed with exact 16-bit integer rules, then played at low volume through your browser. Distortion is the share of signal energy that is not at 375 Hz, measured over 8 whole cycles. The exact mode is clipped by your speaker, not by the chip.

Set the gain to 1.5 and the wrap mode. The loud peaks flip to the bottom and the picture is full of vertical jumps. Switch to saturate. The peaks flatten and the number under the picture drops. At gain 1.6 and below the peaks stay inside the range, and all three modes match.

The failure: symptom, measurement, fix

Symptom. Crackle on loud passages, only at some volumes, never on quiet test tones. Because the test tone you used on the bench was quiet, the bug shipped.

Measurement. The Cortex-M4 keeps a sticky Q flag in its status register (bit 27 of the APSR). SIMD instructions like SMLAD set it on overflow, and it stays set until you clear it. Read it at the end of every block. A log of how often it fires tells you the true headroom of your signal path. You can also watch the peak absolute value of each block, which costs a few cycles.

Fix. Saturation limits the damage, so use it by default. But the real cure is headroom: scale the input down so that the biggest possible result still fits, and scale it up again at the end. Four times headroom, two bits, costs 12 dB of signal-to-noise. Chapter 3 shows how many bits the sums in a filter need.

The rule. Plain C integer maths wraps, and wrap is the worst failure. Use saturating operations at every place a value can leave the range, and add headroom so they rarely fire.

The one value that always breaks

Recall that Q15 has no +1.0. Multiply −1 by −1: the stored words are −32768 each, the product is 230, and after the shift it is 32768. That is one above the top, so it wraps to −32768 again. The answer to (−1) × (−1) is −1. Library code saturates this case to 32767, which is why library multiplies are safer than your own loop.

On real hardware. On an STM32 Nucleo-F446RE (it has a 12-bit DAC), generate the 375 Hz sine in a timer interrupt, multiply by 2 in C once with a plain cast and once with __SSAT, and put the DAC pin on an oscilloscope. Plain C shows vertical jumps at the peaks. Saturation shows flat tops. Then read the Q flag after a block that used __SMLAD.

A Q15 sample of 30000 is multiplied by 1.5 (the true result is 45000). Which line is correct?

Chapter 3

Multiply and Accumulate

Learn why the sum inside a filter needs more bits than its inputs, and how many bits you must keep as a guard

You are averaging 64 microphone samples to smooth them. Each sample is a Q15 number. You add the 64 numbers into a 16-bit variable. On quiet sound it works. On loud sound the result is garbage. The inputs fit. The output would fit. The middle of the sum did not.

Almost every filter in this lesson is a sum of products. Each step multiplies two numbers and adds the result to a running total. This step is the multiply-accumulate, or MAC. The running total is the accumulator. Chips are built around it: a MAC unit is the heart of a DSP, and the Cortex-M4 has one that finishes in a single cycle.

acc = acc + a × b

How big does the total get?

Chapter 1 showed that a product of two Q15 numbers is a Q30 number, held in 32 bits. The largest magnitude it can have is 230. A 32-bit signed register holds up to 231 − 1. So there is room to add the first product, and a second one fills it. Add many and the register overflows.

The fix is more bits for the accumulator. Each time you double the number of terms, the worst case grows by one bit. Add N terms and you need guard bits, extra bits above the product, equal to the base-2 logarithm of N rounded up. Sixty-four terms need 6 guard bits.

bits
The width the accumulator needs so that N worst-case products can never overflow it, counting the sign.
31
One Q30 product, plus a sign bit. A product is below 230, so 31 bits hold it with its sign. The single case of −1 × −1 reaches 230 exactly and needs one more bit, so treat the formula as the usual estimate.
⌈log2 N⌉
The guard bits. N = 64 gives 6. N = 256 gives 8. The ceiling means round up to a whole bit.

For 64 terms that is 37 bits, more than a 32-bit register holds. This is why Arm documents that the standard Q15 FIR and biquad functions in CMSIS-DSP use a 64-bit accumulator. The library says the 2.30 products are accumulated in 34.30 format: 34 integer bits instead of 2, so 32 bits of room above the product. No sum of 16-bit taps can reach that. The accumulator is cut to 34.15 by dropping the low 15 bits, and the final result is saturated back to 1.15.

The fast version and its price

CMSIS-DSP also offers arm_fir_fast_q15. It uses a 32-bit accumulator in 2.30 format. The documentation says plainly that if the accumulator overflows it wraps around and distorts the result. To avoid overflow completely, it says, the input must be scaled down by log2(numTaps) bits. This is Chapter 2’s headroom rule, now with a formula.

You pay for headroom with precision. Scale the input down 6 bits and you lose 6 of its 16 bits of detail. That is 36 dB of signal-to-noise. The fast version trades quality for cycles. Which is right depends on your signal.

Worst case against real life

The log2 N rule is very safe. It assumes every coefficient is as large as it can be. Real filters have small coefficients. The true worst-case sum depends on the L1 norm of the coefficients: the sum of their absolute sizes. If the input is full scale and each sample has the same sign as its coefficient, the sum reaches (L1 norm) × 230.

The 32-bit register is safe whenever the L1 norm is below 2. A lowpass filter with gain 1 at DC has an L1 norm of at least 1, and usually 1.1 to 1.6. A highpass or a narrow bandpass has a larger norm, and can pass 2. The next device computes the real value for a real filter.

Climb the accumulator

The line is the running total for the worst possible input, one tap at a time. The red line is the top of a 32-bit register. Change the filter and see if the total crosses it. Then shift the input down to buy headroom.

63
0.100
0 bits

The filter is a Hamming-windowed sinc, with a highpass made by subtracting the lowpass from a single impulse at the centre. The worst case assumes a full-scale input whose signs match the coefficients. Real signals usually stay far below it, but a loud square wave or a chirp can get close.

Choose the lowpass at 0.1 of the sample rate with 63 taps. The L1 norm is about 1.6, and the total finishes at 79% of the 32-bit limit. Switch to highpass. The norm climbs to 2.2 and the line crosses the red wall by 9%. Shift the input down by one bit and the curve is halved. It fits again, at the cost of one bit of resolution.

The modular trick

There is a quiet piece of good news. Wraparound arithmetic is exact modulo 232. If a partial sum overflows but the final sum fits, the wrapped intermediate steps cancel out, and the final answer is right. This holds for plain wrapping adds. It does not hold for saturating adds, because saturation loses information in the middle. So an accumulator should wrap internally and saturate only once, at the end, when you put the result back into Q15.

Worked example: L1 norm 3.0, so the worst final sum is 3.0 × 230 = 3,221,225,472. That is over 231 = 2,147,483,648. In 32 bits it wraps to 3,221,225,472 − 4,294,967,296 = −1,073,741,824. Shift right by 15 and you read −32768, full-scale negative. The true answer was +3.0 and would have saturated to +32767. A loud peak became the opposite peak.

On real hardware. On an STM32 Nucleo-F411RE, run arm_fir_q15 and arm_fir_fast_q15 on the same block of a full-scale square wave through a 64-tap highpass. Compare the two output arrays. The fast one shows sign flips where the standard one clamps.

You add 256 Q30 products in a plain 32-bit accumulator and the input might be full scale. Roughly how many guard bits does the sum need, and where does the CMSIS standard FIR keep it?

Chapter 4

FIR Filters: The Delay Line and the Taps

Build a filter from a memory of recent samples, see what coefficient rounding does to it, and count what it costs

The microphone picks up a hiss above 3 kHz. A voice lives mostly below it. You want a filter that keeps the low part and removes the high part. Start with the simplest filter you know: average the last four samples. A rapid wiggle goes up and down inside the four, so it cancels. A slow change survives. You have built a lowpass filter.

Now improve it. Why should all four samples count the same? Give recent samples more weight and old ones less. Use eight samples, or sixty-four. The weights decide which frequencies pass. That is a FIR filter, a finite impulse response filter. It is a weighted sum of the last N input samples and nothing else.

y[n]
The output sample at time n. One new output for each new input.
∑k=0N−1
Add up N terms, for k from 0 to N−1. This is N multiply-accumulate steps (Chapter 3).
h[k]
The k-th tap, a fixed weight. All taps together are the filter’s coefficients. You design them once and store them in flash.
x[n−k]
The input sample from k ticks ago. k = 0 is the newest sample, k = 1 the one before it.

If you want the full theory of why these weights shape frequencies, the discrete signals lesson covers it. Here we take it as given and ask what the chip must do.

What the chip stores

The chip keeps the last N samples in a delay line, a buffer where each new sample pushes the oldest out. It is usually a circular buffer: a write pointer wraps around so nothing is copied. For each output the chip reads N samples and N coefficients and runs N MACs. In Q15 that is 2N bytes of delay line in RAM and 2N bytes of coefficients in flash.

CMSIS-DSP makes the state array hold numTaps + blockSize − 1 values, so one call can process a whole block. Its Q15 init function wants numTaps even and at least 4. For an odd length, add a zero tap. That is cheap insurance.

A symmetric set of taps gives a bonus: linear phase. Every frequency is delayed by the same time, (N−1)/2 samples. A 63-tap filter at 48 kHz delays audio by 31 samples, 0.65 ms. Nothing is smeared, and that matters in Chapter 8, where the delay is part of a latency budget.

Designing the taps and rounding them

You design the taps on a PC, in floating point, with a tool such as SciPy’s firwin. The result is a list of real numbers. To use them in Q15 you multiply each by 32768 and round to a whole number. That rounding moves every tap a little, by up to half a step, 1.5 × 10−5.

Does the small error matter? For the passband, no. For the stopband, the region you want silent, it can. A sharp filter cancels the stopband to 100 dB or deeper by making many terms cancel almost exactly. Rounding spoils the exact cancellation. Move the sliders and see where it bites.

Round the taps, see the stopband

Blue is the response with exact coefficients. Warm is the response after rounding to Q15. The cutoff is 3 kHz at 48 kHz. More taps give a sharper filter and cost more cycles.

63

A windowed-sinc design, cutoff 3 kHz at 48 kHz, DC gain 1. The stopband starts at 6 kHz. Cycle counts use the model of Chapter 7 (illustrative): 7 cycles per tap for naive code, 2.5 for packed SIMD code, plus 12 per sample. Coefficients are rounded to the nearest multiple of 1/32768.

With Hamming at 63 taps the float filter reaches about −62 dB in the stopband, and rounding to Q15 moves it by about 1 dB. The window is the limit, not the rounding. Now pick Blackman and push to 255 taps. The float line sinks to −108 dB, but the Q15 line stops near −70 dB and goes flat. Adding taps no longer helps. You have hit the floor of the number format.

The failure: symptom, measurement, fix

Symptom. You double the taps to remove a faint whistle. The whistle stays, and the cycle count doubles.

Measurement. Compute the frequency response of the rounded coefficients on the PC, not of the float design. A few lines of NumPy do it. Compare the stopband with the target. If the rounded filter sits above the target while the float one passes, rounding is the problem.

Fix. Use Q31 coefficients with arm_fir_q31. The steps are 65,536 times finer. It costs more cycles and twice the memory, so use it only for a deep stopband. Or lower the target: check whether 70 dB of rejection is already enough for your signal.

The core, in C

Here is the naive loop and the CMSIS call that replaces it. The naive loop is correct and slow. Chapter 7 shows exactly where its cycles go.

c/* naive: one tap at a time. x[0] is the newest sample. */
static q15_t fir_naive(const q15_t *x, const q15_t *h, int n) {
    int32_t acc = 0;
    for (int k = 0; k < n; k++)
        acc += x[k] * h[k];                  /* Q30 sum, may overflow if L1 norm > 2 */
    return (q15_t)__SSAT(acc >> 15, 16);   /* back to Q15, saturate once */
}

/* CMSIS-DSP: one call per block, 64-bit accumulator inside */
#define NUM_TAPS 64
#define BLOCK    32
static q15_t coeffs[NUM_TAPS] = { /* firwin(...) * 32768, rounded. Symmetric. */ };
static q15_t state[NUM_TAPS + BLOCK - 1];
static arm_fir_instance_q15 fir;

void dsp_init(void)  { arm_fir_init_q15(&fir, NUM_TAPS, coeffs, state, BLOCK); }
void on_block(q15_t *in, q15_t *out) { arm_fir_q15(&fir, in, out, BLOCK); }

The blocks have 32 samples. The call returns 32 outputs, using the 63 samples of history that the state array holds. At 48 kHz the 32-sample block lasts 0.667 ms, so this call must finish in 112,000 cycles. A 64-tap block costs about 32 × 172 = 5,500 cycles in the SIMD model. That is 5% of the budget.

On real hardware. On an STM32 Nucleo-F411RE, enable the cycle counter (Chapter 7 shows how), time arm_fir_q15 on a 32-sample block with 64 taps, and divide by 32. Compare with the 172 cycles per sample in this lesson’s model, then replace the call with fir_naive and compare again.

A 63-tap symmetric FIR runs at 48 kHz. Which statement is right?

Chapter 5

Biquads: Filters That Feed Back

Learn why five coefficients can replace hundreds of taps, and why rounding them can move your cutoff by 30 percent

A power supply hums at 60 Hz, and you want it gone from a microphone signal. An FIR filter that is sharp at 60 Hz and 48 kHz needs hundreds of taps, because 60 Hz is tiny next to the sample rate. At 7 cycles a tap, that is thousands of cycles for every sample. There is a cheaper way.

Think of a child on a swing. You push once and the swing keeps going for many swings. The swing remembers your push. A filter can remember too: it can feed some of its own past output back into the sum. A feedback filter keeps a long memory with very few terms. We call it an IIR filter, an infinite impulse response filter, because one input sample echoes forever, getting smaller.

The biquad

The workhorse is the biquad, a second-order section. It uses the last two inputs and the last two outputs. CMSIS-DSP documents its equation like this.

y[n]
The new output. One output per input, like the FIR.
b0, b1, b2
The feed-forward weights on the current and two past inputs. They shape the zeros of the filter.
a1, a2
The feedback weights on the two past outputs. They set the poles, which control the resonance and the cutoff. In this CMSIS convention they are added. Many textbooks and MATLAB subtract them, so flip their signs when you copy a design.

That is 5 coefficients and 4 remembered values for the whole stage. For a sharper filter you chain several biquads, a cascade. Each stage cleans up what the last one left. One long polynomial would be too sensitive to rounding. Small stages are safe. CMSIS-DSP stores 4 state values per stage, as 4 × numStages.

Arm calls this layout direct form I. It keeps real input and output samples as its state, and they already fit in Q15. That matters in fixed point. The Q15 version accumulates in 64 bits (34.30 format), then saturates to 1.15. Its “fast” sibling uses a 32-bit accumulator in 2.30 and is quicker and less precise.

Poles and the unit circle

The feedback weights place two poles. A pole is a number z that makes the feedback loop ring. If the distance of a pole from the centre of the plane, its radius, is below 1, the ringing fades and the filter is stable. At 1 it rings forever. Above 1 it grows until it overflows. So the pole must stay inside the unit circle, the circle of radius 1.

For a low cutoff the poles sit right next to the point z = 1, close to the edge of the circle. A 100 Hz lowpass at 48 kHz has a1 = 1.981 and a2 = −0.982. Their sum is almost exactly 1. Tiny errors in either number move the poles a lot, and they move the cutoff with them.

The coefficient that does not fit

Look at a1 = 1.981. A Q15 number cannot hold it, because Q15 stops below 1. If you store it as Q15 anyway, it saturates to 0.99997, and your filter becomes a different filter. The library handles this with a postShift. You store the coefficients in Q2.14, with a 2 on the integer side, so they can reach 2. The accumulator then ends up in a different scale, and postShift shifts it back by the right number of bits. The docs describe this shift register on the accumulator output.

But Q2.14 has one bit less of fraction. Each coefficient is rounded to 1/16384, which is twice as coarse. For poles near z = 1, that matters. Try it.

Round the coefficients, move the cutoff

A lowpass biquad at 48 kHz. Blue is exact. Warm is after rounding the five coefficients to the chosen format. Slide the cutoff down and watch the warm curve drift away.

100 Hz

Second-order Butterworth-style lowpass (Q = 0.7071) from the standard audio-EQ formulas, sample rate 48 kHz. The rounded curve uses exact rounding to the chosen number of fraction bits, with saturation at the Q15 word limits. It does not model the noise from rounding the output each sample.

At the 100 Hz default, Q1.15 destroys the filter: a1 saturates and the cutoff lands near 11 kHz. Q2.14 keeps the shape, but the −3 dB point moves from 100 Hz to about 70 Hz. Q3.13 is worse still. Raise the cutoff to 2 kHz and the error vanishes. Low cutoff and high sample rate are the dangerous pair.

The failure: symptom, measurement, fix

Symptom. A low filter cuts off at the wrong frequency, rings after a click, or leaves a slow drift on the output. It passes a bench test with a 1 kHz tone. It fails on bass.

Measurement. On the PC, take the rounded coefficients, compute the poles, and compute the response of what the chip really runs. Print the radius and the angle of the poles. Compare with the design.

Fix. There are three fixes, in order of effort. First, lower the sample rate: decimate (filter and drop samples) to 3 kHz, run the 100 Hz filter there, where its poles sit far from z = 1. Second, use Q31 coefficients: CMSIS-DSP lists a high-precision Q31 biquad. Third, on a core with a floating-point unit, run this one filter in float. A filter that costs 5 MACs is cheap in any format.

On real hardware. On an STM32 Nucleo-F411RE, run a 100 Hz lowpass with arm_biquad_cascade_df1_q15 and with arm_biquad_cascade_df1_f32. Feed both a 70 Hz and a 100 Hz sine and compare the output amplitudes. Time both with the cycle counter.

Why biquads, not one big filter. A single filter of order 8 has 17 coefficients (9 feed-forward and 8 feedback) and very touchy poles. Four biquads have 20 coefficients and each pole pair is moved only by its own five. Split high-order filters into biquads, always.
Your 60 Hz notch at 48 kHz works in float but wanders in Q2.14. What is the most direct reason?

Chapter 6

The FFT in Fixed Point

See which pitches are in a block of sound, and learn why a Q15 spectrum shrinks the signal and sets a floor you can measure

You want a tuner. A guitar string plays, and the screen must say whether it is sharp or flat. For that you need to know which frequencies are in the last few milliseconds of sound. A filter cannot tell you. A spectrum can: a list that says how much energy each frequency holds.

The DFT, the discrete Fourier transform, turns N samples into N frequency values by testing the signal against N waves. Done directly, that is N × N multiplies. For N = 256 that is 65,536. The FFT gives the same answer with about N × log2 N operations, which is 2,048 for N = 256. The FFT lesson derives the trick. We need only its shape.

The butterfly

The FFT splits the N-point problem into two N/2-point problems, again and again, until each piece has two points. Then it joins the results back with butterflies. A butterfly takes two complex numbers, a and b. It multiplies b by a fixed complex number called a twiddle factor, then produces a + tb and a − tb. That is one complex multiply, one add and one subtract.

N points need (N/2) × log2 N butterflies: N = 8 → 12, N = 256 → 1,024, N = 1024 → 5,120

The FFT frequency step is the sample rate divided by N. At 48 kHz and N = 256, each bin is 187.5 Hz wide. A longer block gives finer bins, and takes longer to collect: 256 samples last 5.3 ms.

Why fixed point shrinks the answer

Look at the add in a butterfly: a + tb. If both inputs are near full scale, the sum is near twice full scale. Do this over log2 N stages and the numbers can grow by N. A constant input of 0.5 gives a DC bin of N × 0.5. For N = 256 that is 128, and Q15 stops at 1.

The cure is the same headroom rule as before, applied at every stage: divide by 2 after each stage. Arm’s documentation for the Q15 real FFT states it directly. The input is 1.15, and internally the data is “downscaled by 2 for every stage to avoid saturations”. After log2 N stages the whole output is divided by N. The constant 0.5 would give a DC bin of 128. Halving at all 8 stages gives 128 ÷ 256 = 0.5, the average of the input.

The price is in the output format. The documentation lists how many integer bits the Q15 real FFT output needs, by length.

FFT lengthOutput formatBits to upscale to get back to the input scale
326.105
2569.78
102411.510
409613.312

Read the 256 row. The output is 9.7: nine integer bits and seven fraction bits. Each value is the true value divided by 256, rounded to a 16-bit word. Small bins use only the lowest bits of the word, so rounding hits them hardest. That is the real cost.

Find the quiet tone

A loud tone (half of full scale) and a quiet one go into a Hann-windowed FFT. Blue is the exact spectrum. Warm is the Q15 FFT. Lower the quiet tone until the warm line cannot see it. Then switch scaling off.

-60 dB

A complex radix-2 FFT with Q15 twiddles, rounding at every multiply and every halving, run exactly as 16-bit integers would. It is a model of the same idea as CMSIS-DSP, not its code. Levels are tone amplitude in dB below full scale (the Hann window and the half-spectrum are corrected for). The quiet tone sits at a bin centre plus a fraction. Cycle counts are the Chapter 7 model and are illustrative.

At 256 points and −60 dB the quiet tone shows up near −60 dB in both lines. At −80 dB it sinks into the warm floor, which sits near −78 dB, while the exact line still sees it. The floor does not drop as you change the length: the 16-bit words of the Q15 FFT have a fixed smallest step. Now switch off scaling. Every butterfly overflows and the spectrum is noise.

The failure: symptom, measurement, fix

Symptom. A tuner works on a loud note and loses the quiet overtones that tell a good string from a bad one. Or a spectrum shows a mass of broad noise only when the input is loud.

Measurement. Feed a known two-tone test signal, with the quiet one at −70 dB, through both the chip and a float reference on the PC. Subtract the spectra. The gap is the floor of your fixed-point path. Run it at the loudest input you allow, because that is where scaling costs most.

Fix. Pick the least bad option for the job. A longer window cannot help the floor. Use Q31 (arm_rfft_q31), which has 65,536 times finer steps. Or run the transform in float on a core with an FPU (arm_rfft_fast_f32), at a few more cycles. Or normalise the block before the FFT, so quiet blocks use more of the 16 bits, and keep track of the shift.

Two small facts from the documentation are worth knowing. The Q15 real FFT modifies its source buffer, so copy the block first if you need the audio afterwards. And the fixed-point version also produces the conjugate half of the spectrum, so its output buffer is larger than the float version’s.

On real hardware. On an STM32 Nucleo-F411RE, generate the two-tone block in a test, run arm_rfft_q15 and arm_rfft_fast_f32, convert both to dB and compare the bins. Time each call with the cycle counter. This also shows how far the model cycle counts above are from your build.

A Q15 FFT halves its data after every stage, and has log2(N) stages. What does that do to the output, compared with the exact FFT?

Chapter 7

SIMD: Two Multiplies in One Instruction

Count the cycles of a filter loop instruction by instruction, then pack two samples into one register and count again

Open the compiled loop of the FIR from Chapter 4 and read it. For every tap the chip loads a sample, loads a coefficient, multiplies and adds, counts down and jumps back. That is five or six instructions. Only one of them does the work that the filter needs. The rest is bookkeeping, and the chip pays for it in cycles.

This chapter counts that cost exactly, then removes most of it. It also explains where this lesson’s cycle numbers come from, so you can check them and replace them with your own.

What the core charges for each instruction

The Cortex-M4 Technical Reference Manual gives the timing rules. Here are the ones that matter. A load such as LDR normally takes 2 cycles. But loads are pipelined: if the next instruction is another load, and its address does not depend on the first, it costs only 1 more cycle. The manual’s examples say two independent loads take 3 cycles in total, and three take 4. A multiply or a multiply-accumulate takes 1 cycle. A branch that jumps back reloads the pipeline, which costs extra cycles; our model assumes 2 for the taken branch (an assumption, check your core).

The naive loop, tallied

Here is one tap of the naive loop, in the order the core runs it.

InstructionWhat it doesCycles
LDRSH r3, [x]Load one 16-bit sample, sign-extended2
LDRSH r4, [h]Load one 16-bit coefficient (pipelined behind the first load)1
MLA r0, r3, r4, r0Multiply and add into the accumulator1
SUBS r2, r2, #1Count down the loop counter1
BNE loopJump back if not zero (taken, with pipeline reload)2
Total per tapOne multiply-accumulate of useful work7

Seven cycles for one multiply. A 64-tap filter costs 7 × 64 = 448 cycles, plus about 12 for the shift, the saturate and the store: 460 cycles per sample. That is the number the hero used.

Packing two samples into one register

A register holds 32 bits. A Q15 sample uses 16. So one register can hold two samples, side by side. This is SIMD, single instruction multiple data: one instruction works on both halves at once.

The instruction that matters here is SMLAD, signed multiply accumulate dual. Arm describes it in the CMSIS SIMD reference: it does two signed 16 × 16 multiplies, one on the low halves and one on the high halves, adds both products and adds the sum to a 32-bit accumulator. The multiplies cannot overflow. The Q flag is set if the accumulation does. Our model charges it 1 cycle, as Arm describes the core’s single-cycle multiply-accumulate; confirm the figure in the manual for your part.

A word load now fetches two samples. So one tap pair is two word loads and one SMLAD. Unroll the loop by four taps so the loop overhead is shared:

For four tapsCycles
4 word loads (2 samples or 2 coefficients each), pipelined: 2 + 1 + 1 + 15
2 SMLAD2
Counter and branch3
Total per four taps10, or 2.5 per tap

From 7 cycles per tap to 2.5 is a speed-up of 2.8. Racing the two on the device below makes the saving visible.

Race the two loops

Each box is one instruction, as wide as its cycles. Purple boxes load data. Warm boxes multiply. Grey boxes are loop bookkeeping. Press Run to start the clock on both lanes at once.

64 taps

A hand-counted model for an STM32F407 (Cortex-M4), not a measurement. It assumes zero-wait-state memory, 2 cycles for the first load of a run and 1 for each pipelined load after it (as the Technical Reference Manual excerpt describes), 1 cycle for multiplies and SMLAD, and 2 for a taken branch. The real arm_fir_q15 shares loads between outputs and will beat this tally.

Press Run. The SIMD lane ends in 20 cycles while the naive lane is still at its fourth tap. Then drag the length to 512 taps. At 48 kHz you have 3,500 cycles per sample. Naive code needs 3,596 and misses. Packed code needs 1,292 and fits with room to spare.

Where else SIMD helps, and where it does not

The same counting gives the other kernels of this lesson. A Q15 biquad is 23 cycles per sample as plain code and 16 with packed loads and dual multiplies. That is only a 1.4 times gain. The reason is the feedback from Chapter 5: each output needs the one before it, so the chip cannot spread the work over a block. An FFT butterfly goes from 28 to 12 cycles by packing the real and imaginary halves of a complex number into one word.

KernelPlain C, cyclesPacked SIMD, cyclesGain
FIR, per tap72.52.8 times
Biquad, per sample and stage23161.4 times
FFT butterfly28122.3 times

All three rows are hand tallies from this lesson’s model, in the style of the FIR table above. They are good for comparing designs and bad for promising a deadline. For that you measure.

The core, with intrinsics

This is the packed loop written in C with the CMSIS intrinsics, and the line that measures any code on the chip.

c/* two taps per instruction. x and h must be 4-byte aligned, n even. */
static q15_t fir_simd(const q15_t *x, const q15_t *h, int n) {
    const uint32_t *xp = (const uint32_t *)x;       /* two samples per word */
    const uint32_t *hp = (const uint32_t *)h;
    uint32_t acc = 0;
    for (int k = 0; k < n / 2; k++)
        acc = __SMLAD(xp[k], hp[k], acc);          /* acc += lo*lo + hi*hi, Q30 */
    return (q15_t)__SSAT((int32_t)acc >> 15, 16);
}

/* count the cycles of anything on a Cortex-M3/M4/M7 */
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;        /* enable the trace block */
DWT->CYCCNT = 0;
DWT->CTRL  |= DWT_CTRL_CYCCNTENA_Msk;                  /* start the counter */
uint32_t t0 = DWT->CYCCNT;
arm_fir_q15(&fir, in, out, BLOCK);
uint32_t cycles = DWT->CYCCNT - t0;                    /* divide by BLOCK for cycles per sample */

The failure: symptom, measurement, fix

Symptom. You switch to CMSIS-DSP and the gain is 1.3 times, not 2.8. Or the packed loop faults on the first call.

Measurement. Read the cycle counter around the call, as above. Then check three causes. Data that is not 4-byte aligned makes word loads slow or fault on some cores. Flash wait states: at 168 MHz the STM32F407 flash needs several wait states, and its ART accelerator hides them only when it is enabled (see RM0090). Compiler flags: at -O0 the compiler keeps every value in memory and the loops are several times slower.

Fix. Align buffers with __attribute__((aligned(4))). Enable the flash accelerator and compile with -O2 or -O3. Do not count on the compiler to turn your plain loop into SMLAD. Look at the disassembly to see; it usually does not.

On real hardware. On an STM32 Nucleo-F411RE, time fir_naive, fir_simd and arm_fir_q15 on the same 64-tap block with the counter above, once with the flash cache off and once on. Write the six numbers down. They are the first real entries in your own cost table.

Why does the packed FIR gain nearly 3 times, while a Q15 biquad gains only about 1.4 times?

Chapter 8

The Cycle Budget per Block

Add up a whole chain, find the one block that misses its deadline, and measure it on the chip

Your audio chain works. You add an equaliser and it still works. You add a spectrum display. Now, every few seconds, you hear a click. The average load is 31%. How can a chip at 31% miss a deadline?

Because a deadline belongs to one block, not to the average. A real-time system fails on its worst block. This chapter shows how to find that block before the listener does.

Four costs in every block

Every block pays four things. First, the interrupt cost, the fixed price of waking up (75 cycles in our model). Second, the per-sample chain: biquads and FIR filters that run on every sample, so B samples pay B times. Third, bursts: work that runs once every few blocks, such as an FFT. Fourth, other interrupts that steal the core, such as a radio stack.

worst block
The most cycles any single block needs. This is the block that decides if the system works.
Cirq
Interrupt entry, exit and the call into your code. Paid once per block.
B · Csample
Block size times the cycles one sample costs through the whole chain (Chapters 4 to 7).
Cburst
Work that lands in some blocks only, for instance an FFT every 256 samples. It must fit inside the block that runs it.
Cother
Cycles taken by higher-priority interrupts during this block, such as a radio.
fcpu · B / fs
The block period in cycles: the clock, times the block size, divided by the sample rate. This is the deadline.

Worked example. The core runs at 168 MHz, audio is 48 kHz, blocks have 32 samples. The deadline is 168,000,000 × 32 ÷ 48,000 = 112,000 cycles. The chain has two biquads (46 cycles per sample, naive) and a 64-tap FIR (460). That is 506 per sample, 16,192 per block, plus 75 for the interrupt: 16,267, which is 14.5% of the deadline. Now add a 512-point real FFT every 256 samples. The model gives 31,744 cycles for it in naive code. Every eighth block carries it and costs 48,011 cycles, 43% of the deadline. Still fine on this chip.

Put the same chain on a part at 84 MHz with 16-sample blocks and the deadline is 28,000 cycles. The chain alone is 8,171. The FFT burst alone is 31,744, more than the whole deadline, so every sixteenth block fails. The average load is still about 36%. Averages hide this. Bars show it.

Find the late block

Each bar is one block. The yellow line is the deadline. A bar above it is a click. Switch on the FFT and the radio, then change the clock, the block size or the code style until the bars fit.

32 samples

Sample rate 48 kHz. The model uses this lesson’s illustrative cycle costs: 3 biquads, a 128-tap FIR on every sample, a real 512-point FFT (a 256-point complex FFT plus a 6-cycles-per-point split) run every 256 samples, and an invented radio that takes 0.25 ms of the core every 7.5 ms. The radio numbers are illustrative; measure your own.

Start with the defaults: 84 MHz, naive code, 32-sample blocks, EQ and FIR on. Every bar sits at 56% of the deadline. Switch the FFT on. One bar in eight jumps to 113%, above the line, while the average barely moves. Switch to CMSIS style and all bars fit: the worst is 49%. Now switch the radio on. The worst bar rises to 87% when the radio and the FFT land in the same block. That fits, but with a thin margin. Each fix costs cycles, latency or quality, and the device shows which one buys the most.

The failure: symptom, measurement, fix

Symptom. A click at a steady rhythm, such as 187 times a second at 48 kHz for an FFT every 256 samples, or only when the radio is connected.

Measurement. Set a spare pin high when the work starts and low when it ends. Put a scope or logic analyser on it. The pulse width is the work, the gap between pulses is the period, and the longest pulse is your worst block. This costs two instructions and does not change timing. For numbers per function, use the cycle counter from Chapter 7.

c/* STM32 HAL: I2S DMA ping-pong, one callback per half buffer */
#define BLOCK 32
static q15_t rx[2 * BLOCK], tx[2 * BLOCK], tmp[BLOCK];

static void work(q15_t *in, q15_t *out) {
    GPIOA->BSRR = GPIO_PIN_0;                          /* pin high: work starts */
    arm_biquad_cascade_df1_q15(&eq,  in,  tmp, BLOCK);
    arm_fir_q15(&fir, tmp, out, BLOCK);
    GPIOA->BSRR = (uint32_t)GPIO_PIN_0 << 16;           /* pin low: done. Width = cycles / f_cpu */
}
void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *h) { work(&rx[0],     &tx[0]);     }
void HAL_I2S_RxCpltCallback    (I2S_HandleTypeDef *h) { work(&rx[BLOCK], &tx[BLOCK]); }

Fix. In order of cost. Move the burst out of the interrupt: copy the block into a queue and run the FFT in a lower-priority task, so it can be preempted by the next audio block (the RTOS lesson and interrupts and DMA show how). Slice the burst: one FFT stage per block spreads 31,744 cycles over 9 blocks. Shrink it: a 256-point FFT costs less than half of a 512. Switch to SIMD code. Last, buy cycles with a faster clock, knowing it costs battery.

Latency joins the budget

A larger block gives the chain more room per call, but delays the sound. The delay through the chip is about two blocks (one filling, one draining) plus the group delay of linear-phase filters, (N−1)/2 samples each. A 128-tap FIR adds 127 ÷ 2 = 63.5 samples, 1.3 ms. With 32-sample blocks that makes 1.33 + 1.32 = 2.7 ms. For speech or a monitor that is fine. For active noise control (the next lesson in the track) it is far too long, and the filter must run sample by sample.

On real hardware. On an STM32 Nucleo-F411RE with an I2S codec board, run the callbacks above and record PA0 with a logic analyser at 48 kHz audio. Measure the longest pulse. Turn on a timer interrupt that burns 200 microseconds and see which block grows. That pulse, as a share of the block period, is your real load.

The average CPU load is 31%, but you hear a click 187 times per second at 48 kHz. What is the most likely cause, and the first check?

Chapter 9

Field Guide: The Whole Lesson on One Page

Keep the numbers, the checklist and the core code, and see where the sources came from and what is still a model

Real-time DSP on a small chip is a budget problem. The chip gives you a fixed number of cycles per sample. Fixed-point numbers make each cycle cheap but give you walls to avoid. Filters and transforms spend the cycles. SIMD buys some back. Measuring the worst block tells you if you have enough. Everything else in this lesson is detail on those five sentences.

The numbers

QuantityValueWhere it comes from
Q15 range and step−1 to 0.999969482421875; step 2−15Arm CMSIS-DSP types (1.15); Chapter 1
One 16-bit step90.3 dB below full scale20 log10(2−15); Chapter 1
Product of two Q15Q30 in 32 bits; shift right 15Chapter 1 worked example
OverflowPlain C wraps; __QADD16 and __SSAT saturateCMSIS Core SIMD reference; Chapter 2
Guard bits for N products⌈log2 N⌉ above the 31 bits of a Q30 productChapter 3
Standard Q15 FIR and biquad accumulator64-bit, 34.30; saturates to 1.15 at the endCMSIS-DSP arm_fir_q15, arm_biquad_cascade_df1_q15
Fast Q15 FIR32-bit 2.30, wraps; scale input down by log2(numTaps) bitsCMSIS-DSP arm_fir_fast_q15
FIR init rulesnumTaps even and at least 4; state = numTaps + blockSize − 1CMSIS-DSP arm_fir_init_q15
Biquad5 coefficients (6 words in Q15 with a zero), 4 state values per stage, feedback terms addedCMSIS-DSP BiquadCascadeDF1
Q15 real FFT, 256 pointsOutput 9.7; upscale 8 bits; input halved every stageCMSIS-DSP arm_rfft_q15
Budget per sample168 MHz / 48 kHz = 3,500 cyclesChapter 0
Deadline of a blockfcpu · B / fs; 112,000 cycles at B = 32Chapter 8
Cost per tap, plain and packed7 and 2.5 cycles (model)Chapter 7, hand tally; measure your own

Before you ship

The core as code

c/* one audio block: EQ biquads, then FIR. All Q15, mono, 48 kHz, 32-sample blocks. */
#define BLOCK      32
#define NUM_STAGES 3
#define NUM_TAPS   128

static q15_t bq_coeffs[6 * NUM_STAGES] = { /* per stage: b0, 0, b1, b2, a1, a2 in Q2.14 */ };
static q15_t bq_state[4 * NUM_STAGES];
static arm_biquad_casd_df1_inst_q15 eq;

static q15_t fir_coeffs[NUM_TAPS] = { /* designed in float, x 32768, rounded, checked */ };
static q15_t fir_state[NUM_TAPS + BLOCK - 1];
static arm_fir_instance_q15 fir;

void dsp_init(void) {
    arm_biquad_cascade_df1_init_q15(&eq, NUM_STAGES, bq_coeffs, bq_state, 1);  /* postShift 1 for Q2.14 */
    arm_fir_init_q15(&fir, NUM_TAPS, fir_coeffs, fir_state, BLOCK);
}

void dsp_block(q15_t *in, q15_t *out) {      /* runs once per block, from the DMA callback */
    static q15_t tmp[BLOCK];
    arm_biquad_cascade_df1_q15(&eq, in, tmp, BLOCK);
    arm_fir_q15(&fir, tmp, out, BLOCK);
}

Where this sits

This lesson is the fourth of the audio track. The wire brings samples in, the DMA ping-pong hands them to you in blocks, and the codec sets how loud they arrive, which decides your headroom. What you built here is the processing in the middle. The start-up lesson and the pipeline lesson explain the pipeline and flash behaviour behind the cycle counts.

Keep going

Sources, and what stays a model

Opened for this lesson: the CMSIS-DSP pages for the Q15 biquad cascade, the FIR filters, the real FFT and the Q15 real FFT; the Arm CMSIS Core SIMD intrinsics reference; and an excerpt of the Cortex-M4 Technical Reference Manual (r0p1) on load and store timing, hosted by a university course.

Not verified here, and used as stated assumptions: that SMLAD takes one cycle; that entering an interrupt takes 12 cycles with zero-wait-state memory (a commonly quoted figure); that a taken branch costs 2 cycles; and the STM32F407’s 168 MHz maximum clock and flash wait states, which should be checked in its datasheet and in RM0090. Every cycle tally in the devices is a hand-counted model for comparing designs. Replace it with numbers from the cycle counter before you trust a deadline.

Credit: the library behaviour comes from Arm’s CMSIS-DSP documentation. The lesson, its devices and its models are original to this series. This lesson did not use a course, so there are no slides to credit.

The takeaway. Count first, then write. Know the cycles per sample, keep every value inside its Q format, saturate at the walls, and judge the system by its worst block.
You must ship a 48 kHz audio chain on a Cortex-M4. Which plan follows this lesson?

Now press Teach and explain from memory why a Q15 multiply needs a shift, what the 64-bit accumulator protects, and how you would find the one late block. Then go back to the hero, slide the filter to 512 taps, and say which lesson chapter explains each part of the bar.

Real-Time DSP on a Cortex-M
CMSIS-DSP documentation · CMSIS Core SIMD intrinsics · Back to the audio track