Simvik

Fix: the summed reading is wrong

A conversion macro without parentheses mixes its argument into the surrounding arithmetic. An easy embedded C problem (Inline functions and macros), run and…

easy · Inline functions and macros · find-the-bug · macros · precedence

Bug report. SCALE_MV(raw) converts a 12-bit ADC count (0 to 4095) to millivolts on a 3.3 V reference. It works for a single reading, but sum_mv(a, b), which converts the sum of two readings, returns far too much. Fix it by changing one line.

Starter code

#define SCALE_MV(raw) raw * 3300 / 4095

uint32_t sum_mv(uint32_t a, uint32_t b) {
  return SCALE_MV(a + b);
}

Example tests

Two equal readings

printf("%u\n", sum_mv(1000, 1000));

Expected output:

1611

Learn it first

More Inline functions and macros problems