ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
bme680.cpp
Go to the documentation of this file.
1#include "bme680.h"
2#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
6
7namespace esphome::bme680 {
8
9ESPHOME_LOG_TAG(TAG, "bme680.sensor");
10
11static constexpr uint32_t DATA_TIMEOUT_ID = 0;
12
13static const uint8_t BME680_REGISTER_COEFF1 = 0x89;
14static const uint8_t BME680_REGISTER_COEFF2 = 0xE1;
15
16static const uint8_t BME680_REGISTER_CONFIG = 0x75;
17static const uint8_t BME680_REGISTER_CONTROL_MEAS = 0x74;
18static const uint8_t BME680_REGISTER_CONTROL_HUMIDITY = 0x72;
19static const uint8_t BME680_REGISTER_CONTROL_GAS1 = 0x71;
20static const uint8_t BME680_REGISTER_CONTROL_GAS0 = 0x70;
21static const uint8_t BME680_REGISTER_HEATER_HEAT0 = 0x5A;
22static const uint8_t BME680_REGISTER_HEATER_WAIT0 = 0x64;
23
24static const uint8_t BME680_REGISTER_CHIPID = 0xD0;
25
26static const uint8_t BME680_REGISTER_FIELD0 = 0x1D;
27
28constexpr float BME680_GAS_LOOKUP_TABLE_1[16] PROGMEM = {0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, -0.8,
29 0.0, 0.0, -0.2, -0.5, 0.0, -1.0, 0.0, 0.0};
30
31constexpr float BME680_GAS_LOOKUP_TABLE_2[16] PROGMEM = {0.0, 0.0, 0.0, 0.0, 0.1, 0.7, 0.0, -0.8,
32 -0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
33
34// Indexed by BME680Oversampling
35PROGMEM_STRING_TABLE(OversamplingStrings, "None", "1x", "2x", "4x", "8x", "16x", "UNKNOWN");
36
37[[maybe_unused]] static const LogString *oversampling_to_str(BME680Oversampling value) {
38 return OversamplingStrings::get_log_str(static_cast<uint8_t>(value), OversamplingStrings::LAST_INDEX);
39}
40
41// Indexed by BME680IIRFilter
42PROGMEM_STRING_TABLE(IIRFilterStrings, "OFF", "1x", "3x", "7x", "15x", "31x", "63x", "127x", "UNKNOWN");
43
44[[maybe_unused]] static const LogString *iir_filter_to_str(BME680IIRFilter value) {
45 return IIRFilterStrings::get_log_str(static_cast<uint8_t>(value), IIRFilterStrings::LAST_INDEX);
46}
47
48void BME680Component::setup() {
49 if (!this->setup_registers_())
50 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
51}
52
54 uint8_t chip_id;
55 if (!this->read_byte(BME680_REGISTER_CHIPID, &chip_id) || chip_id != 0x61) {
56 return false;
57 }
58
59 // Read calibration
60 uint8_t coeff1[25];
61 if (!this->read_bytes(BME680_REGISTER_COEFF1, coeff1, 25)) {
62 return false;
63 }
64 uint8_t coeff2[16];
65 if (!this->read_bytes(BME680_REGISTER_COEFF2, coeff2, 16)) {
66 return false;
67 }
68
69 this->calibration_.t1 = encode_value_le<uint16_t>(&coeff2[8]);
70 this->calibration_.t2 = encode_value_le<int16_t>(&coeff1[1]);
71 this->calibration_.t3 = coeff1[3];
72
73 this->calibration_.h1 = coeff2[2] << 4 | (coeff2[1] & 0x0F);
74 this->calibration_.h2 = encode_uint16(coeff2[0], coeff2[1]) >> 4;
75 this->calibration_.h3 = coeff2[3];
76 this->calibration_.h4 = coeff2[4];
77 this->calibration_.h5 = coeff2[5];
78 this->calibration_.h6 = coeff2[6];
79 this->calibration_.h7 = coeff2[7];
80
81 this->calibration_.p1 = encode_value_le<uint16_t>(&coeff1[5]);
82 this->calibration_.p2 = encode_value_le<int16_t>(&coeff1[7]);
83 this->calibration_.p3 = coeff1[9];
84 this->calibration_.p4 = encode_value_le<int16_t>(&coeff1[11]);
85 this->calibration_.p5 = encode_value_le<int16_t>(&coeff1[13]);
86 this->calibration_.p6 = coeff1[16];
87 this->calibration_.p7 = coeff1[15];
88 this->calibration_.p8 = encode_value_le<int16_t>(&coeff1[19]);
89 this->calibration_.p9 = encode_value_le<int16_t>(&coeff1[21]);
90 this->calibration_.p10 = coeff1[23];
91
92 this->calibration_.gh1 = coeff2[14];
93 this->calibration_.gh2 = encode_value<int16_t>(&coeff2[12]);
94 this->calibration_.gh3 = coeff2[15];
95
96 uint8_t temp_var = 0;
97 if (!this->read_byte(0x02, &temp_var)) {
98 return false;
99 }
100 this->calibration_.res_heat_range = ((temp_var & 0x30) / 16);
101
102 if (!this->read_byte(0x00, &temp_var)) {
103 return false;
104 }
105 this->calibration_.res_heat_val = (int8_t) temp_var;
106
107 if (!this->read_byte(0x04, &temp_var)) {
108 return false;
109 }
110 this->calibration_.range_sw_err = ((int8_t) temp_var & (int8_t) 0xf0) / 16;
111
112 this->calibration_.ambient_temperature = 25; // prime ambient temperature
113
114 // Config register
115 if (!this->update_register(BME680_REGISTER_CONFIG, 0b00011100, (this->iir_filter_ & 0b111) << 2)) {
116 return false;
117 }
118
119 // Humidity control register
120 if (!this->update_register(BME680_REGISTER_CONTROL_HUMIDITY, 0b00000111, this->humidity_oversampling_ & 0b111)) {
121 return false;
122 }
123
124 // Gas 1 control register: run gas, heater profile 0
125 if (!this->update_register(BME680_REGISTER_CONTROL_GAS1, 0b00011111, 1 << 4)) {
126 return false;
127 }
128
129 const bool heat_off = this->heater_temperature_ == 0 || this->heater_duration_ == 0;
130
131 // Gas 0 control register
132 if (!this->update_register(BME680_REGISTER_CONTROL_GAS0, 0b00001000, heat_off << 3)) {
133 return false;
134 }
135
136 if (!heat_off) {
137 // Gas Heater Temperature
139 if (!this->write_byte(BME680_REGISTER_HEATER_HEAT0, temperature)) {
140 return false;
141 }
142
143 // Gas Heater Duration
144 uint8_t duration = this->calc_heater_duration_(this->heater_duration_);
145
146 if (!this->write_byte(BME680_REGISTER_HEATER_WAIT0, duration)) {
147 return false;
148 }
149 }
150 return true;
151}
152
153void BME680Component::dump_config() {
154 ESP_LOGCONFIG(TAG, "BME680:");
155 LOG_I2C_DEVICE(this);
156 ESP_LOGCONFIG(TAG, " IIR Filter: %s", LOG_STR_ARG(iir_filter_to_str(this->iir_filter_)));
157 LOG_UPDATE_INTERVAL(this);
158
159 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
160 ESP_LOGCONFIG(TAG, " Oversampling: %s", LOG_STR_ARG(oversampling_to_str(this->temperature_oversampling_)));
161 LOG_SENSOR(" ", "Pressure", this->pressure_sensor_);
162 ESP_LOGCONFIG(TAG, " Oversampling: %s", LOG_STR_ARG(oversampling_to_str(this->pressure_oversampling_)));
163 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
164 ESP_LOGCONFIG(TAG, " Oversampling: %s", LOG_STR_ARG(oversampling_to_str(this->humidity_oversampling_)));
165 LOG_SENSOR(" ", "Gas Resistance", this->gas_resistance_sensor_);
166 if (this->heater_duration_ == 0 || this->heater_temperature_ == 0) {
167 ESP_LOGCONFIG(TAG, " Heater OFF");
168 } else {
169 ESP_LOGCONFIG(TAG, " Heater temperature=%u°C duration=%ums", this->heater_temperature_, this->heater_duration_);
170 }
171}
172
173void BME680Component::update() {
174 uint8_t meas_control = 0; // No need to fetch, we're setting all fields
175 meas_control |= (this->temperature_oversampling_ & 0b111) << 5;
176 meas_control |= (this->pressure_oversampling_ & 0b111) << 2;
177 meas_control |= 0b01; // forced mode
178 if (!this->write_byte(BME680_REGISTER_CONTROL_MEAS, meas_control)) {
179 this->status_set_warning();
180 return;
181 }
182
183 this->set_timeout(DATA_TIMEOUT_ID, this->calc_meas_duration_(), [this]() { this->read_data_(); });
184}
185
187 if (temperature < 200)
188 temperature = 200;
189 if (temperature > 400)
190 temperature = 400;
191
192 const int8_t ambient_temperature = this->calibration_.ambient_temperature;
193 const int8_t gh1 = this->calibration_.gh1;
194 const int16_t gh2 = this->calibration_.gh2;
195 const int8_t gh3 = this->calibration_.gh3;
196 const uint8_t res_heat_range = this->calibration_.res_heat_range;
197 const int8_t res_heat_val = this->calibration_.res_heat_val;
198
199 uint8_t heatr_res;
200 int32_t var1;
201 int32_t var2;
202 int32_t var3;
203 int32_t var4;
204 int32_t var5;
205 int32_t heatr_res_x100;
206
207 var1 = (((int32_t) ambient_temperature * gh3) / 1000) * 256;
208 var2 = (gh1 + 784) * (((((gh2 + 154009) * temperature * 5) / 100) + 3276800) / 10);
209 var3 = var1 + (var2 / 2);
210 var4 = (var3 / (res_heat_range + 4));
211 var5 = (131 * res_heat_val) + 65536;
212 heatr_res_x100 = (int32_t) (((var4 / var5) - 250) * 34);
213 heatr_res = (uint8_t) ((heatr_res_x100 + 50) / 100);
214
215 return heatr_res;
216}
218 uint8_t factor = 0;
219 uint8_t duration_value;
220
221 if (duration >= 0xfc0) {
222 duration_value = 0xff;
223 } else {
224 while (duration > 0x3F) {
225 duration /= 4;
226 factor += 1;
227 }
228 duration_value = duration + (factor * 64);
229 }
230
231 return duration_value;
232}
234 uint8_t data[15];
235 if (!this->status_comm_result(this->read_bytes(BME680_REGISTER_FIELD0, data, 15))) {
236 PUBLISH_STATE(this->temperature_sensor_, NAN);
237 PUBLISH_STATE(this->pressure_sensor_, NAN);
238 PUBLISH_STATE(this->humidity_sensor_, NAN);
239 PUBLISH_STATE(this->gas_resistance_sensor_, NAN);
240 ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
241 return;
242 }
243
244 uint32_t raw_temperature = encode_uint24(data[5], data[6], data[7]) >> 4;
245 uint32_t raw_pressure = encode_uint24(data[2], data[3], data[4]) >> 4;
246 uint32_t raw_humidity = encode_uint16(data[8], data[9]);
247 uint16_t raw_gas = encode_uint16(data[13], data[14]) >> 6;
248 uint8_t gas_range = data[14] & 0x0F;
249
250 float temperature = this->calc_temperature_(raw_temperature);
251 float pressure = this->calc_pressure_(raw_pressure);
252 float humidity = this->calc_humidity_(raw_humidity);
253 float gas_resistance = this->calc_gas_resistance_(raw_gas, gas_range);
254
255 bool gas_valid = (data[14] >> 5) & 1;
256 bool heat_stable = (data[14] >> 4) & 1;
257 if (this->heater_temperature_ == 0 || this->heater_duration_ == 0)
258 heat_stable = true; // Allow reporting gas resistance when heater is disabled
259
260 ESP_LOGD(TAG, "Got temperature=%.1f°C pressure=%.1fhPa humidity=%.1f%% gas_resistance=%.1fΩ", temperature, pressure,
261 humidity, gas_resistance);
262 if (!gas_valid) {
263 ESP_LOGW(TAG, "Gas measurement unsuccessful, reading invalid!");
264 }
265 if (!heat_stable) {
266 ESP_LOGW(TAG, "Heater unstable, reading invalid! (Normal for a few readings after a power cycle)");
267 }
268
269 PUBLISH_STATE(this->temperature_sensor_, temperature);
270 PUBLISH_STATE(this->pressure_sensor_, pressure);
271 PUBLISH_STATE(this->humidity_sensor_, humidity);
272 if (this->gas_resistance_sensor_ != nullptr) {
273 if (gas_valid && heat_stable) {
274 this->gas_resistance_sensor_->publish_state(gas_resistance);
275 } else {
276 this->status_set_warning();
277 this->gas_resistance_sensor_->publish_state(NAN);
278 }
279 }
280}
281
283 float var1 = 0;
284 float var2 = 0;
285 float var3 = 0;
286 float calc_temp = 0;
287 float temp_adc = raw_temperature;
288
289 const float t1 = this->calibration_.t1;
290 const float t2 = this->calibration_.t2;
291 const float t3 = this->calibration_.t3;
292
293 /* calculate var1 data */
294 var1 = ((temp_adc / 16384.0f) - (t1 / 1024.0f)) * t2;
295
296 /* calculate var2 data */
297 var3 = (temp_adc / 131072.0f) - (t1 / 8192.0f);
298 var2 = var3 * var3 * t3 * 16.0f;
299
300 /* t_fine value*/
301 this->calibration_.tfine = (var1 + var2);
302
303 /* compensated temperature data*/
304 calc_temp = ((this->calibration_.tfine) / 5120.0f);
305
306 return calc_temp;
307}
309 const float tfine = this->calibration_.tfine;
310 const float p1 = this->calibration_.p1;
311 const float p2 = this->calibration_.p2;
312 const float p3 = this->calibration_.p3;
313 const float p4 = this->calibration_.p4;
314 const float p5 = this->calibration_.p5;
315 const float p6 = this->calibration_.p6;
316 const float p7 = this->calibration_.p7;
317 const float p8 = this->calibration_.p8;
318 const float p9 = this->calibration_.p9;
319 const float p10 = this->calibration_.p10;
320
321 float var1 = 0;
322 float var2 = 0;
323 float var3 = 0;
324 float var4 = 0;
325 float calc_pres = 0;
326
327 var1 = (tfine / 2.0f) - 64000.0f;
328 var2 = var1 * var1 * (p6 / 131072.0f);
329 var2 = var2 + var1 * p5 * 2.0f;
330 var2 = (var2 / 4.0f) + (p4 * 65536.0f);
331 var1 = (((p3 * var1 * var1) / 16384.0f) + (p2 * var1)) / 524288.0f;
332 var1 = (1.0f + (var1 / 32768.0f)) * p1;
333 calc_pres = 1048576.0f - float(raw_pressure);
334
335 /* Avoid exception caused by division by zero */
336 if (int(var1) != 0) {
337 calc_pres = ((calc_pres - (var2 / 4096.0f)) * 6250.0f) / var1;
338 var1 = (p9 * calc_pres * calc_pres) / 2147483648.0f;
339 var2 = calc_pres * (p8 / 32768.0f);
340 var4 = calc_pres / 256.0f;
341 var3 = var4 * var4 * var4 * (p10 / 131072.0f);
342 calc_pres = calc_pres + (var1 + var2 + var3 + (p7 * 128.0f)) / 16.0f;
343 } else {
344 calc_pres = 0;
345 }
346
347 return calc_pres / 100.0f;
348}
349
350float BME680Component::calc_humidity_(uint16_t raw_humidity) {
351 const float tfine = this->calibration_.tfine;
352 const float h1 = this->calibration_.h1;
353 const float h2 = this->calibration_.h2;
354 const float h3 = this->calibration_.h3;
355 const float h4 = this->calibration_.h4;
356 const float h5 = this->calibration_.h5;
357 const float h6 = this->calibration_.h6;
358 const float h7 = this->calibration_.h7;
359
360 float calc_hum = 0;
361 float var1 = 0;
362 float var2 = 0;
363 float var3 = 0;
364 float var4 = 0;
365 float temp_comp;
366
367 /* compensated temperature data*/
368 temp_comp = tfine / 5120.0f;
369
370 var1 = float(raw_humidity) - (h1 * 16.0f + ((h3 / 2.0f) * temp_comp));
371 var2 = var1 *
372 (((h2 / 262144.0f) * (1.0f + ((h4 / 16384.0f) * temp_comp) + ((h5 / 1048576.0f) * temp_comp * temp_comp))));
373 var3 = h6 / 16384.0f;
374 var4 = h7 / 2097152.0f;
375
376 calc_hum = var2 + (var3 + var4 * temp_comp) * var2 * var2;
377
378 if (calc_hum > 100.0f) {
379 calc_hum = 100.0f;
380 } else if (calc_hum < 0.0f) {
381 calc_hum = 0.0f;
382 }
383
384 return calc_hum;
385}
386float BME680Component::calc_gas_resistance_(uint16_t raw_gas, uint8_t range) {
387 float calc_gas_res;
388 float var1 = 0;
389 float var2 = 0;
390 float var3 = 0;
391 float raw_gas_f = raw_gas;
392 float range_f = 1U << range;
393 const float range_sw_err = this->calibration_.range_sw_err;
394
395 var1 = 1340.0f + (5.0f * range_sw_err);
396 var2 = var1 * (1.0f + BME680_GAS_LOOKUP_TABLE_1[range] / 100.0f);
397 var3 = 1.0f + (BME680_GAS_LOOKUP_TABLE_2[range] / 100.0f);
398
399 calc_gas_res = 1.0f / (var3 * 0.000000125f * range_f * (((raw_gas_f - 512.0f) / var2) + 1.0f));
400
401 return calc_gas_res;
402}
404 uint32_t tph_dur; // Calculate in us
405 uint32_t meas_cycles;
406 const uint8_t os_to_meas_cycles[6] = {0, 1, 2, 4, 8, 16};
407
408 meas_cycles = os_to_meas_cycles[this->temperature_oversampling_];
409 meas_cycles += os_to_meas_cycles[this->pressure_oversampling_];
410 meas_cycles += os_to_meas_cycles[this->humidity_oversampling_];
411
412 /* TPH measurement duration */
413 tph_dur = meas_cycles * 1963u;
414 tph_dur += 477 * 4; // TPH switching duration
415 tph_dur += 477 * 5; // Gas measurement duration
416 tph_dur += 500; // Get it to the closest whole number.
417 tph_dur /= 1000; // Convert to ms
418
419 tph_dur += 1; // Wake up duration of 1ms
420
421 /* The remaining time should be used for heating */
422 tph_dur += this->heater_duration_;
423
424 return tph_dur;
425}
426void BME680Component::set_temperature_oversampling(BME680Oversampling temperature_oversampling) {
427 this->temperature_oversampling_ = temperature_oversampling;
428}
429void BME680Component::set_pressure_oversampling(BME680Oversampling pressure_oversampling) {
430 this->pressure_oversampling_ = pressure_oversampling;
431}
432void BME680Component::set_humidity_oversampling(BME680Oversampling humidity_oversampling) {
433 this->humidity_oversampling_ = humidity_oversampling;
434}
435void BME680Component::set_heater(uint16_t heater_temperature, uint16_t heater_duration) {
436 this->heater_temperature_ = heater_temperature;
437 this->heater_duration_ = heater_duration;
438}
439
440} // namespace esphome::bme680
void mark_failed()
Mark this component as failed.
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
uint8_t calc_heater_duration_(uint16_t duration)
Calculate the heater duration value to send to the BME680 register.
Definition bme680.cpp:217
void read_data_()
Read data from the BME680 and publish results.
Definition bme680.cpp:233
uint8_t calc_heater_resistance_(uint16_t temperature)
Calculate the heater resistance value to send to the BME680 register.
Definition bme680.cpp:186
float calc_humidity_(uint16_t raw_humidity)
Calculate the relative humidity in % using the provided raw ADC value.
Definition bme680.cpp:350
BME680Oversampling pressure_oversampling_
Definition bme680.h:124
bool setup_registers_()
Configure the sensor registers; false on an I2C failure.
Definition bme680.cpp:53
BME680CalibrationData calibration_
Definition bme680.h:122
BME680Oversampling temperature_oversampling_
Definition bme680.h:123
BME680Oversampling humidity_oversampling_
Definition bme680.h:125
float calc_gas_resistance_(uint16_t raw_gas, uint8_t range)
Calculate the gas resistance in Ω using the provided raw ADC value.
Definition bme680.cpp:386
uint32_t calc_meas_duration_()
Calculate how long the sensor will take until we can retrieve data.
Definition bme680.cpp:403
float calc_temperature_(uint32_t raw_temperature)
Calculate the temperature in °C using the provided raw ADC value.
Definition bme680.cpp:282
float calc_pressure_(uint32_t raw_pressure)
Calculate the pressure in hPa using the provided raw ADC value.
Definition bme680.cpp:308
BME680IIRFilter iir_filter_
Definition bme680.h:126
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:312
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:272
bool update_register(uint8_t a_register, uint8_t mask, uint8_t value)
Read a register, replace the bits in mask with those of value and write it back.
Definition i2c.cpp:95
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
Range range
Definition msa3xx.h:0
uint8_t duration
Definition msa3xx.h:0
PROGMEM_STRING_TABLE(OversamplingStrings, "None", "1x", "2x", "4x", "8x", "16x", "UNKNOWN")
BME680IIRFilter
Enum listing all IIR Filter options for the BME680.
Definition bme680.h:10
constexpr float BME680_GAS_LOOKUP_TABLE_1[16] PROGMEM
Definition bme680.cpp:28
BME680Oversampling
Enum listing all oversampling options for the BME680.
Definition bme680.h:22
ESPHOME_LOG_TAG(TAG, "bme680.sensor")
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
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
Definition helpers.h:1084
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:1064
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
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12
uint8_t pressure
Definition tt21100.cpp:7