Avoid Adafruit PulseIn hangs when claiming the DHT GPIO pin.
libgpiod_pulsein fails with "Unable to set line N to input" on Raspberry Pi OS, so read via bitbang and release the pin after a single-shot run. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -18,10 +18,12 @@ def _get_device(dev_type, pin):
|
|||||||
key = (dev_type, pin)
|
key = (dev_type, pin)
|
||||||
if key not in _devices:
|
if key not in _devices:
|
||||||
gpio = Pin(pin)
|
gpio = Pin(pin)
|
||||||
|
# PulseIn/libgpiod_pulsein is unreliable on Raspberry Pi OS: it prints
|
||||||
|
# "Unable to set line N to input" and then hangs. Bitbang reads work.
|
||||||
if dev_type == DHT11:
|
if dev_type == DHT11:
|
||||||
_devices[key] = adafruit_dht.DHT11(gpio)
|
_devices[key] = adafruit_dht.DHT11(gpio, use_pulseio=False)
|
||||||
else:
|
else:
|
||||||
_devices[key] = adafruit_dht.DHT22(gpio)
|
_devices[key] = adafruit_dht.DHT22(gpio, use_pulseio=False)
|
||||||
return _devices[key]
|
return _devices[key]
|
||||||
|
|
||||||
|
|
||||||
@@ -42,3 +44,13 @@ def read(dev_type, pin):
|
|||||||
return None, None
|
return None, None
|
||||||
|
|
||||||
return float(temperature), float(humidity)
|
return float(temperature), float(humidity)
|
||||||
|
|
||||||
|
|
||||||
|
def close():
|
||||||
|
"""Release cached DHT devices and their GPIO lines."""
|
||||||
|
for device in _devices.values():
|
||||||
|
try:
|
||||||
|
device.exit()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
_devices.clear()
|
||||||
|
|||||||
@@ -82,7 +82,10 @@ def main():
|
|||||||
'Single run temperature and humidity reading '
|
'Single run temperature and humidity reading '
|
||||||
'[version: 2.0, Python 3]'
|
'[version: 2.0, Python 3]'
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
return sensor_read(cfg, dev_type, dhtpin)
|
return sensor_read(cfg, dev_type, dhtpin)
|
||||||
|
finally:
|
||||||
|
dhtreader.close()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
Reference in New Issue
Block a user