ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
ms8607.cpp
Go to the documentation of this file.
1#include "ms8607.h"
2
3#include "esphome/core/hal.h"
5#include "esphome/core/log.h"
6
7namespace esphome {
8namespace ms8607 {
9
11static const char *const TAG = "ms8607";
12
14static const uint8_t MS8607_PT_CMD_RESET = 0x1E;
15
18static const uint8_t MS8607_PROM_START = 0xA0;
20static const uint8_t MS8607_PROM_END = 0xAE;
22static const uint8_t MS8607_PROM_COUNT = (MS8607_PROM_END - MS8607_PROM_START) >> 1;
23
25static const uint8_t MS8607_CMD_H_RESET = 0xFE;
27static const uint8_t MS8607_CMD_H_MEASURE_NO_HOLD = 0xF5;
29static const float MS8607_H_TEMP_COEFFICIENT = -0.18;
30
32static const uint8_t MS8607_CMD_ADC_READ = 0x00;
33
34// TODO: allow OSR to be turned down for speed and/or lower power consumption via configuration.
35// ms8607 supports 6 different settings
36
38static const uint8_t MS8607_CMD_CONV_D1_OSR_8K = 0x4A;
40static const uint8_t MS8607_CMD_CONV_D2_OSR_8K = 0x5A;
41
44 NONE = 0,
46 PTH_RESET_FAILED = 1,
48 PT_RESET_FAILED = 2,
50 H_RESET_FAILED = 3,
52 PROM_READ_FAILED = 4,
54 PROM_CRC_FAILED = 5,
55};
56
59 NEEDS_RESET,
61 NEEDS_PROM_READ,
63 SUCCESSFUL,
64};
65
66static uint8_t crc4(uint16_t *buffer, size_t length);
67static uint8_t hsensor_crc_check(uint16_t value);
68
72
73 // I do not know why the device sometimes NACKs the reset command, but
74 // try 3 times in case it's a transitory issue on this boot
75 this->set_retry(
76 "reset", 5, 3,
77 [this](const uint8_t remaining_setup_attempts) {
78 ESP_LOGD(TAG, "Resetting both I2C addresses: 0x%02X, 0x%02X", this->address_,
80 // I believe sending the reset command to both addresses is preferable to
81 // skipping humidity if PT fails for some reason.
82 // However, only consider the reset successful if they both ACK
83 bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
84 bool const h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
85
86 if (!(pt_successful && h_successful)) {
87 ESP_LOGE(TAG, "Resetting I2C devices failed");
88 if (!pt_successful && !h_successful) {
90 } else if (!pt_successful) {
92 } else {
94 }
95
96 if (remaining_setup_attempts > 0) {
97 this->status_set_error();
98 } else {
99 this->mark_failed();
100 }
101 return RetryResult::RETRY;
102 }
103
106 this->status_clear_error();
107
108 // 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
109 this->set_timeout("prom-read", 15, [this]() {
112 this->status_clear_error();
113 } else {
114 this->mark_failed();
115 return;
116 }
117 });
118
119 return RetryResult::DONE;
120 },
121 5.0f); // executes at now, +5ms, +25ms
122}
123
126 // setup is still occurring, either because reset had to retry or due to the 15ms
127 // delay needed between reset & reading the PROM values
128 return;
129 }
130
131 // Updating happens async and sequentially.
132 // Temperature, then pressure, then humidity
134}
135
137 ESP_LOGCONFIG(TAG, "MS8607:");
138 LOG_I2C_DEVICE(this);
139 // LOG_I2C_DEVICE doesn't work for humidity, the `address_` is protected. Log using get_address()
140 ESP_LOGCONFIG(TAG, " Address: 0x%02X", this->humidity_device_->get_address());
141 if (this->is_failed()) {
142 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
143 switch (this->error_code_) {
145 ESP_LOGE(TAG, "Temperature/Pressure RESET failed");
146 break;
148 ESP_LOGE(TAG, "Humidity RESET failed");
149 break;
151 ESP_LOGE(TAG, "Temperature/Pressure && Humidity RESET failed");
152 break;
154 ESP_LOGE(TAG, "Reading PROM failed");
155 break;
157 ESP_LOGE(TAG, "PROM values failed CRC");
158 break;
159 case ErrorCode::NONE:
160 default:
161 ESP_LOGE(TAG, "Error reason unknown %u", static_cast<uint8_t>(this->error_code_));
162 break;
163 }
164 }
165 LOG_UPDATE_INTERVAL(this);
166 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
167 LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
168 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
169}
170
172 ESP_LOGD(TAG, "Reading calibration values from PROM");
173
174 uint16_t buffer[MS8607_PROM_COUNT];
175 bool successful = true;
176
177 for (uint8_t idx = 0; idx < MS8607_PROM_COUNT; ++idx) {
178 uint8_t const address_to_read = MS8607_PROM_START + (idx * 2);
179 successful &= this->read_byte_16(address_to_read, &buffer[idx]);
180 }
181
182 if (!successful) {
183 ESP_LOGE(TAG, "Reading calibration values from PROM failed");
185 return false;
186 }
187
188 ESP_LOGD(TAG, "Checking CRC of calibration values from PROM");
189 uint8_t const expected_crc = (buffer[0] & 0xF000) >> 12; // first 4 bits
190 buffer[0] &= 0x0FFF; // strip CRC from buffer, in order to run CRC
191 uint8_t const actual_crc = crc4(buffer, MS8607_PROM_COUNT);
192
193 if (expected_crc != actual_crc) {
194 ESP_LOGE(TAG, "Incorrect CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc, actual_crc);
196 return false;
197 }
198
200 this->calibration_values_.pressure_offset = buffer[2];
205 ESP_LOGD(TAG, "Finished reading calibration values");
206
207 // Skipping reading Humidity PROM, since it doesn't have anything interesting for us
208
209 return true;
210}
211
218static uint8_t crc4(uint16_t *buffer, size_t length) {
219 uint16_t crc_remainder = 0;
220
221 // algorithm to add a byte into the crc
222 auto apply_crc = [&crc_remainder](uint8_t next) {
223 crc_remainder ^= next;
224 for (uint8_t bit = 8; bit > 0; --bit) {
225 if (crc_remainder & 0x8000) {
226 crc_remainder = (crc_remainder << 1) ^ 0x3000;
227 } else {
228 crc_remainder = (crc_remainder << 1);
229 }
230 }
231 };
232
233 // add all the bytes
234 for (size_t idx = 0; idx < length; ++idx) {
235 for (auto byte : decode_value(buffer[idx])) {
236 apply_crc(byte);
237 }
238 }
239 // For the MS8607 CRC, add a pair of zeros to shift the last byte from `buffer` through
240 apply_crc(0);
241 apply_crc(0);
242
243 return (crc_remainder >> 12) & 0xF; // only the most significant 4 bits
244}
245
255static uint8_t hsensor_crc_check(uint16_t value) {
256 uint32_t polynom = 0x988000; // x^8 + x^5 + x^4 + 1
257 uint32_t msb = 0x800000;
258 uint32_t mask = 0xFF8000;
259 uint32_t result = (uint32_t) value << 8; // Pad with zeros as specified in spec
260
261 while (msb != 0x80) {
262 // Check if msb of current value is 1 and apply XOR mask
263 if (result & msb) {
264 result = ((result ^ polynom) & mask) | (result & ~mask);
265 }
266
267 // Shift by one
268 msb >>= 1;
269 mask >>= 1;
270 polynom >>= 1;
271 }
272 return result & 0xFF;
273}
274
276 // Tell MS8607 to start ADC conversion of temperature sensor
277 if (!this->write_bytes(MS8607_CMD_CONV_D2_OSR_8K, nullptr, 0)) {
278 this->status_set_warning();
279 return;
280 }
281
282 auto f = std::bind(&MS8607Component::read_temperature_, this);
283 // datasheet says 17.2ms max conversion time at OSR 8192
284 this->set_timeout("temperature", 20, f);
285}
286
288 uint8_t bytes[3]; // 24 bits
289 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
290 this->status_set_warning();
291 return;
292 }
293
294 const uint32_t d2_raw_temperature = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
295 this->request_read_pressure_(d2_raw_temperature);
296}
297
298void MS8607Component::request_read_pressure_(uint32_t d2_raw_temperature) {
299 if (!this->write_bytes(MS8607_CMD_CONV_D1_OSR_8K, nullptr, 0)) {
300 this->status_set_warning();
301 return;
302 }
303
304 auto f = std::bind(&MS8607Component::read_pressure_, this, d2_raw_temperature);
305 // datasheet says 17.2ms max conversion time at OSR 8192
306 this->set_timeout("pressure", 20, f);
307}
308
309void MS8607Component::read_pressure_(uint32_t d2_raw_temperature) {
310 uint8_t bytes[3]; // 24 bits
311 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
312 this->status_set_warning();
313 return;
314 }
315 const uint32_t d1_raw_pressure = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
316 this->calculate_values_(d2_raw_temperature, d1_raw_pressure);
317}
318
319void MS8607Component::request_read_humidity_(float temperature_float) {
320 if (!this->humidity_device_->write_bytes(MS8607_CMD_H_MEASURE_NO_HOLD, nullptr, 0)) {
321 ESP_LOGW(TAG, "Request to measure humidity failed");
322 this->status_set_warning();
323 return;
324 }
325
326 auto f = std::bind(&MS8607Component::read_humidity_, this, temperature_float);
327 // datasheet says 15.89ms max conversion time at OSR 8192
328 this->set_timeout("humidity", 20, f);
329}
330
331void MS8607Component::read_humidity_(float temperature_float) {
332 uint8_t bytes[3];
333 if (!this->humidity_device_->read_bytes_raw(bytes, 3)) {
334 ESP_LOGW(TAG, "Failed to read the measured humidity value");
335 this->status_set_warning();
336 return;
337 }
338
339 // "the measurement is stored into 14 bits. The two remaining LSBs are used for transmitting status information.
340 // Bit1 of the two LSBS must be set to '1'. Bit0 is currently not assigned"
341 uint16_t humidity = encode_uint16(bytes[0], bytes[1]);
342 uint8_t const expected_crc = bytes[2];
343 uint8_t const actual_crc = hsensor_crc_check(humidity);
344 if (expected_crc != actual_crc) {
345 ESP_LOGE(TAG, "Incorrect Humidity CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc,
346 actual_crc);
347 this->status_set_warning();
348 return;
349 }
350 if (!(humidity & 0x2)) {
351 // data sheet says Bit1 should always set, but nothing about what happens if it isn't
352 ESP_LOGE(TAG, "Humidity status bit was not set to 1?");
353 }
354 humidity &= ~(0b11); // strip status & unassigned bits from data
355
356 // map 16 bit humidity value into range [-6%, 118%]
357 float const humidity_partial = double(humidity) / (1 << 16);
358 float const humidity_percentage = std::lerp(-6.0, 118.0, humidity_partial);
359 float const compensated_humidity_percentage =
360 humidity_percentage + (20 - temperature_float) * MS8607_H_TEMP_COEFFICIENT;
361 ESP_LOGD(TAG, "Compensated for temperature, humidity=%.2f%%", compensated_humidity_percentage);
362
363 if (this->humidity_sensor_ != nullptr) {
364 this->humidity_sensor_->publish_state(compensated_humidity_percentage);
365 }
366 this->status_clear_warning();
367}
368
369void MS8607Component::calculate_values_(uint32_t d2_raw_temperature, uint32_t d1_raw_pressure) {
370 // Perform the first order pressure/temperature calculation
371
372 // d_t: "difference between actual and reference temperature" = D2 - [C5] * 2**8
373 const int32_t d_t = int32_t(d2_raw_temperature) - (int32_t(this->calibration_values_.reference_temperature) << 8);
374 // actual temperature as hundredths of degree celsius in range [-4000, 8500]
375 // 2000 + d_t * [C6] / (2**23)
376 int32_t temperature =
377 2000 + ((int64_t(d_t) * this->calibration_values_.temperature_coefficient_of_temperature) >> 23);
378
379 // offset at actual temperature. [C2] * (2**17) + (d_t * [C4] / (2**6))
380 int64_t pressure_offset = (int64_t(this->calibration_values_.pressure_offset) << 17) +
382 // sensitivity at actual temperature. [C1] * (2**16) + ([C3] * d_t) / (2**7)
383 int64_t pressure_sensitivity =
384 (int64_t(this->calibration_values_.pressure_sensitivity) << 16) +
386
387 // Perform the second order compensation, for non-linearity over temperature range
388 const int64_t d_t_squared = int64_t(d_t) * d_t;
389 int64_t temperature_2 = 0;
390 int32_t pressure_offset_2 = 0;
391 int32_t pressure_sensitivity_2 = 0;
392 if (temperature < 2000) {
393 // (TEMP - 2000)**2 / 2**4
394 const int32_t low_temperature_adjustment = (temperature - 2000) * (temperature - 2000) >> 4;
395
396 // T2 = 3 * (d_t**2) / 2**33
397 temperature_2 = (3 * d_t_squared) >> 33;
398 // OFF2 = 61 * (TEMP-2000)**2 / 2**4
399 pressure_offset_2 = 61 * low_temperature_adjustment;
400 // SENS2 = 29 * (TEMP-2000)**2 / 2**4
401 pressure_sensitivity_2 = 29 * low_temperature_adjustment;
402
403 if (temperature < -1500) {
404 // (TEMP+1500)**2
405 const int32_t very_low_temperature_adjustment = (temperature + 1500) * (temperature + 1500);
406
407 // OFF2 = OFF2 + 17 * (TEMP+1500)**2
408 pressure_offset_2 += 17 * very_low_temperature_adjustment;
409 // SENS2 = SENS2 + 9 * (TEMP+1500)**2
410 pressure_sensitivity_2 += 9 * very_low_temperature_adjustment;
411 }
412 } else {
413 // T2 = 5 * (d_t**2) / 2**38
414 temperature_2 = (5 * d_t_squared) >> 38;
415 }
416
417 temperature -= temperature_2;
418 pressure_offset -= pressure_offset_2;
419 pressure_sensitivity -= pressure_sensitivity_2;
420
421 // Temperature compensated pressure. [1000, 120000] => [10.00 mbar, 1200.00 mbar]
422 const int32_t pressure = (((d1_raw_pressure * pressure_sensitivity) >> 21) - pressure_offset) >> 15;
423
424 const float temperature_float = temperature / 100.0f;
425 const float pressure_float = pressure / 100.0f;
426 ESP_LOGD(TAG, "Temperature=%0.2f°C, Pressure=%0.2fhPa", temperature_float, pressure_float);
427
428 if (this->temperature_sensor_ != nullptr) {
429 this->temperature_sensor_->publish_state(temperature_float);
430 }
431 if (this->pressure_sensor_ != nullptr) {
432 this->pressure_sensor_->publish_state(pressure_float); // hPa aka mbar
433 }
434 this->status_clear_warning();
435
436 if (this->humidity_sensor_ != nullptr) {
437 // now that we have temperature (to compensate the humidity with), kick off that read
438 this->request_read_humidity_(temperature_float);
439 }
440}
441
442} // namespace ms8607
443} // 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 status_set_error(const char *message=nullptr)
void set_retry(const std::string &name, uint32_t initial_wait_time, uint8_t max_attempts, std::function< RetryResult(uint8_t)> &&f, float backoff_increase_factor=1.0f)
Set an retry function with a unique name.
bool read_bytes_raw(uint8_t *data, uint8_t len)
Definition i2c.h:220
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len, bool stop=true)
Definition i2c.h:252
uint8_t address_
store the address of the device on the bus
Definition i2c.h:273
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:250
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 read_humidity_(float temperature_float)
process async humidity read
Definition ms8607.cpp:331
void request_read_temperature_()
Start async temperature read.
Definition ms8607.cpp:275
@ PROM_CRC_FAILED
The PROM calibration values failed the CRC check.
@ H_RESET_FAILED
Asking the Humidity sensor to reset failed.
@ PT_RESET_FAILED
Asking the Pressure/Temperature sensor to reset failed.
@ PROM_READ_FAILED
Reading the PROM calibration values failed.
@ PTH_RESET_FAILED
Both the Pressure/Temperature address and the Humidity address failed to reset.
@ NONE
Component hasn't failed (yet?)
struct esphome::ms8607::MS8607Component::CalibrationValues calibration_values_
MS8607HumidityDevice * humidity_device_
I2CDevice object to communicate with secondary I2C address for the humidity sensor.
Definition ms8607.h:78
sensor::Sensor * temperature_sensor_
Definition ms8607.h:68
sensor::Sensor * humidity_sensor_
Definition ms8607.h:70
SetupStatus setup_status_
Current step in the multi-step & possibly delayed setup() process.
Definition ms8607.h:104
void calculate_values_(uint32_t raw_temperature, uint32_t raw_pressure)
use raw temperature & pressure to calculate & publish values
Definition ms8607.cpp:369
void read_pressure_(uint32_t raw_temperature)
process async pressure read
Definition ms8607.cpp:309
ErrorCode error_code_
Keep track of the reason why this component failed, to augment the dumped config.
Definition ms8607.h:99
bool read_calibration_values_from_prom_()
Read and store the Pressure & Temperature calibration settings from the PROM.
Definition ms8607.cpp:171
void request_read_pressure_(uint32_t raw_temperature)
start async pressure read
Definition ms8607.cpp:298
sensor::Sensor * pressure_sensor_
Definition ms8607.h:69
@ NEEDS_PROM_READ
Reset commands succeeded, need to wait >= 15ms to read PROM.
@ NEEDS_RESET
This component has not successfully reset the PT & H devices.
@ SUCCESSFUL
Successfully read PROM and ready to update sensors.
void read_temperature_()
Process async temperature read.
Definition ms8607.cpp:287
void request_read_humidity_(float temperature_float)
start async humidity read
Definition ms8607.cpp:319
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
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
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:202
uint16_t pressure_offset_temperature_coefficient
Temperature coefficient of pressure offset | TCO. [C4].
Definition ms8607.h:89
uint16_t temperature_coefficient_of_temperature
Temperature coefficient of the temperature | TEMPSENS. [C6].
Definition ms8607.h:93
uint16_t pressure_sensitivity_temperature_coefficient
Temperature coefficient of pressure sensitivity | TCS. [C3].
Definition ms8607.h:85
uint16_t pressure_sensitivity
Pressure sensitivity | SENS-T1. [C1].
Definition ms8607.h:83
uint16_t pressure_offset
Pressure offset | OFF-T1. [C2].
Definition ms8607.h:87
uint16_t reference_temperature
Reference temperature | T-REF. [C5].
Definition ms8607.h:91
uint16_t temperature
Definition sun_gtil2.cpp:12
uint16_t length
Definition tt21100.cpp:0
uint8_t pressure
Definition tt21100.cpp:7