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 1000A corrupted reading
uint8_t a[3] = { 0x80, 0x00, 0 };
a[2] = sht_crc(a, 2) ^ 0x01;
printf("%d\n", rh_tenths(a));Expected output:
-1Learn it first
- I2C · Addressing, repeated start, clock stretching and bus recovery.
More I2C problems
- Scan the bus · Find every device on the bus without probing the reserved addresses.
- Read a 16-bit register · Write the register pointer, read two bytes back with a repeated start, and handle a NACK.
- Recover a stuck bus · Clock a stuck device out with up to nine pulses, then send a STOP.
- Size the pull-up resistors · Work out the smallest and largest pull-up that meet the I2C specification.
- Driver: write an EEPROM over I2C, with ACK polling · Send an I2C write with the hardware's byte-by-byte handshake, then poll until the EEPROM finishes writing.
- Driver: read registers with a repeated start · Write a register address, then read bytes back without releasing the bus in between.
- Fix: every second transfer is cut short · A write routine leaves STOPF set, so the next transfer thinks it has already finished.