ESPHome 2025.5.0
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 ESP_LOGCONFIG(TAG, "Setting up DHT12...");
38 uint8_t data[5];
39 if (!this->read_data_(data)) {
40 this->mark_failed();
41 return;
42 }
43}
45 ESP_LOGD(TAG, "DHT12:");
46 LOG_I2C_DEVICE(this);
47 if (this->is_failed()) {
48 ESP_LOGE(TAG, "Communication with DHT12 failed!");
49 }
50 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
51 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
52}
54bool DHT12Component::read_data_(uint8_t *data) {
55 if (!this->read_bytes(0, data, 5)) {
56 ESP_LOGW(TAG, "Updating DHT12 failed!");
57 return false;
58 }
59
60 uint8_t checksum = data[0] + data[1] + data[2] + data[3];
61 if (data[4] != checksum) {
62 ESP_LOGW(TAG, "DHT12 Checksum invalid!");
63 return false;
64 }
65
66 return true;
67}
68
69} // namespace dht12
70} // 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="unspecified")
void status_clear_warning()
void dump_config() override
Definition dht12.cpp:44
float get_setup_priority() const override
Definition dht12.cpp:53
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:54
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:39
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:19
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint16_t temperature
Definition sun_gtil2.cpp:12