Simvik

Battery voltage through a resistor divider

Read the divider ratio and the ADC's reference voltage off the schematic, and turn a raw reading into millivolts. An easy embedded C problem (Reading…

easy · Reading datasheets and schematics · schematics · adc · fixed-point

The firmware has to report the battery voltage. Working from the Datasheet excerpt below, write uint32_t vbat_mv(uint16_t raw), which turns the ADC's reading of PA1 into the battery voltage in millivolts, rounded to the nearest millivolt.

Do it in integer arithmetic: this microcontroller has no floating-point unit.

Datasheet excerpt

Board schematic, sheet 2 (power)

BT1 (+) ── VBAT ──[R12 100 kΩ 1 %]──┬── ADC_VBAT ── PA1 (ADC1_IN1)
2S Li-ion, 6.0–8.4 V                │
                                    ├──[R13 47 kΩ 1 %]── GND
                                    │
                                    └──|| C20 100 nF ── GND

VBAT ── U4 (LDO, 3.0 V fixed) ── VDD_3V0 ── VDD, VDDA, VREF+

ADC (microcontroller datasheet)

12-bit result, 0 to 4095. The input range is VSSA to VREF+: a result of 4095 means VREF+.

Starter code

uint32_t vbat_mv(uint16_t raw) {
  return (uint32_t)raw * 3300 / 4095;
}

Example tests

A battery near empty

show(2620);

Expected output:

2620 -> 6003 mV

Learn it first

More Reading datasheets and schematics problems