Simvik

HVAC controller: trust the humidity reading

Combine the bytes an I²C humidity sensor returns, check their CRC, and scale them. A medium embedded C problem (I2C), run and graded in the browser.

medium · I2C · byte-order · crc · sensor · product

Product: Building HVAC controller (Industrial)

Requirement. The building's air handler adds or removes moisture from the humidity reading. A reading corrupted on a long I²C cable must be thrown away, not acted on.

The sensor returns 3 bytes: the raw value's high byte, its low byte, and a CRC-8 of those two (sht_crc(b, 2), provided). Relative humidity is 100 × raw / 65535 percent.

Return the humidity in tenths of a percent, rounded to the nearest, or -1 if the CRC does not match.

Starter code

int16_t rh_tenths(const uint8_t b[3]) {
  uint16_t raw = b[1] << 8 | b[0];
  return raw * 1000 / 65535;
}

Example tests

Half and full scale

uint8_t a[3] = { 0x80, 0x00, 0 };
a[2] = sht_crc(a, 2);
uint8_t b[3] = { 0xFF, 0xFF, 0 };
b[2] = sht_crc(b, 2);
printf("%d %d\n", rh_tenths(a), rh_tenths(b));

Expected output:

500 1000

A corrupted reading

uint8_t a[3] = { 0x80, 0x00, 0 };
a[2] = sht_crc(a, 2) ^ 0x01;
printf("%d\n", rh_tenths(a));

Expected output:

-1

Learn it first

  • I2C · Addressing, repeated start, clock stretching and bus recovery.

More I2C problems