Compensate for the supply voltage
Convert a reading to millivolts using the internal reference instead of an assumed 3.3 V. A medium embedded C problem (ADC), run and graded in the browser.
medium · ADC · adc · calibration · overflow
An ADC measures relative to its supply, so a battery that sags from 3.3 V to 2.8 V shifts every reading. Most MCUs have an internal voltage reference you can convert alongside, plus a factory value vref_cal: the reference's reading when the supply was exactly 3000 mV.
With a 12-bit ADC (full scale 4095):
- the actual supply is
3000 * vref_cal / vref_rawmillivolts, and - a channel reading
rawissupply * raw / 4095millivolts.
Return the channel voltage in millivolts, rounded to the nearest integer. If vref_raw is 0, return 0.
Starter code
uint32_t adc_to_mv(uint16_t raw, uint16_t vref_raw, uint16_t vref_cal) {
return raw * 3300u / 4095u;
}Example tests
Supply at exactly 3.0 V, full scale
printf("%u\n", adc_to_mv(4095, 1500, 1500));Expected output:
3000A sagging supply
printf("%u\n", adc_to_mv(2048, 1650, 1500));Expected output:
1364Learn 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.
- 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.