Simvik

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 of n samples (n > 0), rounded down.
  • scale_mv(raw): a 12-bit ADC reading as millivolts, raw * 3300 / 4095, rounded down.
  • delta(a, b): a - b as 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 95

Learn it first

More Static analysis and MISRA in practice problems