ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
htu31d.cpp
Go to the documentation of this file.
1/*
2 * This file contains source code derived from Adafruit_HTU31D which is under
3 * the BSD license:
4 * Written by Limor Fried/Ladyada for Adafruit Industries.
5 * BSD license, all text above must be included in any redistribution.
6 *
7 * Modifications made by Mark Spicer.
8 */
9
10#include "htu31d.h"
11#include "esphome/core/hal.h"
13#include "esphome/core/log.h"
14
15#include <cinttypes>
16
17namespace esphome {
18namespace htu31d {
19
21static const char *const TAG = "htu31d";
22
24static const uint8_t HTU31D_DEFAULT_I2CADDR = 0x40;
25
27static const uint8_t HTU31D_READTEMPHUM = 0x00;
28
30static const uint8_t HTU31D_CONVERSION = 0x40;
31
33static const uint8_t HTU31D_READSERIAL = 0x0A;
34
36static const uint8_t HTU31D_HEATERON = 0x04;
37
39static const uint8_t HTU31D_HEATEROFF = 0x02;
40
42static const uint8_t HTU31D_RESET = 0x1E;
43
45static const uint8_t HTU31D_DIAGNOSTICS = 0x08;
46
52uint8_t compute_crc(uint32_t value) {
53 uint32_t polynom = 0x98800000; // x^8 + x^5 + x^4 + 1
54 uint32_t msb = 0x80000000;
55 uint32_t mask = 0xFF800000;
56 uint32_t threshold = 0x00000080;
57 uint32_t result = value;
58
59 while (msb != threshold) {
60 // Check if msb of current value is 1 and apply XOR mask
61 if (result & msb)
62 result = ((result ^ polynom) & mask) | (result & ~mask);
63
64 // Shift by one
65 msb >>= 1;
66 mask >>= 1;
67 polynom >>= 1;
68 }
69
70 return result;
71}
72
78 if (!this->reset_()) {
79 this->mark_failed();
80 return;
81 }
82
83 if (this->read_serial_num_() == 0) {
84 this->mark_failed();
85 return;
86 }
87}
88
94 ESP_LOGD(TAG, "Checking temperature and humidty values");
95
96 // Trigger a conversion. From the spec sheet: The conversion command triggers
97 // a single temperature and humidity conversion.
98 if (this->write_register(HTU31D_CONVERSION, nullptr, 0) != i2c::ERROR_OK) {
99 this->status_set_warning();
100 ESP_LOGE(TAG, "Received errror writing conversion register");
101 return;
102 }
103
104 // Wait conversion time.
105 this->set_timeout(20, [this]() {
106 uint8_t thdata[6];
107 if (this->read_register(HTU31D_READTEMPHUM, thdata, 6) != i2c::ERROR_OK) {
108 this->status_set_warning();
109 ESP_LOGE(TAG, "Error reading temperature/humidty register");
110 return;
111 }
112
113 // Calculate temperature value.
114 uint16_t raw_temp = encode_uint16(thdata[0], thdata[1]);
115
116 uint8_t crc = compute_crc((uint32_t) raw_temp << 8);
117 if (crc != thdata[2]) {
118 this->status_set_warning();
119 ESP_LOGE(TAG, "Error validating temperature CRC");
120 return;
121 }
122
123 float temperature = raw_temp;
124 temperature /= 65535.0f;
125 temperature *= 165;
126 temperature -= 40;
127
128 if (this->temperature_ != nullptr) {
129 this->temperature_->publish_state(temperature);
130 }
131
132 // Calculate humidty value.
133 uint16_t raw_hum = encode_uint16(thdata[3], thdata[4]);
134
135 crc = compute_crc((uint32_t) raw_hum << 8);
136 if (crc != thdata[5]) {
137 this->status_set_warning();
138 ESP_LOGE(TAG, "Error validating humidty CRC");
139 return;
140 }
141
142 float humidity = raw_hum;
143 humidity /= 65535.0f;
144 humidity *= 100;
145
146 if (this->humidity_ != nullptr) {
147 this->humidity_->publish_state(humidity);
148 }
149
150 ESP_LOGD(TAG, "Got Temperature=%.1f°C Humidity=%.1f%%", temperature, humidity);
151 this->status_clear_warning();
152 });
153}
154
159 ESP_LOGCONFIG(TAG, "HTU31D:");
160 LOG_I2C_DEVICE(this);
161 if (this->is_failed()) {
162 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
163 }
164 LOG_UPDATE_INTERVAL(this);
165 LOG_SENSOR(" ", "Temperature", this->temperature_);
166 LOG_SENSOR(" ", "Humidity", this->humidity_);
167}
168
175 if (this->write_register(HTU31D_RESET, nullptr, 0) != i2c::ERROR_OK) {
176 return false;
177 }
178
179 delay(15);
180 return true;
181}
182
189 uint8_t reply[4];
190 uint32_t serial = 0;
191 uint8_t padding = 0;
192
193 // Verify we can read the device serial.
194 if (this->read_register(HTU31D_READSERIAL, reply, 4) != i2c::ERROR_OK) {
195 ESP_LOGE(TAG, "Error reading device serial");
196 return 0;
197 }
198
199 serial = encode_uint32(reply[0], reply[1], reply[2], padding);
200
201 uint8_t crc = compute_crc(serial);
202 if (crc != reply[3]) {
203 ESP_LOGE(TAG, "Error validating serial CRC");
204 return 0;
205 }
206
207 ESP_LOGD(TAG, "Found serial: 0x%" PRIX32, serial);
208
209 return serial;
210}
211
219 uint8_t reply[1];
220 uint8_t heater_enabled_position = 0;
221 uint8_t mask = 1 << heater_enabled_position;
222 uint8_t diagnostics = 0;
223
224 if (this->read_register(HTU31D_DIAGNOSTICS, reply, 1) != i2c::ERROR_OK) {
225 ESP_LOGE(TAG, "Error reading device serial");
226 return false;
227 }
228
229 diagnostics = reply[0];
230 return (diagnostics & mask) != 0;
231}
232
239 bool current = this->is_heater_enabled();
240
241 // If the current state matches the desired state, there is nothing to do.
242 if (current == desired) {
243 return;
244 }
245
246 // Update heater state.
248 if (desired) {
249 err = this->write_register(HTU31D_HEATERON, nullptr, 0);
250 } else {
251 err = this->write_register(HTU31D_HEATEROFF, nullptr, 0);
252 }
253
254 // Record any error.
255 if (err != i2c::ERROR_OK) {
256 this->status_set_warning();
257 ESP_LOGE(TAG, "Received error updating heater state");
258 return;
259 }
260}
261
268} // namespace htu31d
269} // namespace esphome
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 set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
void update() override
Setup (reset) the sensor and check connection.
Definition htu31d.cpp:93
uint32_t read_serial_num_()
Reads the serial number from the device and checks the CRC.
Definition htu31d.cpp:188
sensor::Sensor * temperature_
Definition htu31d.h:29
void setup() override
Resets the sensor and ensures that the devices serial number can be read over I2C.
Definition htu31d.cpp:77
float get_setup_priority() const override
Sets the startup priority for this component.
Definition htu31d.cpp:267
sensor::Sensor * humidity_
Definition htu31d.h:30
bool is_heater_enabled()
Checks the diagnostics register to determine if the heater is currently enabled.
Definition htu31d.cpp:218
void set_heater_state(bool desired)
Sets the heater state on or off.
Definition htu31d.cpp:238
bool reset_()
Sends a 'reset' request to the HTU31D, followed by a 15ms delay.
Definition htu31d.cpp:174
void dump_config() override
Update the sensor values (temperature+humidity).
Definition htu31d.cpp:158
ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len, bool stop=true)
writes an array of bytes to a specific register in the I²C device
Definition i2c.cpp:25
ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len, bool stop=true)
reads an array of bytes from a specific register in the I²C device
Definition i2c.cpp:10
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
u_int8_t raw_temp
uint8_t compute_crc(uint32_t value)
Computes a CRC result for the provided input.
Definition htu31d.cpp:52
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:11
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:13
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
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:181
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:173
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint16_t temperature
Definition sun_gtil2.cpp:12