Simvik

Fix: the energy counter loses energy

An energy meter multiplies in 32 bits and only then adds to a 64-bit total. An easy embedded C problem (Static analysis and MISRA in practice), run and…

easy · Static analysis and MISRA in practice · find-the-bug · static-analysis · misra · integer-promotion · overflow

Bug report. The energy totals of a power meter are far too low when it reports over long intervals. The static analyser flagged this line under MISRA C Rule 10.6 ("a composite expression assigned to a wider type"), and the finding was suppressed as a false positive, because "the total is 64 bits".

mv * ma is computed as int, and multiplying by the 32-bit dt_ms happens in 32 bits. Only the wrapped result is widened. Fix meter_add by changing one line, so the whole product is computed in 64 bits.

Starter code

void meter_add(meter_t *m, uint16_t mv, uint16_t ma, uint32_t dt_ms) {
  m->energy_nJ += mv * ma * dt_ms;
}

Example tests

A short interval, then a long one

meter_t m = {0};
add(&m, 3300, 500, 10);
add(&m, 3300, 2000, 1000);

Expected output:

16500000 nJ
6616500000 nJ

Learn it first

More Static analysis and MISRA in practice problems