Essential types in sensor maths
Make three small sensor functions pass MISRA's essential type rules, without changing their results. A hard embedded C problem (Static analysis and MISRA in…
hard · Static analysis and MISRA in practice · misra · static-analysis · essential-types · integer-promotion · fixed-point
MISRA C judges arithmetic by essential type: the type before integer promotion, with an unsigned constant as narrow as its value. For example, u16 * 3300U is essentially a 16-bit unsigned operation, even though C computes it in int. Code written that way does not depend on what int is on the next chip.
These three functions give the right results on this target, but the checker reports several findings. Fix them all, without changing any result:
average(s, n): the mean ofnsamples (n> 0), rounded down.scale_mv(raw): a 12-bit ADC reading as millivolts,raw * 3300 / 4095, rounded down.delta(a, b):a - bas a signed value (the readings differ by less than 32768).
Starter code
uint16_t average(const uint16_t *s, uint8_t n) {
uint32_t sum = 0;
for (uint8_t i = 0; i < n; i++) {
sum += s[i];
}
return sum / n;
}
uint32_t scale_mv(uint16_t raw) {
return raw * 3300 / 4095;
}
int16_t delta(uint16_t a, uint16_t b) {
return a - b;
}Example tests
Typical readings
show(2048, 2000);
show(4095, 4000);Expected output:
avg 2024, 1650 mV, delta 48
avg 4047, 3300 mV, delta 95Learn it first
- Static analysis and MISRA in practice · Warnings worth enabling, the essential type model, common MISRA findings, deviations and legacy code.
More Static analysis and MISRA in practice problems
- Fix: the energy counter loses energy · An energy meter multiplies in 32 bits and only then adds to a 64-bit total.
- Fix: the modem is not reset when it should be · A counter inside the right side of && only counts some of the time.
- Fix: turning the LED off reboots the device · A missing break makes one command fall through into the next.
- Fix: the search that never stops · A countdown loop with an unsigned index has a condition that is always true.
- Fix: faults above 31 cannot be set or cleared · A 64-bit fault mask is updated with 32-bit shifts, and clearing one fault clears thirty-two.
- Fix: settings that say they saved, but did not · A settings save ignores the return values of the flash erase and write.
- Fix: a short frame is read past its end · A length check compares a negative int with sizeof, which converts it to a huge unsigned value.
- Make a driver function MISRA compliant · Working code that the project's MISRA checker rejects: fix every finding without changing what it does.
- No recursion, no heap · Rewrite a recursive function and a heap-using function to fit a safety-critical project's rules.