Skip to content
systemcoding.dev
Embedded

Implement a Fixed-Point FIR Filter in C

Write a Q15 FIR filter in portable C with a circular delay line, a 32-bit accumulator and one saturating shift at the end, with worked moving-average output.

7 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the C, Arm and Espressif logos.

A finite impulse response filter is a weighted sum of the last N inputs, and that is all it is. Fixed point makes it interesting for one reason: where you let the sum grow before you shrink it. Shrink too early and you throw away precision on every tap. Shrink too late, in too narrow a type, and the sum wraps. This post writes a Q15 FIR in plain C99 with a circular buffer, and shows why a 32-bit accumulator and a single shift at the end are the right shape. The code builds on a laptop and on any MCU, with no vendor library.

The equation and its fixed-point form

A FIR of N taps computes y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[N-1]*x[n-N+1]. Store the inputs and coefficients in Q15 (int16_t, value v / 32768). Each product b[k] * x[n-k] has 30 fraction bits, so it fits an int32_t with room to spare: the largest magnitude is 32768 * 32768 = 2^30. If you add N of them in a 32-bit accumulator, you can overflow after only two worst-case products, because 2 * 2^30 = 2^31, one past INT32_MAX.

There are three honest ways to handle this.

  1. Use a 64-bit accumulator. Always safe, slow on cores with a 32-bit datapath.

  2. Bound the coefficients. If the absolute values of the coefficients sum to at most 1.0 (in real terms), no input in range can overflow the sum, because |y| <= sum(|b|) * max|x|. A low-pass filter normalized to unity DC gain satisfies this.

  3. Shift each product before accumulating. Safe in 32 bits, but you lose low bits N times.

We take option 2 with a guard: assert the coefficient bound at design time, keep a 32-bit accumulator, and shift once at the end. That is both fast and precise.

The data structure

A circular buffer avoids shifting the whole history every sample. The write index walks forward and wraps; the newest sample sits at the write index, and older samples are behind it.

fir.hc
#include <stdint.h>

#define FIR_TAPS 5

typedef struct {
    const int16_t *coeffs;      /* FIR_TAPS values, coeffs[0] applies to newest */
    int16_t        hist[FIR_TAPS];
    uint8_t        pos;         /* index of the newest sample */
} fir_q15_t;

static inline int16_t sat16(int32_t x)
{
    if (x > INT16_MAX) return INT16_MAX;
    if (x < INT16_MIN) return INT16_MIN;
    return (int16_t)x;
}

void    fir_init(fir_q15_t *f, const int16_t *coeffs);
int16_t fir_step(fir_q15_t *f, int16_t x);

Note the layout choice: coeffs[0] multiplies the newest sample. Some libraries store coefficients reversed; ours does not, and it makes the inner loop easy to read.

The implementation

fir.cc
#include "fir.h"
#include <string.h>

void fir_init(fir_q15_t *f, const int16_t *coeffs)
{
    f->coeffs = coeffs;
    memset(f->hist, 0, sizeof f->hist);
    f->pos = 0;
}

int16_t fir_step(fir_q15_t *f, int16_t x)
{
    /* advance first so pos always names the slot being overwritten */
    f->pos = (f->pos + 1u == FIR_TAPS) ? 0u : (uint8_t)(f->pos + 1u);
    f->hist[f->pos] = x;

    int32_t acc = 0;
    uint8_t idx = f->pos;
    for (uint8_t k = 0; k < FIR_TAPS; k++) {
        acc += (int32_t)f->coeffs[k] * (int32_t)f->hist[idx];
        idx = (idx == 0u) ? (FIR_TAPS - 1u) : (uint8_t)(idx - 1u);
    }

    acc += (int32_t)1 << 14;        /* round to nearest */
    return sat16(acc >> 15);        /* Q30 -> Q15 */
}

Walk through the index logic, because that is where circular buffers go wrong. pos moves forward and the new sample is written there. The sum then starts at pos (newest, tap 0) and walks backward with wraparound, so tap k reads the sample k steps old. No modulo operator appears: on an M0, % on a non-power-of-two compiles to a library division call, so the explicit compare-and-reset is cheaper.

Check it with a moving average

Five taps of 0.2 each form a moving average. In Q15, 0.2 is 6554 (0.2 * 32768 = 6553.6, rounded). Their sum is 32770, a hair over 1.0, which is the quantization error showing up; for production, adjust one coefficient to 6553 so the sum is exactly 32767 or less. We keep 6554 here because it makes the rounding visible.

main.cc
#include <stdio.h>
#include "fir.h"

