ESPHome  2024.5.2
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"
12 #include "esphome/core/helpers.h"
13 #include "esphome/core/log.h"
14 
15 namespace esphome {
16 namespace htu31d {
17 
19 static const char *const TAG = "htu31d";
20 
22 static const uint8_t HTU31D_DEFAULT_I2CADDR = 0x40;
23 
25 static const uint8_t HTU31D_READTEMPHUM = 0x00;
26 
28 static const uint8_t HTU31D_CONVERSION = 0x40;
29 
31 static const uint8_t HTU31D_READSERIAL = 0x0A;
32 
34 static const uint8_t HTU31D_HEATERON = 0x04;
35 
37 static const uint8_t HTU31D_HEATEROFF = 0x02;
38 
40 static const uint8_t HTU31D_RESET = 0x1E;
41 
43 static const uint8_t HTU31D_DIAGNOSTICS = 0x08;
44 
50 uint8_t compute_crc(uint32_t value) {
51  uint32_t polynom = 0x98800000; // x^8 + x^5 + x^4 + 1
52  uint32_t msb = 0x80000000;
53  uint32_t mask = 0xFF800000;
54  uint32_t threshold = 0x00000080;
55  uint32_t result = value;
56 
57  while (msb != threshold) {
58  // Check if msb of current value is 1 and apply XOR mask
59  if (result & msb)
60  result = ((result ^ polynom) & mask) | (result & ~mask);
61 
62  // Shift by one
63  msb >>= 1;
64  mask >>= 1;
65  polynom >>= 1;
66  }
67 
68  return result;
69 }
70 
76  ESP_LOGCONFIG(TAG, "Setting up esphome/components/htu31d HTU31D...");
77 
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, "Communication with HTU31D failed!");
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%X", 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
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:19
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 status_set_warning(const char *message="unspecified")
Definition: component.cpp:151
void setup() override
Resets the sensor and ensures that the devices serial number can be read over I2C.
Definition: htu31d.cpp:75
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:69
bool reset_()
Sends a &#39;reset&#39; request to the HTU31D, followed by a 15ms delay.
Definition: htu31d.cpp:174
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:186
sensor::Sensor * humidity_
Definition: htu31d.h:30
No error found during execution of method.
Definition: i2c_bus.h:13
float get_setup_priority() const override
Sets the startup priority for this component.
Definition: htu31d.cpp:267
void dump_config() override
Update the sensor values (temperature+humidity).
Definition: htu31d.cpp:158
void status_clear_warning()
Definition: component.cpp:166
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:39
uint32_t read_serial_num_()
Reads the serial number from the device and checks the CRC.
Definition: htu31d.cpp:188
uint8_t compute_crc(uint32_t value)
Computes a CRC result for the provided input.
Definition: htu31d.cpp:50
uint16_t temperature
Definition: sun_gtil2.cpp:26
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:182
u_int8_t raw_temp
bool is_heater_enabled()
Checks the diagnostics register to determine if the heater is currently enabled.
Definition: htu31d.cpp:218
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
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
void set_heater_state(bool desired)
Sets the heater state on or off.
Definition: htu31d.cpp:238
void update() override
Setup (reset) the sensor and check connection.
Definition: htu31d.cpp:93
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition: i2c_bus.h:11
sensor::Sensor * temperature_
Definition: htu31d.h:29
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26