ESPHome 2026.11.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::ms8607 {
8
10ESPHOME_LOG_TAG(TAG, "ms8607");
11
12static constexpr uint32_t RESET_TIMEOUT_ID = 0;
13static constexpr uint32_t PROM_READ_TIMEOUT_ID = 1;
14static constexpr uint32_t TEMPERATURE_TIMEOUT_ID = 2;
15static constexpr uint32_t PRESSURE_TIMEOUT_ID = 3;
16static constexpr uint32_t HUMIDITY_TIMEOUT_ID = 4;
17
19static const uint8_t MS8607_PT_CMD_RESET = 0x1E;
20
23static const uint8_t MS8607_PROM_START = 0xA0;
25static const uint8_t MS8607_PROM_END = 0xAE;
27static const uint8_t MS8607_PROM_COUNT = (MS8607_PROM_END - MS8607_PROM_START) >> 1;
28
30static const uint8_t MS8607_CMD_H_RESET = 0xFE;
32static const uint8_t MS8607_CMD_H_MEASURE_NO_HOLD = 0xF5;
34static const float MS8607_H_TEMP_COEFFICIENT = -0.18;
35
37static const uint8_t MS8607_CMD_ADC_READ = 0x00;
38
39// TODO: allow OSR to be turned down for speed and/or lower power consumption via configuration.
40// ms8607 supports 6 different settings
41
43static const uint8_t MS8607_CMD_CONV_D1_OSR_8K = 0x4A;
45static const uint8_t MS8607_CMD_CONV_D2_OSR_8K = 0x5A;
46
49 NONE = 0,
51 PTH_RESET_FAILED = 1,
53 PT_RESET_FAILED = 2,
55 H_RESET_FAILED = 3,
57 PROM_READ_FAILED = 4,
59 PROM_CRC_FAILED = 5,
60};
61
64 NEEDS_RESET,
66 NEEDS_PROM_READ,
68 SUCCESSFUL,
69};
70
71static uint8_t crc4(uint16_t *buffer, size_t length);
72
76
77 // I do not know why the device sometimes NACKs the reset command, but
78 // try 3 times in case it's a transitory issue on this boot
79 // Backoff: executes at now, +5ms, +30ms
81 this->reset_interval_ = 5;
82 this->try_reset_();
83}
84
86 ESP_LOGD(TAG, "Resetting both I2C addresses: 0x%02X, 0x%02X", this->address_, this->humidity_device_->get_address());
87 // I believe sending the reset command to both addresses is preferable to
88 // skipping humidity if PT fails for some reason.
89 // However, only consider the reset successful if they both ACK
90 bool const pt_successful = this->write_bytes(MS8607_PT_CMD_RESET, nullptr, 0);
91 bool const h_successful = this->humidity_device_->write_bytes(MS8607_CMD_H_RESET, nullptr, 0);
92
93 if (!(pt_successful && h_successful)) {
94 ESP_LOGE(TAG, "Resetting I2C devices failed");
95 if (!pt_successful && !h_successful) {
97 } else if (!pt_successful) {
99 } else {
101 }
102
103 if (--this->reset_attempts_remaining_ > 0) {
105 this->reset_interval_ *= 5;
106 this->set_timeout(RESET_TIMEOUT_ID, delay, [this]() { this->try_reset_(); });
107 this->status_set_error();
108 } else {
109 this->mark_failed();
110 }
111 return;
112 }
113
116 this->status_clear_error();
117
118 // 15ms delay matches datasheet, Adafruit_MS8607 & SparkFun_PHT_MS8607_Arduino_Library
119 this->set_timeout(PROM_READ_TIMEOUT_ID, 15, [this]() {
122 this->status_clear_error();
123 } else {
124 this->mark_failed();
125 return;
126 }
127 });
128}
129
132 // setup is still occurring, either because reset had to retry or due to the 15ms
133 // delay needed between reset & reading the PROM values
134 return;
135 }
136
137 // Updating happens async and sequentially.
138 // Temperature, then pressure, then humidity
140}
141
143 ESP_LOGCONFIG(TAG, "MS8607:");
144 LOG_I2C_DEVICE(this);
145 // LOG_I2C_DEVICE doesn't work for humidity, the `address_` is protected. Log using get_address()
146 ESP_LOGCONFIG(TAG, " Address: 0x%02X", this->humidity_device_->get_address());
147 if (this->is_failed()) {
148 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
149 switch (this->error_code_) {
151 ESP_LOGE(TAG, "Temperature/Pressure RESET failed");
152 break;
154 ESP_LOGE(TAG, "Humidity RESET failed");
155 break;
157 ESP_LOGE(TAG, "Temperature/Pressure && Humidity RESET failed");
158 break;
160 ESP_LOGE(TAG, "Reading PROM failed");
161 break;
163 ESP_LOGE(TAG, "PROM values failed CRC");
164 break;
165 case ErrorCode::NONE:
166 default:
167 ESP_LOGE(TAG, "Error reason unknown %u", static_cast<uint8_t>(this->error_code_));
168 break;
169 }
170 }
171 LOG_UPDATE_INTERVAL(this);
172 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
173 LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
174 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
175}
176
178 ESP_LOGD(TAG, "Reading calibration values from PROM");
179
180 uint16_t buffer[MS8607_PROM_COUNT];
181 bool successful = true;
182
183 for (uint8_t idx = 0; idx < MS8607_PROM_COUNT; ++idx) {
184 uint8_t const address_to_read = MS8607_PROM_START + (idx * 2);
185 successful &= this->read_byte_16(address_to_read, &buffer[idx]);
186 }
187
188 if (!successful) {
189 ESP_LOGE(TAG, "Reading calibration values from PROM failed");
191 return false;
192 }
193
194 ESP_LOGD(TAG, "Checking CRC of calibration values from PROM");
195 uint8_t const expected_crc = (buffer[0] & 0xF000) >> 12; // first 4 bits
196 buffer[0] &= 0x0FFF; // strip CRC from buffer, in order to run CRC
197 uint8_t const actual_crc = crc4(buffer, MS8607_PROM_COUNT);
198
199 if (expected_crc != actual_crc) {
200 ESP_LOGE(TAG, "Incorrect CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc, actual_crc);
202 return false;
203 }
204
206 this->calibration_values_.pressure_offset = buffer[2];
211 ESP_LOGD(TAG, "Finished reading calibration values");
212
213 // Skipping reading Humidity PROM, since it doesn't have anything interesting for us
214
215 return true;
216}
217
224static uint8_t crc4(uint16_t *buffer, size_t length) {
225 uint16_t crc_remainder = 0;
226
227 // algorithm to add a byte into the crc
228 auto apply_crc = [&crc_remainder](uint8_t next) {
229 crc_remainder ^= next;
230 for (uint8_t bit = 8; bit > 0; --bit) {
231 if (crc_remainder & 0x8000) {
232 crc_remainder = (crc_remainder << 1) ^ 0x3000;
233 } else {
234 crc_remainder = (crc_remainder << 1);
235 }
236 }
237 };
238
239 // add all the bytes
240 for (size_t idx = 0; idx < length; ++idx) {
241 for (auto byte : decode_value(buffer[idx])) {
242 apply_crc(byte);
243 }
244 }
245 // For the MS8607 CRC, add a pair of zeros to shift the last byte from `buffer` through
246 apply_crc(0);
247 apply_crc(0);
248
249 return (crc_remainder >> 12) & 0xF; // only the most significant 4 bits
250}
251
253 // Tell MS8607 to start ADC conversion of temperature sensor
254 if (!this->write_bytes(MS8607_CMD_CONV_D2_OSR_8K, nullptr, 0)) {
255 this->status_set_warning();
256 return;
257 }
258
259 // datasheet says 17.2ms max conversion time at OSR 8192
260 this->set_timeout(TEMPERATURE_TIMEOUT_ID, 20, [this]() { this->read_temperature_(); });
261}
262
264 uint8_t bytes[3]; // 24 bits
265 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
266 this->status_set_warning();
267 return;
268 }
269
270 const uint32_t d2_raw_temperature = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
271 this->request_read_pressure_(d2_raw_temperature);
272}
273
275 if (!this->write_bytes(MS8607_CMD_CONV_D1_OSR_8K, nullptr, 0)) {
276 this->status_set_warning();
277 return;
278 }
279
280 // datasheet says 17.2ms max conversion time at OSR 8192
281 this->set_timeout(PRESSURE_TIMEOUT_ID, 20,
282 [this, d2_raw_temperature]() { this->read_pressure_(d2_raw_temperature); });
283}
284
286 uint8_t bytes[3]; // 24 bits
287 if (!this->read_bytes(MS8607_CMD_ADC_READ, bytes, 3)) {
288 this->status_set_warning();
289 return;
290 }
291 const uint32_t d1_raw_pressure = encode_uint32(0, bytes[0], bytes[1], bytes[2]);
292 this->calculate_values_(d2_raw_temperature, d1_raw_pressure);
293}
294
295void MS8607Component::request_read_humidity_(float temperature_float) {
296 if (!this->humidity_device_->write_bytes(MS8607_CMD_H_MEASURE_NO_HOLD, nullptr, 0)) {
297 ESP_LOGW(TAG, "Request to measure humidity failed");
298 this->status_set_warning();
299 return;
300 }
301
302 // datasheet says 15.89ms max conversion time at OSR 8192
303 this->set_timeout(HUMIDITY_TIMEOUT_ID, 20, [this, temperature_float]() { this->read_humidity_(temperature_float); });
304}
305
306void MS8607Component::read_humidity_(float temperature_float) {
307 uint8_t bytes[3];
308 if (!this->humidity_device_->read_bytes_raw(bytes, 3)) {
309 ESP_LOGW(TAG, "Failed to read the measured humidity value");
310 this->status_set_warning();
311 return;
312 }
313
314 // "the measurement is stored into 14 bits. The two remaining LSBs are used for transmitting status information.
315 // Bit1 of the two LSBS must be set to '1'. Bit0 is currently not assigned"
316 uint16_t humidity = encode_uint16(bytes[0], bytes[1]);
317 uint8_t const expected_crc = bytes[2];
318 uint8_t const actual_crc = crc8(bytes, 2, 0, 0x31, true);
319 if (expected_crc != actual_crc) {
320 ESP_LOGE(TAG, "Incorrect Humidity CRC value. Provided value 0x%01X != calculated value 0x%01X", expected_crc,
321 actual_crc);
322 this->status_set_warning();
323 return;
324 }
325 if (!(humidity & 0x2)) {
326 // data sheet says Bit1 should always set, but nothing about what happens if it isn't
327 ESP_LOGE(TAG, "Humidity status bit was not set to 1?");
328 }
329 humidity &= ~(0b11); // strip status & unassigned bits from data
330
331 // map 16 bit humidity value into range [-6%, 118%]
332 float const humidity_partial = float(humidity) / (1 << 16);
333 float const humidity_percentage = std::lerp(-6.0f, 118.0f, humidity_partial);
334 float const compensated_humidity_percentage =
335 humidity_percentage + (20 - temperature_float) * MS8607_H_TEMP_COEFFICIENT;
336 ESP_LOGD(TAG, "Compensated for temperature, humidity=%.2f%%", compensated_humidity_percentage);
337
338 if (this->humidity_sensor_ != nullptr) {
339 this->humidity_sensor_->publish_state(compensated_humidity_percentage);
340 }
341 this->status_clear_warning();
342}
343
344void MS8607Component::calculate_values_(uint32_t d2_raw_temperature, uint32_t d1_raw_pressure) {
345 // Perform the first order pressure/temperature calculation
346
347 // d_t: "difference between actual and reference temperature" = D2 - [C5] * 2**8
348 const int32_t d_t = int32_t(d2_raw_temperature) - (int32_t(this->calibration_values_.reference_temperature) << 8);
349 // actual temperature as hundredths of degree celsius in range [-4000, 8500]
350 // 2000 + d_t * [C6] / (2**23)
351 int32_t temperature =
352 2000 + ((int64_t(d_t) * this->calibration_values_.temperature_coefficient_of_temperature) >> 23);
353
354 // offset at actual temperature. [C2] * (2**17) + (d_t * [C4] / (2**6))
355 int64_t pressure_offset = (int64_t(this->calibration_values_.pressure_offset) << 17) +
357 // sensitivity at actual temperature. [C1] * (2**16) + ([C3] * d_t) / (2**7)
358 int64_t pressure_sensitivity =
359 (int64_t(this->calibration_values_.pressure_sensitivity) << 16) +
361
362 // Perform the second order compensation, for non-linearity over temperature range
363 const int64_t d_t_squared = int64_t(d_t) * d_t;
364 int64_t temperature_2 = 0;
365 int32_t pressure_offset_2 = 0;
366 int32_t pressure_sensitivity_2 = 0;
367 if (temperature < 2000) {
368 // (TEMP - 2000)**2 / 2**4
369 const int32_t low_temperature_adjustment = (temperature - 2000) * (temperature - 2000) >> 4;
370
371 // T2 = 3 * (d_t**2) / 2**33
372 temperature_2 = (3 * d_t_squared) >> 33;
373 // OFF2 = 61 * (TEMP-2000)**2 / 2**4
374 pressure_offset_2 = 61 * low_temperature_adjustment;
375 // SENS2 = 29 * (TEMP-2000)**2 / 2**4
376 pressure_sensitivity_2 = 29 * low_temperature_adjustment;
377
378 if (temperature < -1500) {
379 // (TEMP+1500)**2
380 const int32_t very_low_temperature_adjustment = (temperature + 1500) * (temperature + 1500);
381
382 // OFF2 = OFF2 + 17 * (TEMP+1500)**2
383 pressure_offset_2 += 17 * very_low_temperature_adjustment;
384 // SENS2 = SENS2 + 9 * (TEMP+1500)**2
385 pressure_sensitivity_2 += 9 * very_low_temperature_adjustment;
386 }
387 } else {
388 // T2 = 5 * (d_t**2) / 2**38
389 temperature_2 = (5 * d_t_squared) >> 38;
390 }
391
392 temperature -= temperature_2;
393 pressure_offset -= pressure_offset_2;
394 pressure_sensitivity -= pressure_sensitivity_2;
395
396 // Temperature compensated pressure. [1000, 120000] => [10.00 mbar, 1200.00 mbar]
397 const int32_t pressure = (((d1_raw_pressure * pressure_sensitivity) >> 21) - pressure_offset) >> 15;
398
399 const float temperature_float = temperature / 100.0f;
400 const float pressure_float = pressure / 100.0f;
401 ESP_LOGD(TAG, "Temperature=%0.2f°C, Pressure=%0.2fhPa", temperature_float, pressure_float);
402
403 if (this->temperature_sensor_ != nullptr) {
404 this->temperature_sensor_->publish_state(temperature_float);
405 }
406 if (this->pressure_sensor_ != nullptr) {
407 this->pressure_sensor_->publish_state(pressure_float); // hPa aka mbar
408 }
409 this->status_clear_warning();
410
411 if (this->humidity_sensor_ != nullptr) {
412 // now that we have temperature (to compensate the humidity with), kick off that read
413 this->request_read_humidity_(temperature_float);
414 }
415}
416
417} // namespace esphome::ms8607
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:274
void status_clear_error()
Definition component.h:302
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
void status_clear_warning()
Definition component.h:296
bool read_bytes_raw(uint8_t *data, uint8_t len) const
Definition i2c.h:253
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 read_humidity_(float temperature_float)
process async humidity read
Definition ms8607.cpp:306
void request_read_temperature_()
Start async temperature read.
Definition ms8607.cpp:252
@ 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:344
void read_pressure_(uint32_t raw_temperature)
process async pressure read
Definition ms8607.cpp:285
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:177
void request_read_pressure_(uint32_t raw_temperature)
start async pressure read
Definition ms8607.cpp:274
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:85
void read_temperature_()
Process async temperature read.
Definition ms8607.cpp:263
void request_read_humidity_(float temperature_float)
start async humidity read
Definition ms8607.cpp:295
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
NameCopy * next
uint32_t buffer
Definition gif.cpp:50
ESPHOME_LOG_TAG(TAG, "ms8607")
TAG used for logging calls.
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:1006
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:998
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:1056
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