Problems with reading from a SHT21 Sensor

Hello!

I have a problem with reading from a Sensirion SHT21 temperature and humidity sensor. The code works fine for the temperature part but the humidity is somehow behaving strange. The calculated value becomes negative once it reaches 60. After dropping below 60, everything is back to normal again.

I’ve looked at some other code examples but since all of them (including me) are just using the formula given in the datasheet, I can’t really comprehend why this is happening. Maybe someone is able to point me to the right direction.

#include <Wire.h>


void setup()
{
  Serial.begin(9600);
  Wire.begin();
  delay(1000);
}


void loop()
{
  Serial.println(fetchTemperature());
  Serial.println(fetchHumidity());
  Serial.println();
}


float fetchTemperature()
{
  int firstTempByte = 0, secondTempByte = 0, thirdTempByte = 0;
  Wire.beginTransmission(0x40);
  Wire.write(0xF3);
  Wire.endTransmission();
  delay(200);
  Wire.requestFrom(0x40, 3);
  while (Wire.available() > 2)
  {
    firstTempByte = (int)Wire.read();
    secondTempByte = (int)Wire.read();
    thirdTempByte = (int)Wire.read();
  }
  float calculatedTemperature = -46.85 + (175.72 * (((firstTempByte << 8) + secondTempByte) / (pow(2, 16))));
  return calculatedTemperature;
}


float fetchHumidity()
{
  int firstHumiByte = 0, secondHumiByte = 0, thirdHumiByte = 0;
  Wire.beginTransmission(0x40);
  Wire.write(0xF5);
  Wire.endTransmission();
  delay(200);
  Wire.requestFrom(0x40, 3);
  while (Wire.available() > 2)
  {
    firstHumiByte = (int)Wire.read();
    secondHumiByte = (int)Wire.read();
    thirdHumiByte = (int)Wire.read();
  }
  float calculatedHumidity = -6 + (125 * (((firstHumiByte << 8) + secondHumiByte) / (pow(2, 16))));
  return calculatedHumidity;
}

If you reverse the calculation, and calculate the binairy value from the sensor at 60%, then it is (60 / 125 * 65536.0) + 6.0 = 31463. That means you have a sign problem with the 16-bit integers.

You have to find a better library or example code. Every library that I can find uses unsigned integers.

I wanted to place a link here to good SHT21 code, but I have seen about 6 libraries on Github and they all contain bugs :( Finally I found code that was good: https://github.com/AdysTech/Esp32-weather/tree/master/Esp32WeatherStation_htu21d and the Sparkfun code: https://github.com/sparkfun/HTU21D_Breakout and this simple sketch: https://github.com/coredump-ch/sht21-arduino

Of course it has to be an unsigned integer. Should have known that by having a closer look at the raw values. Thanks a lot! :)