Simvik

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 0

Learn it first

More Digital filters: FIR and IIR problems