C-function calculates CRC of Sensirion SHT1x humidity sensor data

When reading the measured humidity or temperature value from the SHT1x Sensirion humidity sensor one may also read the optional check sum. This check sum can then be used to validate the read value. This function does this operation without using a precalculated CRC table.

The check sum calculation procedure is given in the Sensirion application note CRC Calculation Humidity Sensors SHT1x/SHT7x.

One alternative is to use a precalculated table of CRC values, as described in the application note and implemented in python, see this post.

The alternative method is by “bit-calculation” of the CRC algorithm, as implemented here:

static int32_t humCheckCrc(int32_t v)
	uint32_t x, i;
	uint8_t c;
	x= (uint32_t) v;
	c= 0; // or reversed bits of status byte & 0xf0
	for (i=0; i<32; i++) {
		if ((x >> 31) ^ (c >> 7) != 0) {
			c= ((c << 1)^0x30) | 1;
		else {
			c= c << 1;
		if (i == 23) c= rev8(c);
		x= (x << 1);
	if (c==0) v= v &0xffffff00;
	return v;


The function argument is the byte string read from the device (command, msb, lsb and crc, the crc byte at bits 0 to 7) and returns the same value, but bits 0-7 are set to 0 if the crc is 0 and the value in bit positions 8-23 (msb, lsb) thus valid. The long shifts used are not suitable for microcontrollers without single instuction barrel shifters. If your controller can only shift 1 bit/instruction you better rewrite the compare at line 8 to be more efficient.

Some micro controllers, like the ARM Cortex 3 series, have single instruction bit reversal instruction, those without (and for those who do not want to include assembly into the C-source, can bit reverse using this function:

static const uint8_t revbits[]= 
   {0, 8, 4, 0xc,2, 0xa, 6, 0xe, 1, 9, 5, 0xd, 3, 0xb, 7, 0xf}; 
static uint8_t rev8(uint8_t v)
	uint8_t r;
	int i;
	r= 0;
	for (i= 0; i<2; i++) {
		r <<= 4;
		r= r | revbits[v & 0xf];
		v= v >> 4;
	return r;

0 Responses to “C-function calculates CRC of Sensirion SHT1x humidity sensor data”

  • No Comments

Leave a Reply