ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
dht.cpp
Go to the documentation of this file.
1#include "dht.h"
3#include "esphome/core/log.h"
4
5namespace esphome::dht {
6
7ESPHOME_LOG_TAG(TAG, "dht");
8
9void DHT::setup() {
10 this->t_pin_->digital_write(true);
11 this->t_pin_->setup();
12#ifdef USE_ESP32
14#endif
15 this->t_pin_->digital_write(true);
16}
17
18void DHT::dump_config() {
19 ESP_LOGCONFIG(TAG,
20 "DHT:\n"
21 " %sModel: %s\n"
22 " Internal pull-up: %s",
23 this->is_auto_detect_ ? LOG_STR_LITERAL("Auto-detected ") : "",
24 this->model_ == DHT_MODEL_DHT11 ? LOG_STR_LITERAL("DHT11") : LOG_STR_LITERAL("DHT22 or equivalent"),
25 ONOFF(this->t_pin_->get_flags() & gpio::FLAG_PULLUP));
26 LOG_PIN(" Pin: ", this->t_pin_);
27 LOG_UPDATE_INTERVAL(this);
28 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
29 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
30}
31
32void DHT::update() {
33 float temperature, humidity;
34 bool success;
35 if (this->model_ == DHT_MODEL_AUTO_DETECT) {
36 this->model_ = DHT_MODEL_DHT22;
37 success = this->read_sensor_(&temperature, &humidity, false);
38 if (!success) {
39 this->model_ = DHT_MODEL_DHT11;
40 return;
41 }
42 } else {
43 success = this->read_sensor_(&temperature, &humidity, true);
44 }
45
46 if (success) {
47 PUBLISH_STATE(this->temperature_sensor_, temperature);
48 PUBLISH_STATE(this->humidity_sensor_, humidity);
50 } else {
51 ESP_LOGW(TAG, "Invalid readings");
52 PUBLISH_STATE(this->temperature_sensor_, NAN);
53 PUBLISH_STATE(this->humidity_sensor_, NAN);
54 this->status_set_warning();
55 }
56}
57
58void DHT::set_dht_model(DHTModel model) {
59 this->model_ = model;
61}
62
63bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool report_errors) {
64 *humidity = NAN;
65 *temperature = NAN;
66
67 int error_code = 0;
68 uint8_t data[5] = {};
69
70#ifndef USE_ESP32
72#endif
73 this->pin_.digital_write(false);
74
75 if (this->model_ == DHT_MODEL_DHT11) {
76 delayMicroseconds(18000);
77 } else if (this->model_ == DHT_MODEL_SI7021) {
79 } else if (this->model_ == DHT_MODEL_DHT22_TYPE2) {
81 } else {
83 }
84
85#ifdef USE_ESP32
86 this->pin_.digital_write(true);
87#else
88 this->pin_.pin_mode(this->t_pin_->get_flags());
89#endif
90
91 {
93 // Host pull up 20-40us then DHT response 80us
94 // Start waiting for initial rising edge at the center when we
95 // expect the DHT response (30us+40us)
97
98 uint8_t bit = 7;
99 uint8_t byte = 0;
100
101 // On 32-bit Xtensa/RISC-V cores, int8_t would require masking/sign-extension for comparisons
102 // vs. native int. Using int i is native word size — small win in the timing-critical section.
103 for (int i = -1; i < 40; i++) {
104 uint32_t start_time = micros();
105
106 // Wait for rising edge
107 while (!this->pin_.digital_read()) {
108 if (micros() - start_time > 90) {
109 if (i < 0) {
110 error_code = 1; // line didn't clear
111 } else {
112 error_code = 2; // rising edge for bit i timeout
113 }
114 break;
115 }
116 }
117 if (error_code != 0)
118 break;
119
120 start_time = micros();
121 uint32_t end_time = start_time;
122
123 // Wait for falling edge
124 while (this->pin_.digital_read()) {
125 end_time = micros();
126 if (end_time - start_time > 90) {
127 if (i < 0) {
128 error_code = 3; // requesting data failed
129 } else {
130 error_code = 4; // falling edge for bit i timeout
131 }
132 break;
133 }
134 }
135 if (error_code != 0)
136 break;
137
138 if (i < 0)
139 continue;
140
141 if (end_time - start_time >= 40) {
142 data[byte] |= 1 << bit;
143 }
144 if (bit == 0) {
145 bit = 7;
146 byte++;
147 } else {
148 bit--;
149 }
150 }
151 }
152 if (error_code != 0) {
153 if (report_errors) {
154 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
155 }
156 return false;
157 }
158
159 ESP_LOGVV(TAG,
160 "Data: Hum=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN
161 ", Temp=0b" BYTE_TO_BINARY_PATTERN BYTE_TO_BINARY_PATTERN ", Checksum=0b" BYTE_TO_BINARY_PATTERN,
162 BYTE_TO_BINARY(data[0]), BYTE_TO_BINARY(data[1]), BYTE_TO_BINARY(data[2]), BYTE_TO_BINARY(data[3]),
163 BYTE_TO_BINARY(data[4]));
164
165 uint8_t checksum_a = data[0] + data[1] + data[2] + data[3];
166 // On the DHT11, two algorithms for the checksum seem to be used, either the one from the DHT22,
167 // or just using bytes 0 and 2
168 uint8_t checksum_b = this->model_ == DHT_MODEL_DHT11 ? (data[0] + data[2]) : checksum_a;
169
170 if (checksum_a != data[4] && checksum_b != data[4]) {
171 if (report_errors) {
172 ESP_LOGW(TAG, "Invalid checksum");
173 }
174 return false;
175 }
176
177 if (this->model_ == DHT_MODEL_DHT11) {
178 if (checksum_a == data[4]) {
179 // Data format: 8bit integral RH data + 8bit decimal RH data + 8bit integral T data + 8bit decimal T data + 8bit
180 // check sum - some models always have 0 in the decimal part
181 const uint16_t raw_temperature = static_cast<uint16_t>(data[2]) * 10 + (data[3] & 0x7F);
182 *temperature = static_cast<float>(raw_temperature) / 10.0f;
183 if ((data[3] & 0x80) != 0) {
184 // negative
185 *temperature *= -1;
186 }
187
188 const uint16_t raw_humidity = static_cast<uint16_t>(data[0]) * 10 + data[1];
189 *humidity = static_cast<float>(raw_humidity) / 10.0f;
190 } else {
191 // For compatibility with DHT11 models which might only use 2 bytes checksums, only use the data from these two
192 // bytes
193 *temperature = data[2];
194 *humidity = data[0];
195 }
196 } else {
197 uint16_t raw_humidity = encode_uint16(data[0], data[1]);
198 const int16_t raw_temperature = decode_dht22_temperature(encode_uint16(data[2], data[3]));
199
200 if (raw_temperature == 1 && raw_humidity == 10) {
201 if (report_errors) {
202 ESP_LOGW(TAG, "Invalid data");
203 }
204 return false;
205 }
206
207 *humidity = static_cast<float>(raw_humidity) * 0.1f;
208 if (*humidity > 100.0f)
209 *humidity = NAN;
210 *temperature = raw_temperature * 0.1f;
211 }
212
213 if (*temperature == 0.0f && (*humidity == 1.0f || *humidity == 2.0f)) {
214 if (report_errors) {
215 ESP_LOGW(TAG, "Invalid data");
216 }
217 return false;
218 }
219 return true;
220}
221
222} // namespace esphome::dht
void status_clear_warning()
Definition component.h:309
void digital_write(bool value)
Definition gpio.cpp:234
void pin_mode(gpio::Flags flags)
Definition gpio.cpp:246
Helper class to disable interrupts.
Definition helpers.h:2251
bool is_auto_detect_
Definition dht.h:72
InternalGPIOPin * t_pin_
Definition dht.h:69
DHTModel model_
Definition dht.h:71
bool read_sensor_(float *temperature, float *humidity, bool report_errors)
Definition dht.cpp:63
ISRInternalGPIOPin pin_
Definition dht.h:70
gpio::Flags get_flags() const override
Definition gpio.h:34
void pin_mode(gpio::Flags flags) override
Definition gpio.cpp:195
void digital_write(bool value) override
Definition gpio.cpp:215
ESPHOME_LOG_TAG(TAG, "dht")
@ DHT_MODEL_AUTO_DETECT
Definition dht.h:10
@ DHT_MODEL_DHT22
Definition dht.h:12
@ DHT_MODEL_SI7021
Definition dht.h:16
@ DHT_MODEL_DHT22_TYPE2
Definition dht.h:17
@ DHT_MODEL_DHT11
Definition dht.h:11
int16_t decode_dht22_temperature(uint16_t raw)
Convert a DHT22-family temperature reading to tenths of a degree.
Definition dht.h:22
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
uint32_t IRAM_ATTR HOT micros()
Definition hal.cpp:43
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:1043
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12
SemaphoreHandle_t lock