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
- fix #100, negative representation — committed to RobTillaart/DHTNew by RobTillaart 2 years ago
- fix #100, negative representation — committed to RobTillaart/DHTNew by RobTillaart 2 years ago
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
Nice and clean I will give it a go tomorrow.