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:
30One spike
uint16_t s[5] = { 500, 502, 4095, 501, 499 };
printf("%u\n", median5(s));Expected output:
501Learn it first
- ADC · Resolution, sampling, noise, oversampling and DMA.
More ADC problems
- Oversample for extra bits · Gain resolution from a noisy ADC by summing and shifting.
- Compensate for the supply voltage · Convert a reading to millivolts using the internal reference instead of an assumed 3.3 V.
- Scan the multiplexer channels · Convert each enabled ADC channel in turn from the conversion-complete interrupt.
- Detect an open or shorted sensor · Report a sensor fault when readings sit at a rail for three samples in a row.
- Fix: a random battery voltage at power-up · An average starts from whatever was in memory.
- Greenhouse: calibrated soil moisture · Turn a soil probe reading into a percentage using the probe's own calibration.