int main(void)
{
    static const int16_t avg5[FIR_TAPS] = {6554, 6554, 6554, 6554, 6554};
    fir_q15_t f;
    fir_init(&f, avg5);

    int16_t in[8] = {0, 0, 20000, 20000, 20000, 20000, 20000, 0};
    for (int i = 0; i < 8; i++) {
        printf("%d ", fir_step(&f, in[i]));
    }
    printf("\n");
    return 0;
}
Text
0 0 4000 8000 12001 16001 20001 16001

Check the third output: only the newest sample is 20000, so 6554 * 20000 = 131080000, plus 16384 is 131096384, and >> 15 is 4000. Two samples give 262176384, which shifts to 8000. Three samples give 393256384, which shifts to 12001, and the extra 1 is the coefficient quantization showing: 6554 is slightly more than 0.2. By the seventh output all five taps hold 20000: 655416384 >> 15 is 20001. The last output drops the oldest-but-one sample out of the window, leaving four taps of 20000, so it is 16001.

The steady-state error of one count comes from the coefficient sum, 5 * 6554 = 32770, which is 32770 / 32768 of unity. Replace one tap with 6553 and the sum is 32769; use 6553 for two taps and the sum drops to 32768, exactly unity gain, and the steady state lands on 20000.

Exploit symmetry to halve the multiplies

Most FIR filters designed for a flat group delay are symmetric: b[k] == b[N-1-k]. The sample at tap k and the sample at tap N-1-k then share a coefficient, so you can add the two samples first and multiply once. For an odd tap count the middle tap stands alone. The pre-add of two int16_t values must be done in int32_t, since two full-scale samples sum to 65534, which no 16-bit type holds.

c
int32_t acc = 0;
uint8_t lo = f->pos;                                  /* newest */
uint8_t hi = (uint8_t)((f->pos + 1u) % FIR_TAPS);     /* oldest */
for (uint8_t k = 0; k < FIR_TAPS / 2; k++) {
    int32_t pair = (int32_t)f->hist[lo] + (int32_t)f->hist[hi];
    acc += (int32_t)f->coeffs[k] * pair;
    lo = (lo == 0u) ? (FIR_TAPS - 1u) : (uint8_t)(lo - 1u);
    hi = (hi + 1u == FIR_TAPS) ? 0u : (uint8_t)(hi + 1u);
}
acc += (int32_t)f->coeffs[FIR_TAPS / 2] * (int32_t)f->hist[lo];

The pair sum can reach 65534, and multiplied by a Q15 coefficient up to 32767 the product is near 2^31, so the earlier overflow bound now needs checking against the pre-added value: keep sum(|b|) * 32767 below INT32_MAX with the pairs counted twice. For a unity-gain low-pass that still holds. Here the one % on a compile-time constant is acceptable, because the compiler turns a constant modulus into multiply-and-shift or, for 5, a short sequence; replace it with the compare-and-reset if the profile says otherwise. The gain is real on cores where a multiply costs more than an add, and it is free on any core when the filter is symmetric.

When a 64-bit accumulator is the right call

If you cannot bound the coefficients, for example a filter that amplifies a band, switch the accumulator to int64_t and keep everything else the same. The only change is the type of acc, the rounding constant ((int64_t)1 << 14) and a saturating cast on the way out. On a Cortex-M3 or later the compiler emits SMLAL, a single multiply-accumulate into a 64-bit pair, so the cost is small. On a Cortex-M0 it calls a helper per tap, and that is the signal to redesign the filter with a smaller gain rather than widen the type.

Where this goes wrong

Coefficient sum over 1.0. A high-gain filter can overflow the accumulator even when each product is fine. Either prove the bound, scale the coefficients down, or widen the accumulator to int64_t. The worst-case input for a bound check is x[n-k] = INT16_MAX * sign(b[k]), which gives sum(|b|) * 32767.

Odd rounding. Adding 1 << 14 and shifting rounds half up. For a long filter, that is fine. For control loops where a tiny constant bias matters, see how truncation accumulates in a later post on rounding.

Cost. The inner loop is one 16x16 multiply-accumulate per tap. On a Cortex-M3 or M4 that compiles to SMLABB or a plain MLA and runs in a handful of cycles per tap. On cores with the DSP extension, a library kernel can process two taps per instruction, which a portable C loop will not do. This code is for clarity, portability and host testing, not for maximum throughput.

Testing it on the host

Because this is plain C, test it where you can see the values. Feed an impulse (a single 32767 followed by zeros) and the output should replay the coefficients, scaled by 32767 / 32768. Feed a constant and the output should settle to x * sum(b). Feed a full-scale square wave and check that nothing wraps negative where it should be positive. These three checks catch nearly every indexing and overflow bug in a FIR, and they need no hardware.

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.