Simvik

Exponential smoothing without stalling

A first-order IIR filter in integers that keeps extra fractional bits so it reaches the input. A medium embedded C problem (Digital filters: FIR and IIR),…

medium · Digital filters: FIR and IIR · dsp · iir · fixed-point

The exponential moving average y = y + (x - y) / 2^shift smooths ADC readings with one subtract and one shift. Done in plain integers it has a flaw: once x - y is smaller than 2^shift, the step rounds to zero and y never reaches x.

Write ema_update(f, x) that keeps y in Q8 (acc holds y * 256):

  • On the first sample, set the output to x exactly.
  • After that, acc += ((x << 8) - acc) >> shift.
  • Return the output rounded to the nearest integer: (acc + 128) >> 8.

Inputs are ADC readings from 0 to 4095.

Starter code

uint16_t ema_update(ema_t *f, uint16_t x) {
  f->acc += ((int32_t)x - f->acc) >> f->shift;
  return (uint16_t)f->acc;
}

Example tests

A step from 0 to 1000

ema_t f = { 0, 2, false };
step(&f, 0, 1, true);
step(&f, 1000, 6, true);
printf("\n");

Expected output:

0 250 438 578 684 763 822

Learn it first

More Digital filters: FIR and IIR problems