ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
dht12.cpp
Go to the documentation of this file.
1// Implementation based on:
2// - ESPEasy: https://github.com/letscontrolit/ESPEasy/blob/mega/src/_P034_DHT12.ino
3// - DHT12_sensor_library: https://github.com/xreef/DHT12_sensor_library/blob/master/DHT12.cpp
4
5#include "dht12.h"
6#include "esphome/core/log.h"
7
8namespace esphome::dht12 {
9
10ESPHOME_LOG_TAG(TAG, "dht12");
11
12void DHT12Component::update() {
13 uint8_t data[5];
14 if (!this->read_data_(data)) {
15 this->status_set_warning();
16 return;
17 }
18 const uint16_t raw_temperature = uint16_t(data[2]) * 10 + (data[3] & 0x7F);
19 float temperature = raw_temperature / 10.0f;
20 if ((data[3] & 0x80) != 0) {
21 // negative
22 temperature *= -1;
23 }
24
25 const uint16_t raw_humidity = uint16_t(data[0]) * 10 + data[1];
26 float humidity = raw_humidity / 10.0f;
27
28 ESP_LOGD(TAG, "Got temperature=%.2f°C humidity=%.2f%%", temperature, humidity);
29 PUBLISH_STATE(this->temperature_sensor_, temperature);
30 PUBLISH_STATE(this->humidity_sensor_, humidity);
32}
34 uint8_t data[5];
35 if (!this->read_data_(data)) {
36 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
37 return;
38 }
39}
40void DHT12Component::dump_config() {
41 ESP_LOGD(TAG, "DHT12:");
42 LOG_I2C_DEVICE(this);
43 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
44 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
45}
46
47bool DHT12Component::read_data_(uint8_t *data) {
48 if (!this->read_bytes(0, data, 5)) {
49 ESP_LOGW(TAG, "Updating DHT12 failed!");
50 return false;
51 }
52
53 uint8_t checksum = data[0] + data[1] + data[2] + data[3];
54 if (data[4] != checksum) {
55 ESP_LOGW(TAG, "DHT12 Checksum invalid!");
56 return false;
57 }
58
59 return true;
60}
61
62} // namespace esphome::dht12
uint8_t checksum
Definition bl0906.h:3
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void status_clear_warning()
Definition component.h:309
bool read_data_(uint8_t *data)
Definition dht12.cpp:47
bool read_bytes(uint8_t a_register, uint8_t *data, uint8_t len)
Compat APIs All methods below have been added for compatibility reasons.
Definition i2c.h:249
ESPHOME_LOG_TAG(TAG, "dht12")
std::span< const uint8_t > data
uint16_t temperature
Definition sun_gtil2.cpp:12