DHTNew: Negative temp is calculated wrongly

It’s getting cold out there…

When receiving _bits[2…3] = 0xffff as 0.1 degree, it gets converted to -3200 something, because 0x7fff is taken as 32000, and MSB of 0x8000 is taken as signbit and now makes -32000. Finally _temperature = -32000 * 0.1 = -3200

Code has to take 16 bits “as is”, and move it directly into a int16_t. Then every is “as send” from DHT. And correctly interpreted. And no problem with -0.0, as minus-0 does not exists i the integer world. Code below also do the same with _humidity, but was correct before as long as DHT does not send negative values.

My fixed code in dhtnew.cpp:

  else               //  DHT22, DHT33, DHT44, compatible + Si7021
  {
    int16_t t1 = (_bits[0] << 8) + _bits[1]; // 16 bits, as raw int
    _humidity = t1 * 0.1;
    int16_t t2 = (_bits[2] << 8) + _bits[3]; // 16 bits, as raw int
    _temperature = t2 * 0.1;
  }

DHT11 code above also looks strange to my eyes. But I have not looked up the specs, and I do not use that part anyway.

/Christen

(updated code for syntax highlighting)

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 21 (13 by maintainers)

Commits related to this issue

Most upvoted comments

I guess that AM2302 might always be as documented above. And DHT22 might always be base-2 coded. My DHT22 has no claims of being a AM2302 as your picture does.

Denmark says ok for base-2 part of code as in dev branch

Been a pleasure brainstorming with you Christen

(dht22: 03 d3 00 64 3a temp=10.0, humi=97.9)
(dht22: 01 e6 00 06 ed temp=0.6, humi=48.6)
(dht22: 01 cc 00 00 cd temp=0.0, humi=46.0)
(dht22: 01 b9 ff fa b3 temp=-0.6, humi=44.1)
(dht22: 01 93 ff 4d e0 temp=-17.9, humi=40.3)
(dht22: 01 dd ff 3f 1c temp=-19.3, humi=47.7)

Nice and clean I will give it a go tomorrow.