ESPHome 2026.5.0b1
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
10static const char *const TAG = "dht12";
11
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 if (this->temperature_sensor_ != nullptr)
30 this->temperature_sensor_->publish_state(temperature);
31 if (this->humidity_sensor_ != nullptr)
32 this->humidity_sensor_->publish_state(humidity);
34}
36 uint8_t data[5];
37 if (!this->read_data_(data)) {
38 this->mark_failed();
39 return;
40 }
41}
43 ESP_LOGD(TAG, "DHT12:");
44 LOG_I2C_DEVICE(this);
45 if (this->is_failed()) {
46 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
47 }
48 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
49 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
50}
51
52bool DHT12Component::read_data_(uint8_t *data) {
53 if (!this->read_bytes(0, data, 5)) {
54 ESP_LOGW(TAG, "Updating DHT12 failed!");
55 return false;
56 }
57
58 uint8_t checksum = data[0] + data[1] + data[2] + data[3];
59 if (data[4] != checksum) {
60 ESP_LOGW(TAG, "DHT12 Checksum invalid!");
61 return false;
62 }
63
64 return true;
65}
66
67} // namespace esphome::dht12
uint8_t checksum
Definition bl0906.h:3
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:284
void status_clear_warning()
Definition component.h:306
void dump_config() override
Definition dht12.cpp:42
sensor::Sensor * humidity_sensor_
Definition dht12.h:22
sensor::Sensor * temperature_sensor_
Definition dht12.h:21
bool read_data_(uint8_t *data)
Definition dht12.cpp:52
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:217
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
uint16_t temperature
Definition sun_gtil2.cpp:12