Simvik

A sensor frame, its CRC and its transfer function

Check the CRC the datasheet specifies, then convert raw readings to temperature and humidity. A medium embedded C problem (Reading datasheets and…

medium · Reading datasheets and schematics · datasheets · crc · i2c · sensors · fixed-point

A humidity sensor's datasheet (SHT3x style) describes one measurement read over I2C as 6 bytes:

Byte012345
ContentT MSBT LSBCRC of bytes 0–1RH MSBRH LSBCRC of bytes 3–4

Its checksum section gives:

PropertyValue
Width8 bit
Polynomial0x31 (x⁸ + x⁵ + x⁴ + 1)
Initialisation0xFF
Reflect input / outputno / no
Final XOR0x00
ExampleCRC(0xBE, 0xEF) = 0x92

And the conversion, with S the raw 16-bit value: T [°C] = −45 + 175 × S / 65535, RH [%] = 100 × S / 65535.

Write sht_crc8(p, n), and sht_parse(f, t_centi, rh_centi). If either CRC is wrong, return false. Otherwise, store hundredths of a degree and of a percent and return true. Compute them with integer arithmetic exactly as -4500 + 17500 * S / 65535 and 10000 * S / 65535.

Starter code

uint8_t sht_crc8(const uint8_t *p, int n) {
  uint8_t c = 0x00;
  for (int i = 0; i < n; i++) {
    c ^= p[i];
    for (int k = 0; k < 8; k++) c = (uint8_t)((c & 0x80) ? (c << 1) ^ 0x31 : c << 1);
  }
  return c;
}

bool sht_parse(const uint8_t f[6], int32_t *t_centi, int32_t *rh_centi) {
  uint16_t st = (uint16_t)(f[1] << 8 | f[0]);
  uint16_t srh = (uint16_t)(f[4] << 8 | f[3]);
  *t_centi = -4500 + 17500 * st / 65536;
  *rh_centi = 10000 * srh / 65536;
  return true;
}

Example tests

The datasheet's CRC example

uint8_t ex[2] = { 0xBE, 0xEF };
printf("0x%02X\n", sht_crc8(ex, 2));

Expected output:

0x92

A reading of 25 °C and 50 %

uint8_t f[6];
frame(f, 0x6666, 0x8000);
parse(f);

Expected output:

temp 2500, rh 5000

Learn it first

More Reading datasheets and schematics problems