Simvik

Running median spike filter

Filter a stream with a median over a sliding window of five, keeping the window in arrival order. A medium embedded C problem (Sensors and sensor fusion),…

medium · Sensors and sensor fusion · sensor · filter · sorting

A moving average smears a single wild reading (a spike from a loose connector or an ultrasonic echo) across several outputs. A median filter throws it away.

Write median5(m, x): put x into the window in place of the oldest sample and return the median of the five samples in it. On the very first call, fill the whole window with x.

The window must keep its arrival order so that the oldest sample is the one replaced, so sort a copy.

Starter code

int16_t median5(med_t *m, int16_t x) {
  m->win[m->pos] = x;
  m->pos = (m->pos + 1) % MED_LEN;
  // sort the window and take the middle
  for (int i = 1; i < MED_LEN; i++)
    for (int j = i; j > 0 && m->win[j - 1] > m->win[j]; j--) {
      int16_t t = m->win[j]; m->win[j] = m->win[j - 1]; m->win[j - 1] = t;
    }
  return m->win[MED_LEN / 2];
}

Example tests

A spike in a steady signal

int16_t x[] = { 100, 102, 5000, 101, 99, 103 };
feed(x, 6);

Expected output:

100 100 100 101 101 102

A real step gets through

int16_t x[] = { 0, 1000, 1000, 1000, 1000, 1000, 1000 };
feed(x, 7);

Expected output:

0 0 0 1000 1000 1000 1000

Learn it first

More Sensors and sensor fusion problems