Oversample for extra bits
Gain resolution from a noisy ADC by summing and shifting. A medium embedded C problem (ADC), run and graded in the browser.
medium · ADC · adc · oversampling · resolution
Averaging only reduces noise. Oversampling can also add resolution: summing 4^n samples and shifting the sum right by n gives an ADC reading with n extra bits, provided there is some noise to dither the input.
count is always 4 to the power extra_bits. Return the oversampled reading. The result for a 12-bit ADC with 4 extra bits fills 16 bits.
Starter code
uint16_t oversample(const uint16_t *samples, size_t count, uint8_t extra_bits) {
uint16_t sum = 0;
for (size_t i = 0; i < count; i++) sum += samples[i];
return sum / count;
}Example tests
One extra bit from four samples
uint16_t s[4] = { 100, 101, 101, 102 };
printf("%u\n", oversample(s, 4, 1));Expected output:
202Two extra bits at full scale
uint16_t s[16];
for (int i = 0; i < 16; i++) s[i] = 4095;
printf("%u\n", oversample(s, 16, 2));Expected output:
16380Learn 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.
- 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.