adafruit / Adafruit_CircuitPython_DHT

CircuitPython support for DHT11 and DHT22 type temperature/humidity devices
MIT License
179 stars 62 forks source link

DHT reading may be "None" if read too soon after boot #16

Closed jerryneedell closed 5 years ago

jerryneedell commented 5 years ago

We ra into a strange behavior that some DHT code was failing only after a RESET if loaded as code.py (or main.py) it ran OK via REPL. After much head scraping and false starts it looks like a simple reason.

The code was doing a reading from the dot and checking the value against a limit.

humidity = dht.humidity
if humidity > 50. :
    do something

this failed if dht.humidity returns a None. Normally it will only return a None if it also throws a Runtime error But not if time.monotonic() is < .5 In that case, it just silently skips the reading see https://github.com/adafruit/Adafruit_CircuitPython_DHT/blob/master/adafruit_dht.py#L141

This check is to make sure readings are not too close together. After one successful read, it will just return the last value read.

One fix would just have the diver always delay the first reading until time.monotonic() > .5 This is only an issue for the first .5 sec after boot

jerryneedell commented 5 years ago

Possibly we could just initialize self._last_called =-1 instead of 0 Then it would always do a reading on first call. Any problem with this?

jerryneedell commented 5 years ago

Even simpler fix -- just test if self._last_called == 0 in line 141 If it is the do the reading since this guarantees that no readings have been done. This eliminates the only case where a None will be returned without a Runtime error. Test this now -- seem to be working -- I'll put in a PR for discussion.