adafruit/DHT-sensor-library

DHT12 - Evaluating negative temperatures

Mk1G opened this issue · 1 comments

Mk1G commented
  • Arduino board: Not relevant (based on visual inspection of code)

  • Arduino IDE version (found in Arduino -> About Arduino menu): Also not relevant (based on visual inspection of code

  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too):

In file: DHT.cpp,
In function: float DHT::readTemperature(bool S, bool force)
While handling the DHT12 (extracting the float value from the 5-byte data received from the device
Code lines 100-105 are:
case DHT12:
f = data[2];
f += (data[3] & 0x0f) * 0.1;
if (data[2] & 0x80) {
f *= -1;
}

Bit 7 of data[2] is included in the float value, AND is used as a sign bit.
Surely this can't be right.
E.g. if data[2] = 0x80 and data[3]=0x00
then this will return a temperature of -128.0 degreesC

I've the same problem with the DHT22. In my case, the temperature data from the DHT22 is 2's complement. The current code thinks the data is signed binary and returns incorrect values for negative temperatures (e.g.-3257.9 for -18.9). The following code fixes the problem. It combines the temperature data in data[2] and data[3] into a signed 16 bit integer (int16_t) which is then converted to a float when multiplied by 0.1. I don't know if this applies to DHT11 and 12 also.

case DHT22:
case DHT21:
f = (int16_t)(data[2] << 8 | data[3])*0.1;
if (S) {
f = convertCtoF(f);
}
break;

I'll let someone else update the code in GITHUB