Simvik

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_raw millivolts, and
  • a channel reading raw is supply * raw / 4095 millivolts.

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:

3000

A sagging supply

printf("%u\n", adc_to_mv(2048, 1650, 1500));

Expected output:

1364

Learn it first

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

More ADC problems