From 7df72ddb969bca32a72795e4137e01abe1b36f49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20Smidsr=C3=B8d?= Date: Tue, 19 May 2020 01:24:13 +0200 Subject: [PATCH] dht: Fix sensor reading from DHT22 (#926) * dht: Fix sensor reading from DHT22 (#239) Looking at the datasheet for DHT22, it claims to need a delay of 18ms, not 800us. Change to use the same delay as DHT11. Tested working with NodeMCUv3 and DHT22 sensor with board with built-in resistor. * dht: Add model DHT22_TYPE2 with 2ms delay instead of 0.8ms The model DHT22_TYPE2 is exactly the same as DHT22, but uses a different delay. * dht: Fix bogus negative temperature reading on DHT22_TYPE2 The workaround for negative numbers associated with DHT22s can be skipped on these sensors. --- esphome/components/dht/dht.cpp | 4 +++- esphome/components/dht/dht.h | 4 +++- esphome/components/dht/sensor.py | 1 + 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/esphome/components/dht/dht.cpp b/esphome/components/dht/dht.cpp index c311aa43ec..988a5300dd 100644 --- a/esphome/components/dht/dht.cpp +++ b/esphome/components/dht/dht.cpp @@ -92,6 +92,8 @@ bool HOT ICACHE_RAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, delayMicroseconds(500); this->pin_->digital_write(true); delayMicroseconds(40); + } else if (this->model_ == DHT_MODEL_DHT22_TYPE2) { + delayMicroseconds(2000); } else { delayMicroseconds(800); } @@ -208,7 +210,7 @@ bool HOT ICACHE_RAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, uint16_t raw_humidity = (uint16_t(data[0] & 0xFF) << 8) | (data[1] & 0xFF); uint16_t raw_temperature = (uint16_t(data[2] & 0xFF) << 8) | (data[3] & 0xFF); - if ((raw_temperature & 0x8000) != 0) + if (this->model_ != DHT_MODEL_DHT22_TYPE2 && (raw_temperature & 0x8000) != 0) raw_temperature = ~(raw_temperature & 0x7FFF); if (raw_temperature == 1 && raw_humidity == 10) { diff --git a/esphome/components/dht/dht.h b/esphome/components/dht/dht.h index 4ed5d4e022..8826a3d2b7 100644 --- a/esphome/components/dht/dht.h +++ b/esphome/components/dht/dht.h @@ -12,7 +12,8 @@ enum DHTModel { DHT_MODEL_DHT22, DHT_MODEL_AM2302, DHT_MODEL_RHT03, - DHT_MODEL_SI7021 + DHT_MODEL_SI7021, + DHT_MODEL_DHT22_TYPE2 }; /// Component for reading temperature/humidity measurements from DHT11/DHT22 sensors. @@ -28,6 +29,7 @@ class DHT : public PollingComponent { * - DHT_MODEL_AM2302 * - DHT_MODEL_RHT03 * - DHT_MODEL_SI7021 + * - DHT_MODEL_DHT22_TYPE2 * * @param model The DHT model. */ diff --git a/esphome/components/dht/sensor.py b/esphome/components/dht/sensor.py index 8455f74fb4..8749d85b52 100644 --- a/esphome/components/dht/sensor.py +++ b/esphome/components/dht/sensor.py @@ -15,6 +15,7 @@ DHT_MODELS = { 'AM2302': DHTModel.DHT_MODEL_AM2302, 'RHT03': DHTModel.DHT_MODEL_RHT03, 'SI7021': DHTModel.DHT_MODEL_SI7021, + 'DHT22_TYPE2': DHTModel.DHT_MODEL_DHT22_TYPE2, } DHT = dht_ns.class_('DHT', cg.PollingComponent)