ESPHome 2026.5.0b1
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::ms8607 {
8
10static const char *const TAG = "ms8607";
11
13static const uint8_t MS8607_PT_CMD_RESET = 0x1E;
14
17static const uint8_t MS8607_PROM_START = 0xA0;
19static const uint8_t MS8607_PROM_END = 0xAE;
21static const uint8_t MS8607_PROM_COUNT = (MS8607_PROM_END - MS8607_PROM_START) >> 1;
22
24static const uint8_t MS8607_CMD_H_RESET = 0xFE;
26static const uint8_t MS8607_CMD_H_MEASURE_NO_HOLD = 0xF5;
28static const float MS8607_H_TEMP_COEFFICIENT = -0.18;
29
31static const uint8_t MS8607_CMD_ADC_READ = 0x00;
32
33// TODO: allow OSR to be turned down for speed and/or lower power consumption via configuration.
34// ms8607 supports 6 different settings
35
37static const uint8_t MS8607_CMD_CONV_D1_OSR_8K = 0x4A;
39static const uint8_t MS8607_CMD_CONV_D2_OSR_8K = 0x5A;
40
43 NONE = 0,
45 PTH_RESET_FAILED = 1,
47 PT_RESET_FAILED = 2,
49 H_RESET_FAILED = 3,
51 PROM_READ_FAILED = 4,
53 PROM_CRC_FAILED = 5,
54};
55
58 NEEDS_RESET,
60 NEEDS_PROM_READ,
62 SUCCESSFUL,
63};
64
65static uint8_t crc4(uint16_t *buffer, size_t length);
66
70
71 // I do not know why the device sometimes NACKs the reset command, but
72 // try 3 times in case it's a transitory issue on this boot
73 // Backoff: executes at now, +5ms, +30ms
75 this->reset_interval_ = 5;
76 this->try_reset_();
77}
78
80 ESP_LOGD(TAG, "Resetting both I2C addresses: 0x%02X, 0x%02X", this->address_, this->humidity_device_->get_address());
81 // I believe sending the reset command to both addresses is preferable to
82 // skipping humidity if PT fails for some reason.
83 // However, only consider the reset successful if they both ACK
84 bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
85 bool const h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
86
87 if (!(pt_successful && h_successful)) {
88 ESP_LOGE(TAG, "Resetting I2C devices failed");
89 if (!pt_successful && !h_successful) {
91 } else if (!pt_successful) {
93 } else {
95 }
96
97 if (--this->reset_attempts_remaining_ > 0) {
99 this->reset_interval_ *= 5;
100 this->set_timeout("reset", delay, [this]() { this->try_reset_(); });
101 this->status_set_error();
102 } else {
103 this->mark_failed();
104 }
105 return;
106 }
107
110 this->status_clear_error();
111
112 // 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
113 this->set_timeout("prom-read", 15, [this]() {
116 this->status_clear_error();
117 } else {
118 this->mark_failed();
119 return;
120 }
121 });
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
247 // Tell MS8607 to start ADC conversion of temperature sensor
248 if (!this->write_bytes(MS8607_CMD_CONV_D2_OSR_8K, nullptr, 0)) {
249 this->status_set_warning();
250 return;
251 }
252
253 // datasheet says 17.2ms max conversion time at OSR 8192
254 this->set_timeout("temperature", 20, [this]() { this->read_temperature_(); });
255}
256
258 uint8_t bytes[3]; // 24 bits
259 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
260 this->status_set_warning();
261 return;
262 }
263
264 const uint32_t d2_raw_temperature = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
265 this->request_read_pressure_(d2_raw_temperature);
266}
267
269 if (!this->write_bytes(MS8607_CMD_CONV_D1_OSR_8K, nullptr, 0)) {
270 this->status_set_warning();
271 return;
272 }
273
274 // datasheet says 17.2ms max conversion time at OSR 8192
275 this->set_timeout("pressure", 20, [this, d2_raw_temperature]() { this->read_pressure_(d2_raw_temperature); });
276}
277
279 uint8_t bytes[3]; // 24 bits
280 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
281 this->status_set_warning();
282 return;
283 }
284 const uint32_t d1_raw_pressure = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
285 this->calculate_values_(d2_raw_temperature, d1_raw_pressure);
286}
287
288void MS8607Component::request_read_humidity_(float temperature_float) {
289 if (!this->humidity_device_->write_bytes(MS8607_CMD_H_MEASURE_NO_HOLD, nullptr, 0)) {
290 ESP_LOGW(TAG, "Request to measure humidity failed");
291 this->status_set_warning();
292 return;
293 }
294
295 // datasheet says 15.89ms max conversion time at OSR 8192
296 this->set_timeout("humidity", 20, [this, temperature_float]() { this->read_humidity_(temperature_float); });
297}
298
299void MS8607Component::read_humidity_(float temperature_float) {
300 uint8_t bytes[3];
301 if (!this->humidity_device_->read_bytes_raw(bytes, 3)) {
302 ESP_LOGW(TAG, "Failed to read the measured humidity value");
303 this->status_set_warning();
304 return;
305 }
306
307 // "the measurement is stored into 14 bits. The two remaining LSBs are used for transmitting status information.
308 // Bit1 of the two LSBS must be set to '1'. Bit0 is currently not assigned"
309 uint16_t humidity = encode_uint16(bytes[0], bytes[1]);
310 uint8_t const expected_crc = bytes[2];
311 uint8_t const actual_crc = crc8(bytes, 2, 0, 0x31, true);
312 if (expected_crc != actual_crc) {
313 ESP_LOGE(TAG, "Incorrect Humidity CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc,
314 actual_crc);
315 this->status_set_warning();
316 return;
317 }
318 if (!(humidity & 0x2)) {
319 // data sheet says Bit1 should always set, but nothing about what happens if it isn't
320 ESP_LOGE(TAG, "Humidity status bit was not set to 1?");
321 }
322 humidity &= ~(0b11); // strip status & unassigned bits from data
323
324 // map 16 bit humidity value into range [-6%, 118%]
325 float const humidity_partial = double(humidity) / (1 << 16);
326 float const humidity_percentage = std::lerp(-6.0, 118.0, humidity_partial);
327 float const compensated_humidity_percentage =
328 humidity_percentage + (20 - temperature_float) * MS8607_H_TEMP_COEFFICIENT;
329 ESP_LOGD(TAG, "Compensated for temperature, humidity=%.2f%%", compensated_humidity_percentage);
330
331 if (this->humidity_sensor_ != nullptr) {
332 this->humidity_sensor_->publish_state(compensated_humidity_percentage);
333 }
334 this->status_clear_warning();
335}
336
337void MS8607Component::calculate_values_(uint32_t d2_raw_temperature, uint32_t d1_raw_pressure) {
338 // Perform the first order pressure/temperature calculation
339
340 // d_t: "difference between actual and reference temperature" = D2 - [C5] * 2**8
341 const int32_t d_t = int32_t(d2_raw_temperature) - (int32_t(this->calibration_values_.reference_temperature) << 8);
342 // actual temperature as hundredths of degree celsius in range [-4000, 8500]
343 // 2000 + d_t * [C6] / (2**23)
344 int32_t temperature =
345 2000 + ((int64_t(d_t) * this->calibration_values_.temperature_coefficient_of_temperature) >> 23);
346
347 // offset at actual temperature. [C2] * (2**17) + (d_t * [C4] / (2**6))
348 int64_t pressure_offset = (int64_t(this->calibration_values_.pressure_offset) << 17) +
350 // sensitivity at actual temperature. [C1] * (2**16) + ([C3] * d_t) / (2**7)
351 int64_t pressure_sensitivity =
352 (int64_t(this->calibration_values_.pressure_sensitivity) << 16) +
354
355 // Perform the second order compensation, for non-linearity over temperature range
356 const int64_t d_t_squared = int64_t(d_t) * d_t;
357 int64_t temperature_2 = 0;
358 int32_t pressure_offset_2 = 0;
359 int32_t pressure_sensitivity_2 = 0;
360 if (temperature < 2000) {
361 // (TEMP - 2000)**2 / 2**4
362 const int32_t low_temperature_adjustment = (temperature - 2000) * (temperature - 2000) >> 4;
363
364 // T2 = 3 * (d_t**2) / 2**33
365 temperature_2 = (3 * d_t_squared) >> 33;
366 // OFF2 = 61 * (TEMP-2000)**2 / 2**4
367 pressure_offset_2 = 61 * low_temperature_adjustment;
368 // SENS2 = 29 * (TEMP-2000)**2 / 2**4
369 pressure_sensitivity_2 = 29 * low_temperature_adjustment;
370
371 if (temperature < -1500) {
372 // (TEMP+1500)**2
373 const int32_t very_low_temperature_adjustment = (temperature + 1500) * (temperature + 1500);
374
375 // OFF2 = OFF2 + 17 * (TEMP+1500)**2
376 pressure_offset_2 += 17 * very_low_temperature_adjustment;
377 // SENS2 = SENS2 + 9 * (TEMP+1500)**2
378 pressure_sensitivity_2 += 9 * very_low_temperature_adjustment;
379 }
380 } else {
381 // T2 = 5 * (d_t**2) / 2**38
382 temperature_2 = (5 * d_t_squared) >> 38;
383 }
384
385 temperature -= temperature_2;
386 pressure_offset -= pressure_offset_2;
387 pressure_sensitivity -= pressure_sensitivity_2;
388
389 // Temperature compensated pressure. [1000, 120000] => [10.00 mbar, 1200.00 mbar]
390 const int32_t pressure = (((d1_raw_pressure * pressure_sensitivity) >> 21) - pressure_offset) >> 15;
391
392 const float temperature_float = temperature / 100.0f;
393 const float pressure_float = pressure / 100.0f;
394 ESP_LOGD(TAG, "Temperature=%0.2f°C, Pressure=%0.2fhPa", temperature_float, pressure_float);
395
396 if (this->temperature_sensor_ != nullptr) {
397 this->temperature_sensor_->publish_state(temperature_float);
398 }
399 if (this->pressure_sensor_ != nullptr) {
400 this->pressure_sensor_->publish_state(pressure_float); // hPa aka mbar
401 }
402 this->status_clear_warning();
403
404 if (this->humidity_sensor_ != nullptr) {
405 // now that we have temperature (to compensate the humidity with), kick off that read
406 this->request_read_humidity_(temperature_float);
407 }
408}
409
410} // namespace esphome::ms8607
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:284
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:510
void status_clear_error()
Definition component.h:312
void status_clear_warning()
Definition component.h:306
bool read_bytes_raw(uint8_t *data, uint8_t len) const
Definition i2c.h:221
uint8_t address_
store the address of the device on the bus
Definition i2c.h:270
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:249
bool write_bytes(uint8_t a_register, const uint8_t *data, uint8_t len) const
Definition i2c.h:251
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:217
void read_humidity_(float temperature_float)
process async humidity read
Definition ms8607.cpp:299
void request_read_temperature_()
Start async temperature read.
Definition ms8607.cpp:246
@ 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:79
sensor::Sensor * temperature_sensor_
Definition ms8607.h:69
sensor::Sensor * humidity_sensor_
Definition ms8607.h:71
SetupStatus setup_status_
Current step in the multi-step & possibly delayed setup() process.
Definition ms8607.h:105
void calculate_values_(uint32_t raw_temperature, uint32_t raw_pressure)
use raw temperature & pressure to calculate & publish values
Definition ms8607.cpp:337
void read_pressure_(uint32_t raw_temperature)
process async pressure read
Definition ms8607.cpp:278
ErrorCode error_code_
Keep track of the reason why this component failed, to augment the dumped config.
Definition ms8607.h:100
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:268
sensor::Sensor * pressure_sensor_
Definition ms8607.h:70
@ 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 try_reset_()
Attempt to reset both I2C devices, retrying with backoff on failure.
Definition ms8607.cpp:79
void read_temperature_()
Process async temperature read.
Definition ms8607.cpp:257
void request_read_humidity_(float temperature_float)
start async humidity read
Definition ms8607.cpp:288
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
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:867
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:59
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:859
void HOT delay(uint32_t ms)
Definition hal.cpp:82
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:888
static void uint32_t
uint16_t pressure_offset_temperature_coefficient
Temperature coefficient of pressure offset | TCO. [C4].
Definition ms8607.h:90
uint16_t temperature_coefficient_of_temperature
Temperature coefficient of the temperature | TEMPSENS. [C6].
Definition ms8607.h:94
uint16_t pressure_sensitivity_temperature_coefficient
Temperature coefficient of pressure sensitivity | TCS. [C3].
Definition ms8607.h:86
uint16_t pressure_sensitivity
Pressure sensitivity | SENS-T1. [C1].
Definition ms8607.h:84
uint16_t pressure_offset
Pressure offset | OFF-T1. [C2].
Definition ms8607.h:88
uint16_t reference_temperature
Reference temperature | T-REF. [C5].
Definition ms8607.h:92
uint16_t temperature
Definition sun_gtil2.cpp:12
uint16_t length
Definition tt21100.cpp:0
uint8_t pressure
Definition tt21100.cpp:7