Simvik

Median of five samples

Reject a single spike by taking the median instead of the average. An easy embedded C problem (ADC), run and graded in the browser.

easy · ADC · adc · filter · sorting

A single spike from a motor or a relay can ruin an average. The median of a few samples ignores it.

Return the median of the five samples. Do not modify the caller's array.

Starter code

uint16_t median5(const uint16_t s[5]) {
  uint32_t sum = 0;
  for (int i = 0; i < 5; i++) sum += s[i];
  return (uint16_t)(sum / 5);
}

Example tests

Evenly spread samples

uint16_t s[5] = { 10, 20, 30, 40, 50 };
printf("%u\n", median5(s));

Expected output:

30

One spike

uint16_t s[5] = { 500, 502, 4095, 501, 499 };
printf("%u\n", median5(s));

Expected output:

501

Learn it first

  • ADC · Resolution, sampling, noise, oversampling and DMA.

More ADC problems