Simvik

Fix: the battery always shows 0 %

Dividing before multiplying throws the whole result away in integer arithmetic. An easy embedded C problem (Fixed-point and signal processing), run and…

easy · Fixed-point and signal processing · find-the-bug · integer-division · order-of-operations

Bug report. battery_percent(now_mv, empty_mv, full_mv) should map the battery voltage onto 0 to 100 %, rounding down. The display shows 0 % until the battery is completely full, when it jumps to 100 %. Fix it by changing one line.

Starter code

unsigned battery_percent(unsigned now_mv, unsigned empty_mv, unsigned full_mv) {
  if (now_mv <= empty_mv) return 0;
  if (now_mv >= full_mv) return 100;
  return (now_mv - empty_mv) / (full_mv - empty_mv) * 100;
}

Example tests

Half and nearly full

printf("%u %u\n", battery_percent(3600, 3300, 3900), battery_percent(3894, 3300, 3900));

Expected output:

50 99

Learn it first

More Fixed-point and signal processing problems