Simvik

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:

1000

A single reading

uint16_t s[] = {4095};
printf("%u\n", adc_average(s, 1));

Expected output:

4095

Learn it first

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

More ADC problems