Skip to content
systemcoding.dev
Embedded

Use CMSIS-DSP Q15 and Q31 Functions for Filtering

Call arm_fir_q15 and arm_biquad_cascade_df1_q31 from CMSIS-DSP to filter fixed-point samples on a Cortex-M, with correct state sizes, scaling and block layout.

6 min read
Summarize in AI
Flat illustration of video frames passing through a codec, with the Arm, C and VLC media player logos.

CMSIS-DSP is Arm's library of signal-processing kernels for Cortex-M. It ships fixed-point versions of the common filters, and on cores with the DSP extension (Cortex-M4, M7, M33 and others) those kernels use packed 16-bit multiply-accumulate instructions that a plain C loop will not reach. The catch is that the API has sharp edges: state arrays whose size is a formula, coefficient layouts that differ per filter, and a fixed-point scaling convention you have to apply by hand. This post walks a Q15 FIR filter and a Q31 biquad cascade end to end, using the CMSIS-DSP 1.x API (the 1.16 line, with the arm_ prefixed C functions declared in arm_math.h).

What Q15 and Q31 mean to the library

q15_t is int16_t and q31_t is int32_t. A q15_t value x represents x / 32768, and a q31_t represents x / 2^31. Both span -1.0 up to just under 1.0. Inputs and coefficients must already be in that range. If you feed raw 12-bit ADC counts straight in, you are not filtering anything meaningful; you must scale first, for example by shifting a 12-bit unsigned sample into the high bits and removing the offset. The library does not normalize anything for you.

A Q15 FIR filter with arm_fir_q15

A finite impulse response filter computes y[n] = sum(b[k] * x[n-k]). CMSIS-DSP keeps the history of past inputs in a state array that you provide, so the filter can process one block of samples per call and continue seamlessly into the next.

The instance is initialized with arm_fir_init_q15(). Its signature is:

c
arm_status arm_fir_init_q15(arm_fir_instance_q15 *S,
                            uint16_t numTaps,
                            const q15_t *pCoeffs,
                            q15_t *pState,
                            uint32_t blockSize);

Two rules matter. First, pState must hold numTaps + blockSize - 1 elements; the function does not check this. Second, on the Cortex-M4 and M7 implementations numTaps must be even, and the init function returns ARM_MATH_ARGUMENT_ERROR if it is not. Pad an odd filter with a zero coefficient. The coefficients are stored in the order b[numTaps-1], ..., b[1], b[0], reversed from how you would write the impulse response, and the documentation says so explicitly.

Here is a 4-tap moving average, each coefficient 0.25. In Q15, 0.25 is 8192. A symmetric filter reads the same reversed, so the order is moot here, but we keep the comment for the asymmetric case.

fir_q15.cc
#include "arm_math.h"

#define NUM_TAPS    4
#define BLOCK_SIZE  8

/* b[3], b[2], b[1], b[0]: reversed order, as the library requires. */
static const q15_t coeffs[NUM_TAPS] = { 8192, 8192, 8192, 8192 };

static q15_t fir_state[NUM_TAPS + BLOCK_SIZE - 1];
static arm_fir_instance_q15 fir;

void filter_init(void)
{
    arm_fir_init_q15(&fir, NUM_TAPS, (q15_t *)coeffs, fir_state, BLOCK_SIZE);
}

void filter_block(const q15_t *in, q15_t *out)
{
    arm_fir_q15(&fir, (q15_t *)in, out, BLOCK_SIZE);
}

The cast away from const is needed because the init and process functions in this API take non-const pointers even though they do not write coefficients or input. Do not remove it by editing the library header; a cast at the call site is the portable answer.

Feed it a constant input of 16384 (0.5) for eight samples, with the state zeroed at start:

c
q15_t in[BLOCK_SIZE]  = {16384,16384,16384,16384,16384,16384,16384,16384};
q15_t out[BLOCK_SIZE];
filter_init();
filter_block(in, out);
for (int i = 0; i < BLOCK_SIZE; i++) printf("%d ", out[i]);
Text
4096 8192 12288 16384 16384 16384 16384 16384

The first output includes one real sample and three zeros from the empty history: 0.25 * 0.5 = 0.125, which is 4096. By the fourth sample all four taps hold real data and the output settles at 0.5 (16384). That ramp is the filter's transient, and it lasts numTaps - 1 samples.

How the fixed-point arithmetic behaves

