dht22 calculates temperature incorrectly at negative values

Open Beginner friendly
#1,074 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
62/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
embedded-iot

Research direction

Start in dht.py at the DHT22 temperature calculation and reproduce the supplied buffer example. Compare the current result with the proposed calculation, then verify that the example reports -2.2°C and that humidity remains 69.0%.

Written by the indexing model from the issue text.

Description

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()

Dominant language
Python
Stars
2.9k
Forks
1.1k
Avg merge
7d 6h
Merged PRs (30d)
3

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from micropython/micropython-lib

All issues in micropython/micropython-lib

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.