Fix: the filter output is one sample late
An FIR filter's impulse response comes out shifted by one sample. A medium embedded C problem (Digital filters: FIR and IIR), run and graded in the browser.
medium · Digital filters: FIR and IIR · find-the-bug · dsp · fir
Bug report. The FIR filter y[n] = h[0]·x[n] + h[1]·x[n-1] + ... + h[3]·x[n-3] gives the right shape of output, but everything comes out one sample late: feeding an impulse gives 0 first, then the coefficients. A one-sample delay matters here, because the filter runs inside a control loop.
Find the defect in fir_step and fix it, changing at most two lines.
Starter code
int32_t fir_step(fir_t *f, int16_t x) {
int32_t acc = 0;
for (int k = TAPS - 1; k > 0; k--) f->z[k] = f->z[k - 1]; // age the delay line
for (int k = 0; k < TAPS; k++) acc += (int32_t)f->h[k] * f->z[k];
f->z[0] = x;
return acc;
}Example tests
Impulse response
int16_t x[] = { 100, 0, 0, 0, 0 };
feed(1, 2, 3, 4, x, 5);Expected output:
100 200 300 400 0Learn it first
- Digital filters: FIR and IIR · Moving averages, FIR and IIR filters, biquads and notch filters.
More Digital filters: FIR and IIR problems
- Moving average with a running sum · Average the last few samples with one add and one subtract per sample.
- Exponential smoothing without stalling · A first-order IIR filter in integers that keeps extra fractional bits so it reaches the input.
- ECG patch: smooth the heartbeat signal · A running four-sample average that keeps a constant cost per sample and starts cleanly.