arm_fir_q15 accumulates products in a 64-bit accumulator on cores with the right hardware, or in 32 bits on others, then shifts and saturates once at the end, so internal overflow is much less likely than with a hand-written loop that saturates each step. The result is saturated to q15_t. That is still not magic: if your coefficients sum to more than 1.0 and the input is near full scale, the output will clip. The standard cure is to scale the coefficients so their absolute values sum to at most 1.0, or to keep some headroom in the input.

A related trap is the precision loss from quantizing the coefficients. A Q15 coefficient has a resolution of 2^-15, about 0.00003. A narrow low-pass filter with a transition band of a few percent of the sample rate can have stopband attenuation that quantization visibly degrades. If a Q15 filter misses its spec while the floating-point design met it, try Q31 coefficients before redesigning.

A Q31 biquad cascade

An IIR filter built from second-order sections (biquads) is far cheaper than a long FIR for sharp responses. CMSIS-DSP provides arm_biquad_cascade_df1_q31 and its init:

c
void arm_biquad_cascade_df1_init_q31(arm_biquad_casd_df1_inst_q31 *S,
                                     uint8_t numStages,
                                     const q31_t *pCoeffs,
                                     q31_t *pState,
                                     uint8_t postShift);

Each stage takes five coefficients in the order b0, 0, b1, b2, a1, a2: that is six numbers per stage, because the library keeps a zero slot for alignment with the DSP instructions. The state is four values per stage (x[n-1], x[n-2], y[n-1], y[n-2]), so pState has 4 * numStages elements. The feedback coefficients a1 and a2 are stored with the sign convention of the library: the difference equation is y[n] = b0*x[n] + b1*x[n-1] + b2*x[n-2] + a1*y[n-1] + a2*y[n-2], so you pass a1 and a2 negated relative to the textbook form that subtracts them. Getting this sign wrong produces an unstable or wrong filter, and it is the most common mistake with this function.

postShift is the key to Q31 biquads. Coefficients in Q31 can only represent values in [-1, 1), but biquad coefficients routinely exceed 1 in magnitude (a1 is often near 2). The solution is to scale the coefficients down by 2^postShift when you store them, and the library shifts the accumulator left by postShift bits after summing. So if your largest coefficient is 1.9, use postShift = 1, store every coefficient divided by 2, and the library multiplies back.

biquad_q31.cc
#include "arm_math.h"

#define STAGES 1

/* One low-pass stage. Real coefficients: b0=0.0675, b1=0.1349, b2=0.0675,
   a1(lib)=1.1430, a2(lib)=-0.4128. Largest magnitude is above 1, so
   postShift = 1 and every value is stored divided by 2, in Q31. */
static const q31_t bq_coeffs[5 * STAGES + STAGES] = {
    72494460,   /* b0 / 2 */
    0,
    144988920,  /* b1 / 2 */
    72494460,   /* b2 / 2 */
    1227328000, /* a1 / 2 */
    -443235000  /* a2 / 2 */
};
static q31_t bq_state[4 * STAGES];
static arm_biquad_casd_df1_inst_q31 bq;

void biquad_init(void)
{
    arm_biquad_cascade_df1_init_q31(&bq, STAGES, (q31_t *)bq_coeffs,
                                    bq_state, 1);
}

void biquad_run(const q31_t *in, q31_t *out, uint32_t n)
{
    arm_biquad_cascade_df1_q31(&bq, (q31_t *)in, out, n);
}

The Q31 values come from multiplying each real number by 2^31 after dividing by 2: 0.0675 / 2 * 2147483648 is about 72494460. Compute them in a script or a spreadsheet at design time and paste them in, rather than doing the conversion on the target.

Converting between float and fixed

CMSIS-DSP includes arm_float_to_q15 and arm_q15_to_float, along with the Q31 pair. They saturate on conversion, so a value of 1.2 becomes 32767, and they process whole arrays:

c
float32_t f[4] = {0.5f, -0.5f, 1.2f, 0.0f};
q15_t q[4];
arm_float_to_q15(f, q, 4);
Text
q = {16384, -16384, 32767, 0}

Use these at the edges of the system (calibration tables, host-side tests) and keep the inner loop entirely in fixed point.

Where this does not fit

If the chip has a single-precision FPU, arm_fir_f32 and arm_biquad_cascade_df2T_f32 are usually the better first choice: no scaling, no postShift, and the dynamic range problems go away. Fixed point earns its place on cores without an FPU, such as the Cortex-M3, or where you need bit-exact results across builds. Also note that CMSIS-DSP picks its implementation from the compile-time core definition; building for a Cortex-M0 gets a generic C path, with none of the SIMD speed-up that motivated Q15 here.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.