ESPHome 2025.9.0-dev
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 {
9namespace dht12 {
10
11static const char *const TAG = "dht12";
12
14 uint8_t data[5];
15 if (!this->read_data_(data)) {
16 this->status_set_warning();
17 return;
18 }
19 const uint16_t raw_temperature = uint16_t(data[2]) * 10 + (data[3] & 0x7F);
20 float temperature = raw_temperature / 10.0f;
21 if ((data[3] & 0x80) != 0) {
22 // negative
23 temperature *= -1;
24 }
25
26 const uint16_t raw_humidity = uint16_t(data[0]) * 10 + data[1];
27 float humidity = raw_humidity / 10.0f;
28
29 ESP_LOGD(TAG, "Got temperature=%.2f°C humidity=%.2f%%", temperature, humidity);
30 if (this->temperature_sensor_ != nullptr)
31 this->temperature_sensor_->publish_state(temperature);
32 if (this->humidity_sensor_ != nullptr)
33 this->humidity_sensor_->publish_state(humidity);
35}
37 uint8_t data[5];
38 if (!this->read_data_(data)) {
39 this->mark_failed();
40 return;
41 }
42}
44 ESP_LOGD(TAG, "DHT12:");
45 LOG_I2C_DEVICE(this);
46 if (this->is_failed()) {
47 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
48 }
49 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
50 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
51}
53bool DHT12Component::read_data_(uint8_t *data) {
54 if (!this->read_bytes(0, data, 5)) {
55 ESP_LOGW(TAG, "Updating DHT12 failed!");
56 return false;
57 }
58
59 uint8_t checksum = data[0] + data[1] + data[2] + data[3];
60 if (data[4] != checksum) {
61 ESP_LOGW(TAG, "DHT12 Checksum invalid!");
62 return false;
63 }
64
65 return true;
66}
67
68} // namespace dht12
69} // namespace esphome
uint8_t checksum
Definition bl0906.h:3
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
void dump_config() override
Definition dht12.cpp:43
float get_setup_priority() const override
Definition dht12.cpp:52
sensor::Sensor * humidity_sensor_
Definition dht12.h:24
sensor::Sensor * temperature_sensor_
Definition dht12.h:23
bool read_data_(uint8_t *data)
Definition dht12.cpp:53
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:216
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:50
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint16_t temperature
Definition sun_gtil2.cpp:12