ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ms8607.cpp
Go to the documentation of this file.
1#include "ms8607.h"
2
3#include <cmath>
4
5#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
8
9namespace esphome::ms8607 {
10
11ESPHOME_LOG_TAG(TAG, "ms8607");
12
13static constexpr uint32_t RESET_TIMEOUT_ID = 0;
14static constexpr uint32_t PROM_READ_TIMEOUT_ID = 1;
15static constexpr uint32_t TEMPERATURE_TIMEOUT_ID = 2;
16static constexpr uint32_t PRESSURE_TIMEOUT_ID = 3;
17static constexpr uint32_t HUMIDITY_TIMEOUT_ID = 4;
18
20static constexpr uint8_t MS8607_PT_CMD_RESET = 0x1E;
21
24static constexpr uint8_t MS8607_PROM_START = 0xA0;
26static constexpr uint8_t MS8607_PROM_END = 0xAE;
28static constexpr uint8_t MS8607_PROM_COUNT = (MS8607_PROM_END - MS8607_PROM_START) >> 1;
29
31static constexpr uint8_t MS8607_CMD_H_RESET = 0xFE;
33static constexpr uint8_t MS8607_CMD_H_MEASURE_NO_HOLD = 0xF5;
35static constexpr float MS8607_H_TEMP_COEFFICIENT = -0.18f;
36
38static constexpr uint8_t MS8607_CMD_ADC_READ = 0x00;
39
40// TODO: allow OSR to be turned down for speed and/or lower power consumption via configuration.
41// ms8607 supports 6 different settings
42
44static constexpr uint8_t MS8607_CMD_CONV_D1_OSR_8K = 0x4A;
46static constexpr uint8_t MS8607_CMD_CONV_D2_OSR_8K = 0x5A;
47
48static uint8_t crc4(uint16_t *buffer, size_t length);
49
50// Sanity check Temperature & Pressure Readings, these values are way out of range
51
53static constexpr float TEMPERATURE_LOWER_LIMIT = -50.0f;
55static constexpr float TEMPERATURE_UPPER_LIMIT = 100.0f;
56
58static constexpr float PRESSURE_LOWER_LIMIT = 0.0f;
60static constexpr float PRESSURE_UPPER_LIMIT = 2000.0f;
61
62void MS8607Component::setup() {
63 // I do not know why the device sometimes NACKs the reset command, but
64 // try 3 times in case it's a transitory issue on this boot
65 // Backoff: executes at now, +5ms, +30ms
66 this->try_reset_();
67}
68
70 // I believe sending the reset command to both addresses is preferable to
71 // skipping humidity if PT fails for some reason.
72 // However, only consider the reset successful if they both ACK
73 bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
74 bool h_successful = true;
75 if (this->humidity_device_ != nullptr) {
76 ESP_LOGD(TAG, "Resetting I2C addresses: 0x%02X, 0x%02X", this->address_, this->humidity_device_->get_i2c_address());
77 h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
78 } else {
79 ESP_LOGD(TAG, "Resetting I2C address: 0x%02X", this->address_);
80 }
81
82 if (!(pt_successful && h_successful)) {
83 ESP_LOGE(TAG, "Resetting I2C devices failed");
84 if (--this->reset_attempts_remaining_ > 0) {
86 this->reset_interval_ *= 5;
87 this->set_timeout(RESET_TIMEOUT_ID, delay, [this]() { this->try_reset_(); });
88 this->status_set_error();
89 return;
90 }
91 // The retries set the error flag without a reason; clear it so mark_failed() can record one
92 this->status_clear_error();
93 if (!pt_successful && !h_successful) {
94 this->mark_failed(LOG_STR("Temperature/Pressure and Humidity reset failed"));
95 } else if (!pt_successful) {
96 this->mark_failed(LOG_STR("Temperature/Pressure reset failed"));
97 } else {
98 this->mark_failed(LOG_STR("Humidity reset failed"));
99 }
100 return;
101 }
102
103 this->status_clear_error();
104
105 // 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
106 this->set_timeout(PROM_READ_TIMEOUT_ID, 15, [this]() {
108 this->setup_complete_ = true;
109 });
110}
111
112void MS8607Component::update() {
113 if (!this->setup_complete_) {
114 // setup is still occurring, either because reset had to retry or due to the 15ms
115 // delay needed between reset & reading the PROM values
116 return;
117 }
118
119 this->update_ok_ = true;
120
121 // Updating happens async and sequentially.
122 // Temperature, then optionally pressure, then optionally humidity
123 // Temperature is used for compensation of pressure & humidity, so we'll always want it
125}
126
127void MS8607Component::dump_config() {
128 ESP_LOGCONFIG(TAG, "MS8607:");
129 LOG_I2C_DEVICE(this);
130 if (this->humidity_device_ != nullptr) {
131 ESP_LOGCONFIG(TAG, " Address: 0x%02X", this->humidity_device_->get_i2c_address());
132 }
133 LOG_UPDATE_INTERVAL(this);
134 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
135 LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
136 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
137 // Empty at boot, since the PROM is read after a delay; useful on a device that is already running
138 ESP_LOGVV(TAG,
139 " Calibration Values:\n"
140 " Pressure Sensitivity: 0x%04X\n"
141 " Pressure Offset: 0x%04X\n"
142 " Pressure Sensitivity Temperature Coefficient: 0x%04X\n"
143 " Pressure Offset Temperature Coefficient: 0x%04X\n"
144 " Reference Temperature: 0x%04X\n"
145 " Temperature Coefficient of Temperature: 0x%04X",
146 this->calibration_values_.pressure_sensitivity, this->calibration_values_.pressure_offset,
147 this->calibration_values_.pressure_sensitivity_temperature_coefficient,
148 this->calibration_values_.pressure_offset_temperature_coefficient,
149 this->calibration_values_.reference_temperature,
150 this->calibration_values_.temperature_coefficient_of_temperature);
151}
152
154 ESP_LOGD(TAG, "Reading calibration values from PROM");
155
156 uint16_t buffer[MS8607_PROM_COUNT];
157 bool successful = true;
158
159 for (uint8_t idx = 0; idx < MS8607_PROM_COUNT; ++idx) {
160 uint8_t const address_to_read = MS8607_PROM_START + (idx * 2);
161 successful &= this->read_byte_16(address_to_read, &buffer[idx]);
162 }
163
164 if (!successful) {
165 this->mark_failed(LOG_STR("Reading the PROM calibration values failed"));
166 return false;
167 }
168
169 ESP_LOGD(TAG, "Checking CRC of calibration values from PROM");
170 uint8_t const expected_crc = (buffer[0] & 0xF000) >> 12; // first 4 bits
171 buffer[0] &= 0x0FFF; // strip CRC from buffer, in order to run CRC
172 uint8_t const actual_crc = crc4(buffer, MS8607_PROM_COUNT);
173
174 if (expected_crc != actual_crc) {
175 ESP_LOGE(TAG, "Incorrect CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc, actual_crc);
176 this->mark_failed(LOG_STR("PROM calibration values failed the CRC check"));
177 return false;
178 }
179
181 this->calibration_values_.pressure_offset = buffer[2];
186 ESP_LOGD(TAG, "Finished reading calibration values");
187
188 // Skipping reading Humidity PROM, since it doesn't have anything interesting for us
189
190 return true;
191}
192
199static uint8_t crc4(uint16_t *buffer, size_t length) {
200 uint16_t crc_remainder = 0;
201
202 // algorithm to add a byte into the crc
203 auto apply_crc = [&crc_remainder](uint8_t next) {
204 crc_remainder ^= next;
205 for (uint8_t bit = 8; bit > 0; --bit) {
206 if (crc_remainder & 0x8000) {
207 crc_remainder = (crc_remainder << 1) ^ 0x3000;
208 } else {
209 crc_remainder = (crc_remainder << 1);
210 }
211 }
212 };
213
214 // add all the bytes
215 for (size_t idx = 0; idx < length; ++idx) {
216 for (auto byte : decode_value(buffer[idx])) {
217 apply_crc(byte);
218 }
219 }
220 // For the MS8607 CRC, add a pair of zeros to shift the last byte from `buffer` through
221 apply_crc(0);
222 apply_crc(0);
223
224 return (crc_remainder >> 12) & 0xF; // only the most significant 4 bits
225}
226
228 uint8_t bytes[3]; // 24 bits
229 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3))
230 return false;
231 value = encode_uint24(bytes[0], bytes[1], bytes[2]);
232 return true;
233}
234
236 // Tell MS8607 to start ADC conversion of temperature sensor
237 if (!this->write_bytes(MS8607_CMD_CONV_D2_OSR_8K, nullptr, 0)) {
238 ESP_LOGW(TAG, "Requesting ADC Read of temperature failed");
239 this->update_ok_ = false;
240 this->finalize_update_();
241 return;
242 }
243
244 // datasheet says 17.2ms max conversion time at OSR 8192
245 this->set_timeout(TEMPERATURE_TIMEOUT_ID, 20, [this]() { this->read_temperature_(); });
246}
247
249 uint32_t d2_raw_temperature;
250 if (!this->read_adc_(d2_raw_temperature)) {
251 ESP_LOGW(TAG, "ADC Read of temperature failed");
252 this->update_ok_ = false;
253 this->finalize_update_();
254 return;
255 }
256
258 if (temperature.temperature_float < TEMPERATURE_LOWER_LIMIT ||
259 temperature.temperature_float > TEMPERATURE_UPPER_LIMIT) {
260 ESP_LOGW(TAG, "Treating this temperature read of %0.2f°C as a failed read, skipping it",
261 temperature.temperature_float);
262 this->update_ok_ = false;
263 this->finalize_update_();
264 return;
265 }
266
267 PUBLISH_STATE(this->temperature_sensor_, temperature.temperature_float);
268
269 if (this->pressure_sensor_ == nullptr || !this->request_read_pressure_(d2_raw_temperature)) {
270 this->finish_update_(temperature.temperature_float);
271 }
272}
273
275 if (!this->write_bytes(MS8607_CMD_CONV_D1_OSR_8K, nullptr, 0)) {
276 ESP_LOGW(TAG, "Requesting ADC Read of pressure failed");
277 this->update_ok_ = false;
278 return false;
279 }
280
281 // datasheet says 17.2ms max conversion time at OSR 8192
282 this->set_timeout(PRESSURE_TIMEOUT_ID, 20,
283 [this, d2_raw_temperature]() { this->read_pressure_(d2_raw_temperature); });
284 return true;
285}
286
289
290 uint32_t d1_raw_pressure;
291 if (!this->read_adc_(d1_raw_pressure)) {
292 ESP_LOGW(TAG, "ADC Read of pressure failed");
293 this->update_ok_ = false;
294 } else if (d1_raw_pressure == 0) {
295 // Sensor returns all zeros if the ADC conversion isn't done yet. Check the timeout in request_read_pressure_
296 ESP_LOGW(TAG, "ADC Read of pressure returned all zeros, the conversion had not finished");
297 this->update_ok_ = false;
298 } else {
299 const float pressure = compensated_pressure(d1_raw_pressure, this->calibration_values_, temperature);
300 if (pressure < PRESSURE_LOWER_LIMIT || pressure > PRESSURE_UPPER_LIMIT) {
301 ESP_LOGW(TAG, "Treating this pressure read of %.2fhPa as a failed read, skipping it", pressure);
302 this->update_ok_ = false;
303 } else {
304 this->pressure_sensor_->publish_state(pressure); // hPa aka mbar
305 }
306 }
307
308 this->finish_update_(temperature.temperature_float);
309}
310
312 if (this->humidity_device_ != nullptr) {
313 // now that we have temperature (to compensate the humidity with), kick off that read
314 this->request_read_humidity_(temperature);
315 } else {
316 this->finalize_update_();
317 }
318}
319
321 if (!this->humidity_device_->write_bytes(MS8607_CMD_H_MEASURE_NO_HOLD, nullptr, 0)) {
322 ESP_LOGW(TAG, "Request to measure humidity failed");
323 this->update_ok_ = false;
324 this->finalize_update_();
325 return;
326 }
327
328 // datasheet says 15.89ms max conversion time at OSR 8192
329 this->set_timeout(HUMIDITY_TIMEOUT_ID, 20, [this, temperature]() { this->read_humidity_(temperature); });
330}
331
333 uint8_t bytes[3];
334 if (!this->humidity_device_->read_bytes_raw(bytes, 3)) {
335 ESP_LOGW(TAG, "Failed to read the measured humidity value");
336 this->update_ok_ = false;
337 this->finalize_update_();
338 return;
339 }
340
341 // "the measurement is stored into 14 bits. The two remaining LSBs are used for transmitting status information.
342 // Bit1 of the two LSBS must be set to '1'. Bit0 is currently not assigned"
343 uint16_t humidity = encode_uint16(bytes[0], bytes[1]);
344 uint8_t const expected_crc = bytes[2];
345 uint8_t const actual_crc = crc8(bytes, 2, 0, 0x31, true);
346 if (expected_crc != actual_crc) {
347 ESP_LOGW(TAG, "Incorrect Humidity CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc,
348 actual_crc);
349 this->update_ok_ = false;
350 this->finalize_update_();
351 return;
352 }
353 if (!(humidity & 0x2)) {
354 // data sheet says Bit1 should always set, but nothing about what happens if it isn't
355 ESP_LOGW(TAG, "Humidity status bit was not set to 1?");
356 }
357 if (humidity == 0) {
358 // treat this like a bad I2C read, because we received all zeros, despite the datasheet saying
359 // there should be at least Bit1 set. CRC might have passed because all zeros results in expected CRC of 0.
360 ESP_LOGW(TAG, "Treating this humidity read as a failed read, skipping it");
361 this->update_ok_ = false;
362 this->finalize_update_();
363 return;
364 }
365 humidity &= ~(0b11); // strip status & unassigned bits from data
366
367 this->humidity_sensor_->publish_state(compensated_humidity(humidity, temperature));
368 this->finalize_update_();
369}
370
372
374 const CalibrationValues &calibration_values) {
376 // Perform the first order temperature calculation
377
378 // d_t: "difference between actual and reference temperature" = D2 - [C5] * 2**8
379 result.d_t = int32_t(d2_raw_temperature) - (int32_t(calibration_values.reference_temperature) << 8);
380 const int64_t d_t_squared = int64_t(result.d_t) * result.d_t;
381
382 // actual temperature as hundredths of degree celsius in range [-4000, 8500]
383 // 2000 + d_t * [C6] / (2**23)
385 2000 + ((int64_t(result.d_t) * calibration_values.temperature_coefficient_of_temperature) >> 23);
386
387 // Perform the second order temperature compensation, for non-linearity over temperature range
388 int32_t temperature_2;
389 if (result.first_order_temperature < 2000) {
390 // T2 = 3 * (d_t**2) / 2**33
391 temperature_2 = int32_t((3 * d_t_squared) >> 33);
392 } else {
393 // T2 = 5 * (d_t**2) / 2**38
394 temperature_2 = int32_t((5 * d_t_squared) >> 38);
395 }
396
397 result.temperature_float = (result.first_order_temperature - temperature_2) / 100.0f;
398
399 return result;
400}
401
402float compensated_pressure(uint32_t d1_raw_pressure, const CalibrationValues &calibration_values,
403 const CompensatedTemperature &temperature_values) {
404 // Perform the first order pressure calculation
405
406 // offset at actual temperature. [C2] * (2**17) + (d_t * [C4] / (2**6))
407 int64_t pressure_offset =
408 (int64_t(calibration_values.pressure_offset) << 17) +
409 ((int64_t(temperature_values.d_t) * calibration_values.pressure_offset_temperature_coefficient) >> 6);
410 // sensitivity at actual temperature. [C1] * (2**16) + ([C3] * d_t) / (2**7)
411 int64_t pressure_sensitivity =
412 (int64_t(calibration_values.pressure_sensitivity) << 16) +
413 ((int64_t(temperature_values.d_t) * calibration_values.pressure_sensitivity_temperature_coefficient) >> 7);
414
415 // Perform the second order pressure compensation, for non-linearity over temperature range
416 int32_t pressure_offset_2 = 0;
417 int32_t pressure_sensitivity_2 = 0;
418 if (temperature_values.first_order_temperature < 2000) {
419 // (TEMP - 2000)**2 / 2**4
420 const int32_t low_temperature_adjustment =
421 (temperature_values.first_order_temperature - 2000) * (temperature_values.first_order_temperature - 2000) >> 4;
422
423 // OFF2 = 61 * (TEMP-2000)**2 / 2**4
424 pressure_offset_2 = 61 * low_temperature_adjustment;
425 // SENS2 = 29 * (TEMP-2000)**2 / 2**4
426 pressure_sensitivity_2 = 29 * low_temperature_adjustment;
427
428 if (temperature_values.first_order_temperature < -1500) {
429 // (TEMP+1500)**2
430 const int32_t very_low_temperature_adjustment =
431 (temperature_values.first_order_temperature + 1500) * (temperature_values.first_order_temperature + 1500);
432
433 // OFF2 = OFF2 + 17 * (TEMP+1500)**2
434 pressure_offset_2 += 17 * very_low_temperature_adjustment;
435 // SENS2 = SENS2 + 9 * (TEMP+1500)**2
436 pressure_sensitivity_2 += 9 * very_low_temperature_adjustment;
437 }
438 }
439
440 pressure_offset -= pressure_offset_2;
441 pressure_sensitivity -= pressure_sensitivity_2;
442
443 // Temperature compensated pressure. [1000, 120000] => [10.00 mbar, 1200.00 mbar]
444 const int32_t pressure = (((d1_raw_pressure * pressure_sensitivity) >> 21) - pressure_offset) >> 15;
445
446 return pressure / 100.0f;
447}
448
449float compensated_humidity(float humidity_float, float temperature_float) {
450 // map 16 bit humidity value into range [-6%, 119%]
451 // Datasheet is inconsistent on upper max value (118 vs 119), but example value,
452 // calculation equation, and max value in table all indicate it should be 119%
453 float const humidity_partial = humidity_float / (1 << 16);
454 float const humidity_percentage = std::lerp(-6.0f, 119.0f, humidity_partial);
455 return humidity_percentage + (20 - temperature_float) * MS8607_H_TEMP_COEFFICIENT;
456}
457
458} // namespace esphome::ms8607
void mark_failed()
Mark this component as failed.
void status_clear_error()
Definition component.h:315
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
bool read_bytes_raw(uint8_t *data, uint8_t len) const
Definition i2c.h:253
uint8_t get_i2c_address() const
Returns the I2C address of the object.
Definition i2c.h:155
uint8_t address_
store the address of the device on the bus
Definition i2c.h:327
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:281
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:298
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:249
void request_read_humidity_(float temperature)
start async humidity read
Definition ms8607.cpp:320
void request_read_temperature_()
Start async temperature read.
Definition ms8607.cpp:235
bool update_ok_
False once any step of the current update cycle failed.
Definition ms8607.h:122
bool read_adc_(uint32_t &value)
Read a 24-bit converted ADC value, either D1 (pressure) or D2 (temperature)
Definition ms8607.cpp:227
MS8607HumidityDevice * humidity_device_
I2CDevice object to communicate with secondary I2C address for the humidity sensor.
Definition ms8607.h:112
void read_humidity_(float temperature)
process async humidity read
Definition ms8607.cpp:332
void read_pressure_(uint32_t d2_raw_temperature)
Process async pressure read and publish it.
Definition ms8607.cpp:287
bool request_read_pressure_(uint32_t d2_raw_temperature)
Start async pressure read; false if the request failed.
Definition ms8607.cpp:274
bool setup_complete_
Set once the PROM calibration values have been read.
Definition ms8607.h:118
CalibrationValues calibration_values_
This device's pressure & temperature calibration values, read from PROM.
Definition ms8607.h:115
void finalize_update_()
End the update cycle, setting or clearing the warning from update_ok_.
Definition ms8607.cpp:371
bool read_calibration_values_from_prom_()
Read and CRC-check the PROM calibration values; marks the component failed on error.
Definition ms8607.cpp:153
void try_reset_()
Attempt to reset both I2C devices, retrying with backoff on failure.
Definition ms8607.cpp:69
void read_temperature_()
Process async temperature read, publish it and hand off to pressure or humidity.
Definition ms8607.cpp:248
void finish_update_(float temperature)
Read humidity if it is configured, otherwise end the update cycle.
Definition ms8607.cpp:311
NameCopy * next
uint32_t buffer
Definition gif.cpp:50
float compensated_humidity(float humidity_float, float temperature_float)
convert raw humidity value into correct range & apply temperature compensation calculation
Definition ms8607.cpp:449
ESPHOME_LOG_TAG(TAG, "ms8607")
float compensated_pressure(uint32_t d1_raw_pressure, const CalibrationValues &calibration_values, const CompensatedTemperature &temperature_values)
use raw pressure, calibration values, and current temperature to figure out actual pressure Precondit...
Definition ms8607.cpp:402
CompensatedTemperature compensated_temperature(uint32_t d2_raw_temperature, const CalibrationValues &calibration_values)
use raw temperature and calibration values to figure out actual temperature value return value includ...
Definition ms8607.cpp:373
uint32_t value
Definition hal.cpp:41
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition helpers.h:1047
uint8_t crc8(const uint8_t *data, uint8_t len, uint8_t crc, uint8_t poly, bool msb_first)
Calculate a CRC-8 checksum of data with size len.
Definition helpers.cpp:68
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:1043
void HOT delay(uint32_t ms)
Definition hal.cpp:85
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:1101
static void uint32_t
Pressure & temperature calibration values, read from the PROM.
Definition ms8607.h:10
uint16_t pressure_offset_temperature_coefficient
Temperature coefficient of pressure offset | TCO. [C4].
Definition ms8607.h:18
uint16_t pressure_sensitivity_temperature_coefficient
Temperature coefficient of pressure sensitivity | TCS. [C3].
Definition ms8607.h:14
uint16_t pressure_sensitivity
Pressure sensitivity | SENS-T1. [C1].
Definition ms8607.h:12
uint16_t temperature_coefficient_of_temperature
Temperature coefficient of the temperature | TEMPSENS. [C6].
Definition ms8607.h:22
uint16_t reference_temperature
Reference temperature | T-REF. [C5].
Definition ms8607.h:20
uint16_t pressure_offset
Pressure offset | OFF-T1. [C2].
Definition ms8607.h:16
int32_t first_order_temperature
temperature as hundredths of degree celsius in range [-4000, 8500], after first order temperature cal...
Definition ms8607.h:30
int32_t d_t
difference between actual and reference temperature
Definition ms8607.h:27
float temperature_float
actual temperature, after 2nd order temperature calculation, in degrees celsius as a float
Definition ms8607.h:32
uint16_t temperature
Definition sun_gtil2.cpp:12
uint16_t length
Definition tt21100.cpp:0
uint8_t pressure
Definition tt21100.cpp:7