Skip to content

dht22 calculates temperature incorrectly at negative values #1074

Description

@m32

I recently installed DHT22, and to my surprise, after a few days of frost, it showed a temperature of -3274.5.
The calculations performed by dht.py are consistent with the documentation, but they are incorrect.

Example and proposal for new calculation:

class DHTBase:
    def xbuf(self, buf):
        self.buf = buf

class DHT22(DHTBase):
    def humidity(self):
        return (self.buf[0] << 8 | self.buf[1]) * 0.1

    def temperature(self):
        t = (self.buf[2] & 0x7f) << 8 | self.buf[3]
        if self.buf[2] & 0x80:
            t = - t ^ 0x7fff
        return t*0.1

def main():
    # hum = 69, temp=-3274.5 = -2.2
    cls = DHT22()
    cls.xbuf([2, 183, 255, 233, 162])
    temp = cls.temperature()
    hum = cls.humidity()
    print(f'temp={temp:.1f} hum={hum:.1f}')

main()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions