Fix: a random battery voltage at power-up
An average starts from whatever was in memory. An easy embedded C problem (ADC), run and graded in the browser.
easy · ADC · find-the-bug · uninitialised · averaging
Bug report. The battery voltage shown after power-up is wildly wrong, and different on every board. The raw ADC samples logged next to it look fine.
adc_average returns the mean of n samples, rounded down; n is always at least 1 and at most 64. Find the defect and fix it by changing one line. Run the examples to see what the interpreter reports.
Starter code
uint16_t adc_average(const uint16_t *samples, uint8_t n) {
uint32_t sum;
for (uint8_t i = 0; i < n; i++) sum += samples[i];
return (uint16_t)(sum / n);
}Example tests
Four readings around 1000
uint16_t s[] = {1000, 1010, 990, 1000};
printf("%u\n", adc_average(s, 4));Expected output:
1000A single reading
uint16_t s[] = {4095};
printf("%u\n", adc_average(s, 1));Expected output:
4095Learn it first
- ADC · Resolution, sampling, noise, oversampling and DMA.
More ADC problems
- Median of five samples · Reject a single spike by taking the median instead of the average.
- 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.
- Greenhouse: calibrated soil moisture · Turn a soil probe reading into a percentage using the probe's own calibration.