Skip to content

[DHT22] modified interpretation of temperature values in byte 2 and 3, such that negative temperature values are handled correctly#223

Open
bkormann80 wants to merge 1 commit intoadafruit:masterfrom
bkormann80:dht22_negtemp_fix
Open

[DHT22] modified interpretation of temperature values in byte 2 and 3, such that negative temperature values are handled correctly#223
bkormann80 wants to merge 1 commit intoadafruit:masterfrom
bkormann80:dht22_negtemp_fix

Conversation

@bkormann80
Copy link

This pull request solves the issue described in #221.

Negative temperature values from a DHT22 sensor can be interpreted as a 16 bit signed integer (short). There is no additional differentiation needed.

float DHT::readTemperature(bool S, bool force) {
  float f = NAN;
  short s = 0;
...
    case DHT22:
      s = ((short) data[2]) << 8 | data[3];
      f = s * 0.1;
      if (S) {
        f = convertCtoF(f);
      }
      break;
... 

The patch was successfully tested using five different DHT22 sensors on an Arduino UNO and an ESP8266 at positive and negative temperatures.

…hat negative temperature values are handled correctly
@dhalbert dhalbert requested a review from caternuson December 29, 2024 17:43
@bkormann80
Copy link
Author

Is any information missing?

@caternuson
Copy link

Negative temperature values from a DHT22 sensor can be interpreted as a 16 bit signed integer (short).

Are you sure about this? This doesn't look like twos complement, looks like sign/magnitude:

image

ex:

#include <stdio.h>
#include <stdint.h>

uint8_t  b2 = 0b10000000;
uint8_t  b3 = 0b01100101;

short t;

int main() {
  t  = ((short) b2) << 8 | b3;
  printf("t = %d\n", t);
  return 0;
}

yields:

t = -32667

Can you dump the actual bytes you are getting from whatever sensor you are using when there is a negative temperature?

@bkormann80
Copy link
Author

I am sure. In issue #221 I described this mismatch between documentation and all of my sensors. Documentation doesn't describe two complement, but sensor returns data this way.
If you want to keep both variants, simply add this flavor as another sensor type like DHT22b.

@dklein-pik
Copy link

Why isn't this pull request merged? I was having the same issues with my DHT22 sensor, tried a couple of libraries, including this one. None of them work. Then I tested the suggested changes locally and they solved the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants