Skip to main content

edrv_bme680/
lib.rs

1//! Driver for the BME680 temperature, humidity, pressure and gas sensor.
2//!
3//! The compensation maths follows Bosch Sensortec's official BME68x SensorAPI
4//! (`bme68x.c`, BSD-3-Clause), which is also the reference for the register map.
5//! The sensor's own state machine is deliberately not reproduced: this driver
6//! exposes a small, idiomatic `embedded-hal` API instead. Raw register access is
7//! available through [`BME680::read_reg`], [`BME680::read_regs`] and
8//! [`BME680::write_reg`] for anything the high-level API does not cover.
9//!
10//! Only the **BME680** (Bosch `BME68X_VARIANT_GAS_LOW`) gas path is implemented.
11//! The integer ("no FPU") Bosch compensation is used, so the driver itself does
12//! no floating point work; the `f32` accessors on [`Measurements`] perform a
13//! single final conversion. The BME688 shares the die and answers the same chip
14//! ID (`0x61`), but uses the `BME68X_VARIANT_GAS_HIGH` gas-resistance formula,
15//! so [`BME680::variant_id`] is exposed and gas readings on a BME688 should be
16//! treated as invalid.
17//!
18//! This module contains the asynchronous driver. See [`blocking`] for the
19//! blocking variant.
20//!
21//! # Licence
22//!
23//! This crate is distributed under `MIT OR Apache-2.0`, but it derives from
24//! Bosch's BSD-3-Clause BME68x SensorAPI. The retained upstream notice is in
25//! `LICENSE-BOSCH`.
26
27#![cfg_attr(not(test), no_std)]
28
29use embedded_hal_async::delay::DelayNs;
30
31pub mod blocking;
32
33/// Default 7-bit I2C address, selected when SDO is tied low.
34pub const ADDRESS: u8 = 0x76;
35/// Alternative 7-bit I2C address, selected when SDO is tied high.
36pub const ADDRESS_ALT: u8 = 0x77;
37
38/// Value expected in the chip ID register (`0xD0`).
39pub const CHIP_ID: u8 = 0x61;
40
41/// Ambient temperature, in degrees Celsius, used to compute the heater
42/// resistance. Bosch's `calc_res_heat` is the only compensation step that needs
43/// an ambient temperature; 25 C is used by default because the BME680 cannot
44/// measure it before the first conversion. Override
45/// [`BME680::ambient_temperature_celsius`] if the board runs hot or cold.
46pub const DEFAULT_AMBIENT_CELSIUS: i8 = 25;
47
48/// Default gas heater target, in degrees Celsius. This is Bosch's recommended
49/// set point for the BME680.
50pub const DEFAULT_HEATER_TARGET_CELSIUS: u16 = 320;
51
52/// Default gas heater duration, in milliseconds. This is Bosch's recommended
53/// duration for the BME680.
54pub const DEFAULT_HEATER_DURATION_MS: u16 = 150;
55
56/// BME680 register addresses and register fields.
57pub mod regs {
58    /// `res_heat_val`: heater resistance correction, start of calibration block 3.
59    pub const RES_HEAT_VAL: u8 = 0x00;
60    /// `res_heat_range`: heater resistance range, start of the calibration block
61    /// read that also covers [`RES_HEAT_VAL`].
62    pub const RES_HEAT_RANGE: u8 = 0x02;
63    /// `range_sw_err`: gas range switching error.
64    pub const RANGE_SW_ERR: u8 = 0x04;
65
66    /// `field0`: start of the 17-byte measurement field.
67    pub const FIELD0: u8 = 0x1D;
68    /// `field0` bit 7: a new measurement is ready.
69    pub const FIELD_NEW_DATA: u8 = 0x80;
70    /// `field14` bit 5: the gas measurement is valid (`gasm_valid`).
71    pub const FIELD_GAS_VALID: u8 = 0x20;
72    /// `field14` bit 4: the heater reached its set point (`heat_stab`).
73    pub const FIELD_HEAT_STABLE: u8 = 0x10;
74    /// `field14` bits 3:0: gas range index.
75    pub const FIELD_GAS_RANGE: u8 = 0x0F;
76
77    /// `res_heat0`: heater resistance for gas profile 0.
78    pub const RES_HEAT0: u8 = 0x5A;
79    /// `gas_wait0`: heater duration for gas profile 0.
80    pub const GAS_WAIT0: u8 = 0x64;
81
82    /// `ctrl_gas_0`: heater on/off, bit 3.
83    pub const CTRL_GAS_0: u8 = 0x70;
84    /// `ctrl_gas_1`: `run_gas` (bit 4) and `nb_conv` (bits 3:0).
85    pub const CTRL_GAS_1: u8 = 0x71;
86    /// `ctrl_hum`: humidity oversampling, bits 2:0.
87    pub const CTRL_HUM: u8 = 0x72;
88    /// `ctrl_meas`: temperature/pressure oversampling and power mode.
89    pub const CTRL_MEAS: u8 = 0x74;
90    /// `config`: IIR filter (bits 4:2) and SPI mode.
91    pub const CONFIG: u8 = 0x75;
92
93    /// Start of calibration block 1 (`0x8A..=0xA0`).
94    pub const COEFF1: u8 = 0x8A;
95    /// `chip_id`: chip identification register.
96    pub const CHIP_ID: u8 = 0xD0;
97    /// `reset`: write `0xB6` to trigger a soft reset.
98    pub const SOFT_RESET: u8 = 0xE0;
99    /// Start of calibration block 2 (`0xE1..=0xEE`).
100    pub const COEFF2: u8 = 0xE1;
101    /// `variant_id`: `0x00` for the BME680, `0x01` for the BME688.
102    pub const VARIANT_ID: u8 = 0xF0;
103
104    /// Length of calibration block 1.
105    pub const COEFF1_LEN: usize = 23;
106    /// Length of calibration block 2.
107    pub const COEFF2_LEN: usize = 14;
108    /// Length of calibration block 3 (`0x00..=0x04`).
109    pub const COEFF3_LEN: usize = 5;
110    /// Length of the concatenated calibration image.
111    pub const CALIBRATION_LEN: usize = COEFF1_LEN + COEFF2_LEN + COEFF3_LEN;
112    /// Length of one measurement field.
113    pub const FIELD_LEN: usize = 17;
114}
115
116/// Soft reset command written to [`regs::SOFT_RESET`].
117pub const SOFT_RESET_COMMAND: u8 = 0xB6;
118
119/// Errors returned by the BME680 driver.
120#[derive(Debug)]
121pub enum Error<E> {
122    /// Error from the underlying I2C bus.
123    Bus(E),
124    /// The chip ID register (`0xD0`) did not read [`CHIP_ID`]. The payload is
125    /// the value that was read.
126    InvalidDevice(u8),
127    /// A measurement was requested before the calibration data had been read.
128    /// Call `init` first.
129    NotCalibrated,
130    /// The sensor did not report a new measurement within the driver's polling
131    /// limit.
132    Timeout,
133}
134
135impl<E> From<E> for Error<E> {
136    fn from(error: E) -> Self {
137        Error::Bus(error)
138    }
139}
140
141/// Calibration coefficients, named after Bosch's `struct bme68x_calib_data`.
142///
143/// All fields are public so that a calibration image read elsewhere can be fed
144/// to the compensation functions, but normal use only requires [`BME680::init`]
145/// to read them from the device.
146#[derive(Debug, Default, Clone, Copy)]
147pub struct CalibrationData {
148    /// Temperature coefficient 1.
149    pub par_t1: u16,
150    /// Temperature coefficient 2.
151    pub par_t2: i16,
152    /// Temperature coefficient 3.
153    pub par_t3: i8,
154    /// Pressure coefficient 1.
155    pub par_p1: u16,
156    /// Pressure coefficient 2.
157    pub par_p2: i16,
158    /// Pressure coefficient 3.
159    pub par_p3: i8,
160    /// Pressure coefficient 4.
161    pub par_p4: i16,
162    /// Pressure coefficient 5.
163    pub par_p5: i16,
164    /// Pressure coefficient 6.
165    pub par_p6: i8,
166    /// Pressure coefficient 7.
167    pub par_p7: i8,
168    /// Pressure coefficient 8.
169    pub par_p8: i16,
170    /// Pressure coefficient 9.
171    pub par_p9: i16,
172    /// Pressure coefficient 10.
173    pub par_p10: u8,
174    /// Humidity coefficient 1.
175    pub par_h1: u16,
176    /// Humidity coefficient 2.
177    pub par_h2: u16,
178    /// Humidity coefficient 3.
179    pub par_h3: i8,
180    /// Humidity coefficient 4.
181    pub par_h4: i8,
182    /// Humidity coefficient 5.
183    pub par_h5: i8,
184    /// Humidity coefficient 6.
185    pub par_h6: u8,
186    /// Humidity coefficient 7.
187    pub par_h7: i8,
188    /// Gas heater coefficient 1.
189    pub par_gh1: i8,
190    /// Gas heater coefficient 2.
191    pub par_gh2: i16,
192    /// Gas heater coefficient 3.
193    pub par_gh3: i8,
194    /// Heater resistance range.
195    pub res_heat_range: u8,
196    /// Heater resistance correction value.
197    pub res_heat_val: i8,
198    /// Gas range switching error. Bosch parses this as a **signed** value.
199    pub range_sw_err: i8,
200}
201
202impl CalibrationData {
203    /// Placeholder used until `init` reads the real values from the device.
204    pub fn new() -> Self {
205        Self::default()
206    }
207
208    /// Decode the three calibration blocks exactly as Bosch's `get_calib_data`.
209    ///
210    /// `raw` is the concatenation of block 1 (`0x8A..=0xA0`), block 2
211    /// (`0xE1..=0xEE`) and block 3 (`0x00..=0x04`).
212    fn from_raw(raw: &[u8; regs::CALIBRATION_LEN]) -> Self {
213        Self {
214            par_t1: u16::from_le_bytes([raw[31], raw[32]]),
215            par_t2: i16::from_le_bytes([raw[0], raw[1]]),
216            par_t3: raw[2] as i8,
217            par_p1: u16::from_le_bytes([raw[4], raw[5]]),
218            par_p2: i16::from_le_bytes([raw[6], raw[7]]),
219            par_p3: raw[8] as i8,
220            par_p4: i16::from_le_bytes([raw[10], raw[11]]),
221            par_p5: i16::from_le_bytes([raw[12], raw[13]]),
222            par_p6: raw[15] as i8,
223            par_p7: raw[14] as i8,
224            par_p8: i16::from_le_bytes([raw[18], raw[19]]),
225            par_p9: i16::from_le_bytes([raw[20], raw[21]]),
226            par_p10: raw[22],
227            // par_h1 lives in the low nibble of 0xE2 and the whole of 0xE3,
228            // par_h2 in the high nibble of 0xE2 and the whole of 0xE1.
229            par_h1: ((raw[25] as u16) << 4) | (raw[24] as u16 & 0x0F),
230            par_h2: ((raw[23] as u16) << 4) | (raw[24] as u16 >> 4),
231            par_h3: raw[26] as i8,
232            par_h4: raw[27] as i8,
233            par_h5: raw[28] as i8,
234            par_h6: raw[29],
235            par_h7: raw[30] as i8,
236            par_gh1: raw[35] as i8,
237            par_gh2: i16::from_le_bytes([raw[33], raw[34]]),
238            par_gh3: raw[36] as i8,
239            res_heat_range: (raw[39] & 0x30) / 16,
240            res_heat_val: raw[37] as i8,
241            range_sw_err: ((raw[41] & 0xF0) as i8) / 16,
242        }
243    }
244}
245
246/// One compensated measurement.
247///
248/// The `raw_*` accessors return the ADC values exactly as they appeared in the
249/// sensor's measurement field. The public fields hold Bosch's integer
250/// compensation results, so integer-only users never have to touch floating
251/// point; the `f32` accessors are a convenience with a single conversion at the
252/// end.
253#[derive(Debug, Clone, Copy)]
254pub struct Measurements {
255    raw_temperature: u32,
256    raw_pressure: u32,
257    raw_humidity: u16,
258    raw_gas_resistance: u16,
259    gas_range: u8,
260    /// Compensated temperature in hundredths of a degree Celsius.
261    pub temperature: i32,
262    /// Compensated pressure in pascal.
263    pub pressure: u32,
264    /// Compensated relative humidity in thousandths of a percent.
265    pub humidity: u32,
266    /// Compensated gas resistance in ohms. Bosch's `gasm_valid` flag says
267    /// whether this value is meaningful; the resistance also drifts and needs
268    /// burn-in, so treat it as a relative air-quality signal, not a calibrated
269    /// reading.
270    pub gas_resistance: u32,
271    /// Bosch `gasm_valid`: the gas measurement completed.
272    pub gas_valid: bool,
273    /// Bosch `heat_stab`: the gas heater reached its set point, so
274    /// `gas_resistance` is trustworthy.
275    pub heat_stable: bool,
276}
277
278impl Measurements {
279    /// Compensated temperature in degrees Celsius.
280    pub fn temperature_celsius(&self) -> f32 {
281        self.temperature as f32 / 100.0
282    }
283
284    /// Compensated pressure in pascal.
285    pub fn pressure_pa(&self) -> u32 {
286        self.pressure
287    }
288
289    /// Compensated pressure in hectopascal.
290    pub fn pressure_hpa(&self) -> f32 {
291        self.pressure as f32 / 100.0
292    }
293
294    /// Compensated relative humidity in percent.
295    pub fn humidity_percent(&self) -> f32 {
296        self.humidity as f32 / 1000.0
297    }
298
299    /// Compensated gas resistance in ohms.
300    pub fn gas_resistance_ohms(&self) -> f32 {
301        self.gas_resistance as f32
302    }
303
304    /// Raw 20-bit temperature ADC value.
305    pub fn raw_temperature(&self) -> u32 {
306        self.raw_temperature
307    }
308
309    /// Raw 20-bit pressure ADC value.
310    pub fn raw_pressure(&self) -> u32 {
311        self.raw_pressure
312    }
313
314    /// Raw 16-bit humidity ADC value.
315    pub fn raw_humidity(&self) -> u16 {
316        self.raw_humidity
317    }
318
319    /// Raw 10-bit gas resistance ADC value.
320    pub fn raw_gas_resistance(&self) -> u16 {
321        self.raw_gas_resistance
322    }
323
324    /// Gas range index (0..=15) used to interpret [`Self::raw_gas_resistance`].
325    pub fn gas_range(&self) -> u8 {
326        self.gas_range
327    }
328}
329
330// - MARK: Bosch compensation maths
331
332/// Lookup table 1 from Bosch's `calc_gas_resistance_low`.
333const GAS_RANGE_LOOKUP_1: [i64; 16] = [
334    2_147_483_647,
335    2_147_483_647,
336    2_147_483_647,
337    2_147_483_647,
338    2_147_483_647,
339    2_126_008_810,
340    2_147_483_647,
341    2_130_303_777,
342    2_147_483_647,
343    2_147_483_647,
344    2_143_188_679,
345    2_136_746_228,
346    2_147_483_647,
347    2_126_008_810,
348    2_147_483_647,
349    2_147_483_647,
350];
351
352/// Lookup table 2 from Bosch's `calc_gas_resistance_low`.
353const GAS_RANGE_LOOKUP_2: [i64; 16] = [
354    4_096_000_000,
355    2_048_000_000,
356    1_024_000_000,
357    512_000_000,
358    255_744_255,
359    127_110_228,
360    64_000_000,
361    32_258_064,
362    16_016_016,
363    8_000_000,
364    4_000_000,
365    2_000_000,
366    1_000_000,
367    500_000,
368    250_000,
369    125_000,
370];
371
372/// Bosch `calc_temperature`. Returns `(t_fine, temperature)` where the
373/// temperature is in hundredths of a degree Celsius and `t_fine` is the
374/// intermediate used by pressure and humidity.
375#[inline]
376fn calc_temperature(adc_temp: u32, calib: &CalibrationData) -> (i32, i32) {
377    let var1 = ((adc_temp as i32 >> 3) - ((calib.par_t1 as i32) << 1)) as i64;
378    let var2 = (var1 * (calib.par_t2 as i64)) >> 11;
379    let var3 = ((var1 >> 1) * (var1 >> 1)) >> 12;
380    let var3 = (var3 * ((calib.par_t3 as i64) << 4)) >> 14;
381
382    let t_fine = (var2 + var3) as i32;
383    let temperature = ((t_fine * 5) + 128) >> 8;
384
385    (t_fine, temperature)
386}
387
388/// Bosch `calc_pressure`. Returns pressure in pascal.
389///
390/// Bosch performs some of these operations in `int32_t` where they are allowed
391/// to wrap; the `wrapping_*` calls reproduce that two's-complement behaviour
392/// instead of panicking in a debug build. The `var1 == 0` guard is ours: Bosch
393/// would divide by zero on a device whose `par_p1` read back as zero.
394#[inline]
395fn calc_pressure(adc_pres: u32, t_fine: i32, calib: &CalibrationData) -> u32 {
396    /// Bosch's `BME68X_OVERFLOW_CHECK` (`1 << 30`).
397    const OVERFLOW_CHECK: i32 = 0x4000_0000;
398
399    let mut var1 = (t_fine >> 1).wrapping_sub(64_000);
400    let mut var2 = (((var1 >> 2).wrapping_mul(var1 >> 2)) >> 11).wrapping_mul(calib.par_p6 as i32) >> 2;
401    var2 = var2.wrapping_add((var1.wrapping_mul(calib.par_p5 as i32)) << 1);
402    var2 = (var2 >> 2).wrapping_add((calib.par_p4 as i32) << 16);
403    var1 = (((((var1 >> 2).wrapping_mul(var1 >> 2)) >> 13).wrapping_mul((calib.par_p3 as i32) << 5)) >> 3)
404        .wrapping_add((calib.par_p2 as i32).wrapping_mul(var1) >> 1);
405    var1 >>= 18;
406    var1 = (32_768_i32.wrapping_add(var1).wrapping_mul(calib.par_p1 as i32)) >> 15;
407
408    if var1 == 0 {
409        return 0;
410    }
411
412    let mut pressure_comp = (1_048_576_i32.wrapping_sub(adc_pres as i32))
413        .wrapping_sub(var2 >> 12)
414        .wrapping_mul(3125);
415
416    pressure_comp = if pressure_comp >= OVERFLOW_CHECK {
417        (pressure_comp / var1) << 1
418    } else {
419        (pressure_comp << 1) / var1
420    };
421
422    var1 = (calib.par_p9 as i32).wrapping_mul(((pressure_comp >> 3).wrapping_mul(pressure_comp >> 3)) >> 13) >> 12;
423    var2 = ((pressure_comp >> 2).wrapping_mul(calib.par_p8 as i32)) >> 13;
424    let var3 = ((pressure_comp >> 8)
425        .wrapping_mul(pressure_comp >> 8)
426        .wrapping_mul(pressure_comp >> 8))
427    .wrapping_mul(calib.par_p10 as i32)
428        >> 17;
429
430    pressure_comp = pressure_comp.wrapping_add(
431        (var1
432            .wrapping_add(var2)
433            .wrapping_add(var3)
434            .wrapping_add((calib.par_p7 as i32) << 7))
435            >> 4,
436    );
437
438    pressure_comp as u32
439}
440
441/// Bosch `calc_humidity`. Returns relative humidity in thousandths of a
442/// percent, capped to `0..=100_000`.
443///
444/// As in [`calc_pressure`], `wrapping_*` reproduces the wrapping of Bosch's
445/// `int32_t` arithmetic.
446#[inline]
447fn calc_humidity(adc_hum: u16, t_fine: i32, calib: &CalibrationData) -> u32 {
448    let temp_scaled = ((t_fine.wrapping_mul(5)).wrapping_add(128)) >> 8;
449
450    let var1 = (adc_hum as i32)
451        .wrapping_sub((calib.par_h1 as i32).wrapping_mul(16))
452        .wrapping_sub((temp_scaled.wrapping_mul(calib.par_h3 as i32) / 100) >> 1);
453
454    let var2 = (calib.par_h2 as i32).wrapping_mul(
455        (temp_scaled.wrapping_mul(calib.par_h4 as i32) / 100)
456            .wrapping_add((temp_scaled.wrapping_mul(temp_scaled.wrapping_mul(calib.par_h5 as i32) / 100) >> 6) / 100)
457            .wrapping_add(1 << 14),
458    ) >> 10;
459
460    let var3 = var1.wrapping_mul(var2);
461    let var4 = ((calib.par_h6 as i32) << 7).wrapping_add(temp_scaled.wrapping_mul(calib.par_h7 as i32) / 100) >> 4;
462    let var5 = ((var3 >> 14).wrapping_mul(var3 >> 14)) >> 10;
463    let var6 = var4.wrapping_mul(var5) >> 1;
464    let humidity = ((var3.wrapping_add(var6) >> 10).wrapping_mul(1000)) >> 12;
465
466    humidity.clamp(0, 100_000) as u32
467}
468
469/// Bosch `calc_gas_resistance_low`, the **BME680** (`BME68X_VARIANT_GAS_LOW`)
470/// gas path. Returns gas resistance in ohms.
471#[inline]
472fn calc_gas_resistance(adc_gas: u16, gas_range: u8, calib: &CalibrationData) -> u32 {
473    let var1 = ((1340 + 5 * (calib.range_sw_err as i64)) * GAS_RANGE_LOOKUP_1[gas_range as usize]) >> 16;
474    let var2 = ((adc_gas as i64) << 15) - 16_777_216 + var1;
475    let var3 = (GAS_RANGE_LOOKUP_2[gas_range as usize] * var1) >> 9;
476
477    if var2 == 0 {
478        return 0;
479    }
480
481    ((var3 + (var2 >> 1)) / var2) as u32
482}
483
484/// Bosch `calc_res_heat`. Returns the value for the `res_heat0` register.
485///
486/// `target_celsius` is capped at 400 C, exactly as Bosch does. `ambient_celsius`
487/// is the only place the driver needs an ambient temperature.
488#[inline]
489fn calc_res_heat(target_celsius: u16, ambient_celsius: i8, calib: &CalibrationData) -> u8 {
490    let temp = target_celsius.min(400) as i32;
491
492    let var1 = (((ambient_celsius as i32) * (calib.par_gh3 as i32)) / 1000) * 256;
493    let var2 =
494        (calib.par_gh1 as i32 + 784) * (((((calib.par_gh2 as i32 + 154_009) * temp * 5) / 100) + 3_276_800) / 10);
495    let var3 = var1 + (var2 / 2);
496    let var4 = var3 / (calib.res_heat_range as i32 + 4);
497    let var5 = (131 * (calib.res_heat_val as i32)) + 65_536;
498    let heatr_res_x100 = ((var4 / var5) - 250) * 34;
499
500    ((heatr_res_x100 + 50) / 100) as u8
501}
502
503/// Bosch `calc_gas_wait`. Encodes a heater duration in milliseconds for the
504/// `gas_wait0` register (strictly, it is a uint16 duration with an exponent and
505/// a mantissa, in units of the sensor's frame timing).
506#[inline]
507fn calc_gas_wait(mut duration_ms: u16) -> u8 {
508    if duration_ms >= 0x0FC0 {
509        return 0xFF;
510    }
511
512    let mut factor = 0u8;
513    while duration_ms > 0x3F {
514        duration_ms /= 4;
515        factor += 1;
516    }
517
518    (duration_ms as u8) + (factor * 64)
519}
520
521/// Decode a raw measurement field and compensate every channel.
522fn compensate_field(calib: &CalibrationData, field: &[u8; regs::FIELD_LEN]) -> Measurements {
523    let raw_pressure = ((field[2] as u32) << 12) | ((field[3] as u32) << 4) | ((field[4] as u32) >> 4);
524    let raw_temperature = ((field[5] as u32) << 12) | ((field[6] as u32) << 4) | ((field[7] as u32) >> 4);
525    let raw_humidity = ((field[8] as u16) << 8) | (field[9] as u16);
526    let raw_gas_resistance = ((field[13] as u16) << 2) | ((field[14] as u16) >> 6);
527    let gas_range = field[14] & regs::FIELD_GAS_RANGE;
528
529    let (t_fine, temperature) = calc_temperature(raw_temperature, calib);
530    let pressure = calc_pressure(raw_pressure, t_fine, calib);
531    let humidity = calc_humidity(raw_humidity, t_fine, calib);
532    let gas_resistance = calc_gas_resistance(raw_gas_resistance, gas_range, calib);
533
534    Measurements {
535        raw_temperature,
536        raw_pressure,
537        raw_humidity,
538        raw_gas_resistance,
539        gas_range,
540        temperature,
541        pressure,
542        humidity,
543        gas_resistance,
544        gas_valid: field[14] & regs::FIELD_GAS_VALID != 0,
545        heat_stable: field[14] & regs::FIELD_HEAT_STABLE != 0,
546    }
547}
548
549// - MARK: Async driver
550
551/// Async BME680 driver.
552pub struct BME680<I2C: embedded_hal_async::i2c::I2c> {
553    addr: u8,
554    i2c: I2C,
555    calibrated: bool,
556    /// Ambient temperature used by [`BME680::set_gas_heater`]; defaults to
557    /// [`DEFAULT_AMBIENT_CELSIUS`].
558    pub ambient_temperature_celsius: i8,
559    /// Variant ID read from register `0xF0`: `0x00` is a BME680, `0x01` a
560    /// BME688. Gas compensation is only valid for `0x00`.
561    pub variant_id: u8,
562    /// Calibration data read by [`BME680::init`].
563    pub calib: CalibrationData,
564    gas_heater_target_celsius: u16,
565    gas_heater_duration_ms: u16,
566}
567
568impl<I2C: embedded_hal_async::i2c::I2c> BME680<I2C> {
569    /// Create a driver for a sensor at `addr`.
570    ///
571    /// This does not touch the bus. Call [`BME680::init`] before measuring.
572    pub fn new(i2c: I2C, addr: u8) -> Self {
573        Self {
574            addr,
575            i2c,
576            calibrated: false,
577            ambient_temperature_celsius: DEFAULT_AMBIENT_CELSIUS,
578            variant_id: 0,
579            calib: CalibrationData::new(),
580            gas_heater_target_celsius: DEFAULT_HEATER_TARGET_CELSIUS,
581            gas_heater_duration_ms: DEFAULT_HEATER_DURATION_MS,
582        }
583    }
584
585    /// Create a driver for a sensor at the default address ([`ADDRESS`]).
586    pub fn new_primary(i2c: I2C) -> Self {
587        Self::new(i2c, ADDRESS)
588    }
589
590    /// Validate the chip, read the calibration data and program the defaults.
591    ///
592    /// Bosch's own `bme68x_init` starts with a soft reset, but this driver
593    /// deliberately splits the reset into [`BME680::reset`] to match
594    /// [`bme280`](https://docs.rs/edrv-bme280): the two crates share one shape.
595    /// `init` is safe without a preceding reset because it programs every
596    /// control register explicitly.
597    ///
598    /// Unlike `bme280`, the control registers are written as one burst in
599    /// Bosch's order, `CTRL_GAS_1 (0x71)` through `CONFIG (0x75)`. This matters:
600    /// `CTRL_HUM (0x72)` must be written *before* `CTRL_MEAS (0x74)`, otherwise
601    /// the humidity oversampling setting never takes effect.
602    ///
603    /// Defaults: temperature oversampling x2, pressure x16, humidity x1, IIR
604    /// filter size 3, gas heater enabled at 320 C for 150 ms. The part is left
605    /// in sleep mode; use [`BME680::measure`] for a one-shot forced-mode
606    /// measurement.
607    pub async fn init(&mut self) -> Result<(), Error<I2C::Error>> {
608        let chip_id = self.read_reg(regs::CHIP_ID).await?;
609        if chip_id != CHIP_ID {
610            return Err(Error::InvalidDevice(chip_id));
611        }
612
613        self.variant_id = self.read_reg(regs::VARIANT_ID).await?;
614
615        self.read_calibration().await?;
616        self.configure().await?;
617        self.write_heater_config().await?;
618
619        Ok(())
620    }
621
622    /// Soft reset the sensor and wait for it to come back.
623    ///
624    /// Writes `0xB6` to register `0xE0` and waits 10 ms, which is Bosch's
625    /// `BME68X_PERIOD_RESET` (10000 microseconds). The calibration data is kept,
626    /// but the driver is marked uncalibrated so the next [`BME680::measure`]
627    /// fails with [`Error::NotCalibrated`] until `init` runs again.
628    pub async fn reset(&mut self, mut delay: impl DelayNs) -> Result<(), Error<I2C::Error>> {
629        self.write_reg(regs::SOFT_RESET, SOFT_RESET_COMMAND).await?;
630
631        delay.delay_ms(10).await;
632
633        self.calibrated = false;
634
635        Ok(())
636    }
637
638    /// Read and store the calibration data. Also called by [`BME680::init`].
639    async fn read_calibration(&mut self) -> Result<(), Error<I2C::Error>> {
640        let mut raw = [0u8; regs::CALIBRATION_LEN];
641        let split = regs::COEFF1_LEN + regs::COEFF2_LEN;
642        self.read_regs(regs::COEFF1, &mut raw[..regs::COEFF1_LEN]).await?;
643        self.read_regs(regs::COEFF2, &mut raw[regs::COEFF1_LEN..split]).await?;
644        self.read_regs(regs::RES_HEAT_VAL, &mut raw[split..]).await?;
645
646        self.calib = CalibrationData::from_raw(&raw);
647        self.calibrated = true;
648
649        Ok(())
650    }
651
652    /// Program the default oversampling, filter and gas settings.
653    async fn configure(&mut self) -> Result<(), Error<I2C::Error>> {
654        // Read and write the whole 0x71..=0x75 block, as Bosch's
655        // `bme68x_set_conf` does. Bit fields have to be merged into the values
656        // that are already there so reserved bits are preserved.
657        let mut conf = [0u8; 5];
658        self.read_regs(regs::CTRL_GAS_1, &mut conf).await?;
659        let [ctrl_gas_1, ctrl_hum, _reserved, ctrl_meas, config] = &mut conf;
660
661        // ctrl_gas_1: nb_conv = 0, run_gas = 1, ODR3 = 1. Bosch's
662        // `bme68x_set_conf` sets ODR3 when the ODR is disabled.
663        *ctrl_gas_1 = (*ctrl_gas_1 & !0x0F) | (1 << 4) | 0x80;
664        // ctrl_hum: osrs_h = x1.
665        *ctrl_hum = (*ctrl_hum & !0x07) | 0b001;
666        // ctrl_meas: osrs_t = x2, osrs_p = x16, mode = sleep.
667        *ctrl_meas = (*ctrl_meas & !0xE0) | (0b010 << 5);
668        *ctrl_meas = (*ctrl_meas & !0x1C) | (0b101 << 2);
669        *ctrl_meas &= !0x03;
670        // config: ODR20 = 0, IIR filter coefficient 3.
671        *config = (*config & !0xE0) | (0b010 << 2);
672
673        self.write_config_block(&conf).await?;
674
675        // ctrl_gas_0 bit 3 low enables the heater.
676        let ctrl_gas_0 = self.read_reg(regs::CTRL_GAS_0).await?;
677        self.write_reg(regs::CTRL_GAS_0, ctrl_gas_0 & !0x08).await?;
678
679        Ok(())
680    }
681
682    /// Write `res_heat0` and `gas_wait0` for the configured heater profile.
683    async fn write_heater_config(&mut self) -> Result<(), Error<I2C::Error>> {
684        let res_heat = calc_res_heat(
685            self.gas_heater_target_celsius,
686            self.ambient_temperature_celsius,
687            &self.calib,
688        );
689        let gas_wait = calc_gas_wait(self.gas_heater_duration_ms);
690
691        self.write_reg(regs::RES_HEAT0, res_heat).await?;
692        self.write_reg(regs::GAS_WAIT0, gas_wait).await?;
693
694        Ok(())
695    }
696
697    /// Perform a single forced-mode measurement.
698    ///
699    /// Triggers one conversion and polls the measurement field for the new-data
700    /// flag, sleeping 1 ms between polls. The `delay` is borrowed exactly like
701    /// [`bme280::reset`](https://docs.rs/edrv-bme280) borrows its delay. Returns
702    /// [`Error::Timeout`] if no new data appears within the polling limit
703    /// (roughly one second, which is far longer than the 150 ms gas heater plus
704    /// a TPH conversion).
705    ///
706    /// [`Error::NotCalibrated`] is returned if [`BME680::init`] has not run (or
707    /// [`BME680::reset`] has run since).
708    pub async fn measure(&mut self, mut delay: impl DelayNs) -> Result<Measurements, Error<I2C::Error>> {
709        /// Number of 1 ms polls before giving up.
710        const POLL_LIMIT: u32 = 1000;
711
712        if !self.calibrated {
713            return Err(Error::NotCalibrated);
714        }
715
716        // The heater profile can be changed between measurements, so re-apply it
717        // while the part is still in sleep mode.
718        self.write_heater_config().await?;
719
720        // Trigger a single forced-mode conversion.
721        let ctrl_meas = self.read_reg(regs::CTRL_MEAS).await?;
722        self.write_reg(regs::CTRL_MEAS, (ctrl_meas & !0x03) | 0x01).await?;
723
724        let mut polls = 0;
725        while self.read_reg(regs::FIELD0).await? & regs::FIELD_NEW_DATA == 0 {
726            polls += 1;
727            if polls >= POLL_LIMIT {
728                return Err(Error::Timeout);
729            }
730            delay.delay_ms(1).await;
731        }
732
733        let mut field = [0u8; regs::FIELD_LEN];
734        self.read_regs(regs::FIELD0, &mut field).await?;
735
736        Ok(compensate_field(&self.calib, &field))
737    }
738
739    /// Set the gas heater target and duration used by later
740    /// [`BME680::measure`] calls.
741    ///
742    /// The values are stored, not written immediately; `measure` programs
743    /// `res_heat0`/`gas_wait0` before triggering each conversion. `target_celsius`
744    /// is capped at 400 C by the compensation maths, and `duration_ms` saturates
745    /// at the sensor's maximum encodable value.
746    pub fn set_gas_heater(&mut self, target_celsius: u16, duration_ms: u16) {
747        self.gas_heater_target_celsius = target_celsius;
748        self.gas_heater_duration_ms = duration_ms;
749    }
750
751    /// Write the 5-byte `0x71..=0x75` configuration block in one transaction.
752    async fn write_config_block(&mut self, conf: &[u8; 5]) -> Result<(), Error<I2C::Error>> {
753        self.i2c
754            .write(
755                self.addr,
756                &[regs::CTRL_GAS_1, conf[0], conf[1], conf[2], conf[3], conf[4]],
757            )
758            .await?;
759
760        Ok(())
761    }
762
763    /// Read one register.
764    pub async fn read_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
765        let mut buf = [0u8; 1];
766        self.i2c.write_read(self.addr, &[reg], &mut buf).await?;
767        Ok(buf[0])
768    }
769
770    /// Read consecutive registers into `buf`.
771    pub async fn read_regs(&mut self, reg: u8, buf: &mut [u8]) -> Result<(), Error<I2C::Error>> {
772        self.i2c.write_read(self.addr, &[reg], buf).await?;
773        Ok(())
774    }
775
776    /// Write one register.
777    pub async fn write_reg(&mut self, reg: u8, val: u8) -> Result<(), Error<I2C::Error>> {
778        self.i2c.write(self.addr, &[reg, val]).await?;
779        Ok(())
780    }
781}
782
783#[cfg(test)]
784mod tests {
785    use super::*;
786
787    /// Real-sensor calibration dump, used by Pimoroni's own compensation tests
788    /// (bme680-python issue #11), encoded into Bosch's 42-byte register image.
789    const CALIBRATION_A: [u8; regs::CALIBRATION_LEN] = [
790        0x65, 0x67, 0x03, 0x00, 0x41, 0x8f, 0xed, 0xd6, 0x58, 0x00, 0x8e, 0x1c, 0x7f, 0xff, 0x2e, 0x1e, 0x00, 0x00,
791        0x97, 0xf3, 0xb5, 0xf6, 0x1e, 0x40, 0x54, 0x2a, 0x00, 0x2d, 0x14, 0x78, 0x9c, 0xb9, 0x65, 0x4e, 0x9f, 0xe2,
792        0x12, 0x30, 0x00, 0x10, 0x00, 0x00,
793    ];
794
795    /// Calibration used by the `bme68x` crate's own compensation tests.
796    const CALIBRATION_B: [u8; regs::CALIBRATION_LEN] = [
797        0x66, 0x67, 0x03, 0x00, 0x30, 0x8e, 0x43, 0xd6, 0x58, 0x00, 0x10, 0x27, 0x38, 0xff, 0xce, 0x1e, 0x00, 0x00,
798        0xa8, 0xe4, 0x70, 0x17, 0x1e, 0x3f, 0xb8, 0x33, 0x00, 0x2d, 0x14, 0x78, 0x9c, 0x90, 0x65, 0x3c, 0xf6, 0xe2,
799        0x04, 0x28, 0x00, 0x10, 0x00, 0xe0,
800    ];
801
802    /// Build a measurement field the way Bosch's `read_field_data` parses it.
803    fn field(
804        temperature: u32,
805        pressure: u32,
806        humidity: u16,
807        gas_resistance: u16,
808        gas_range: u8,
809        gas_valid: bool,
810        heat_stable: bool,
811    ) -> [u8; regs::FIELD_LEN] {
812        let mut field = [0u8; regs::FIELD_LEN];
813        field[0] = regs::FIELD_NEW_DATA;
814        field[2] = (pressure >> 12) as u8;
815        field[3] = (pressure >> 4) as u8;
816        field[4] = ((pressure & 0x0F) << 4) as u8;
817        field[5] = (temperature >> 12) as u8;
818        field[6] = (temperature >> 4) as u8;
819        field[7] = ((temperature & 0x0F) << 4) as u8;
820        field[8] = (humidity >> 8) as u8;
821        field[9] = humidity as u8;
822        field[13] = (gas_resistance >> 2) as u8;
823        field[14] = (((gas_resistance & 0x03) << 6) as u8) | (gas_range & regs::FIELD_GAS_RANGE);
824        if gas_valid {
825            field[14] |= regs::FIELD_GAS_VALID;
826        }
827        if heat_stable {
828            field[14] |= regs::FIELD_HEAT_STABLE;
829        }
830        field
831    }
832
833    #[test]
834    fn calibration_decoding_matches_bosch_reference() {
835        let a = CalibrationData::from_raw(&CALIBRATION_A);
836        assert_eq!(a.par_t1, 26041);
837        assert_eq!(a.par_t2, 26469);
838        assert_eq!(a.par_t3, 3);
839        assert_eq!(a.par_p1, 36673);
840        assert_eq!(a.par_p2, -10515);
841        assert_eq!(a.par_p3, 88);
842        assert_eq!(a.par_p4, 7310);
843        assert_eq!(a.par_p5, -129);
844        assert_eq!(a.par_p6, 30);
845        assert_eq!(a.par_p7, 46);
846        assert_eq!(a.par_p8, -3177);
847        assert_eq!(a.par_p9, -2379);
848        assert_eq!(a.par_p10, 30);
849        assert_eq!(a.par_h1, 676);
850        assert_eq!(a.par_h2, 1029);
851        assert_eq!(a.par_h3, 0);
852        assert_eq!(a.par_h4, 45);
853        assert_eq!(a.par_h5, 20);
854        assert_eq!(a.par_h6, 120);
855        assert_eq!(a.par_h7, -100);
856        assert_eq!(a.par_gh1, -30);
857        assert_eq!(a.par_gh2, -24754);
858        assert_eq!(a.par_gh3, 18);
859        assert_eq!(a.res_heat_range, 1);
860        assert_eq!(a.res_heat_val, 48);
861        assert_eq!(a.range_sw_err, 0);
862
863        // Two's-complement packing of the shared H1/H2 byte and the signed
864        // range-switching error (0xE0 decodes to -2).
865        let b = CalibrationData::from_raw(&CALIBRATION_B);
866        assert_eq!(b.par_h1, 824);
867        assert_eq!(b.par_h2, 1019);
868        assert_eq!(b.par_gh2, -2500);
869        assert_eq!(b.range_sw_err, -2);
870    }
871
872    #[test]
873    fn temperature_matches_bosch_reference() {
874        let a = CalibrationData::from_raw(&CALIBRATION_A);
875        let (t_fine, temperature) = calc_temperature(501240, &a);
876        assert_eq!(t_fine, 136667);
877        assert_eq!(temperature, 2669);
878
879        let b = CalibrationData::from_raw(&CALIBRATION_B);
880        let (t_fine, temperature) = calc_temperature(519888, &b);
881        assert_eq!(t_fine, 167871);
882        assert_eq!(temperature, 3279);
883    }
884
885    #[test]
886    fn pressure_matches_bosch_reference() {
887        let a = CalibrationData::from_raw(&CALIBRATION_A);
888        let (t_fine, _) = calc_temperature(501240, &a);
889        assert_eq!(calc_pressure(353485, t_fine, &a), 98711);
890
891        let b = CalibrationData::from_raw(&CALIBRATION_B);
892        let (t_fine, _) = calc_temperature(519888, &b);
893        assert_eq!(calc_pressure(364576, t_fine, &b), 91655);
894    }
895
896    #[test]
897    fn humidity_matches_bosch_reference() {
898        let a = CalibrationData::from_raw(&CALIBRATION_A);
899        let (t_fine, _) = calc_temperature(501240, &a);
900        assert_eq!(calc_humidity(19019, t_fine, &a), 42402);
901
902        // Bosch caps humidity at 100 %RH.
903        let b = CalibrationData::from_raw(&CALIBRATION_B);
904        let (t_fine, _) = calc_temperature(519888, &b);
905        assert_eq!(calc_humidity(30000, t_fine, &b), 100000);
906    }
907
908    #[test]
909    fn gas_resistance_matches_bosch_reference() {
910        let a = CalibrationData::from_raw(&CALIBRATION_A);
911        assert_eq!(calc_gas_resistance(0, 0, &a), 12946860);
912
913        // Range 12 is the entry that several third-party ports get wrong; the
914        // Bosch value is 1711 ohms.
915        let b = CalibrationData::from_raw(&CALIBRATION_B);
916        assert_eq!(calc_gas_resistance(700, 8, &b), 27407);
917        assert_eq!(calc_gas_resistance(700, 12, &b), 1711);
918    }
919
920    #[test]
921    fn heater_resistance_matches_bosch_reference() {
922        let a = CalibrationData::from_raw(&CALIBRATION_A);
923        assert_eq!(calc_res_heat(200, 25, &a), 78);
924        assert_eq!(calc_res_heat(300, 25, &a), 101);
925        assert_eq!(calc_res_heat(320, 25, &a), 106);
926        assert_eq!(calc_res_heat(400, 25, &a), 124);
927        // Targets above 400 C are capped, not rejected.
928        assert_eq!(calc_res_heat(500, 25, &a), calc_res_heat(400, 25, &a));
929
930        let b = CalibrationData::from_raw(&CALIBRATION_B);
931        assert_eq!(calc_res_heat(320, 25, &b), 121);
932    }
933
934    #[test]
935    fn gas_wait_encoding_matches_bosch_reference() {
936        assert_eq!(calc_gas_wait(0), 0x00);
937        assert_eq!(calc_gas_wait(63), 0x3F);
938        assert_eq!(calc_gas_wait(64), 0x50);
939        assert_eq!(calc_gas_wait(150), 0x65);
940        assert_eq!(calc_gas_wait(252), 0x7F);
941        assert_eq!(calc_gas_wait(1008), 0xBF);
942        assert_eq!(calc_gas_wait(4031), 0xFE);
943        assert_eq!(calc_gas_wait(4032), 0xFF);
944        assert_eq!(calc_gas_wait(u16::MAX), 0xFF);
945    }
946
947    #[test]
948    fn field_decoding_and_compensation_match_reference() {
949        let a = CalibrationData::from_raw(&CALIBRATION_A);
950        let raw_field = field(501240, 353485, 19019, 0, 0, true, true);
951        let m = compensate_field(&a, &raw_field);
952
953        // Raw values survive the register bit packing untouched.
954        assert_eq!(m.raw_temperature(), 501240);
955        assert_eq!(m.raw_pressure(), 353485);
956        assert_eq!(m.raw_humidity(), 19019);
957        assert_eq!(m.raw_gas_resistance(), 0);
958        assert_eq!(m.gas_range(), 0);
959
960        // Compensated values match the Bosch C reference.
961        assert_eq!(m.temperature, 2669);
962        assert_eq!(m.temperature_celsius(), 26.69);
963        assert_eq!(m.pressure_pa(), 98711);
964        assert_eq!(m.pressure_hpa(), 987.11);
965        assert_eq!(m.humidity, 42402);
966        assert_eq!(m.humidity_percent(), 42.402);
967        assert_eq!(m.gas_resistance, 12946860);
968        assert_eq!(m.gas_resistance_ohms(), 12946860.0);
969        assert!(m.gas_valid);
970        assert!(m.heat_stable);
971
972        // The flags come from bits 5 and 4 of field byte 14.
973        let m = compensate_field(&a, &field(501240, 353485, 19019, 0, 0, false, false));
974        assert!(!m.gas_valid);
975        assert!(!m.heat_stable);
976    }
977
978    #[test]
979    fn constants_are_as_documented() {
980        assert_eq!(ADDRESS, 0x76);
981        assert_eq!(ADDRESS_ALT, 0x77);
982        assert_eq!(CHIP_ID, 0x61);
983        assert_eq!(SOFT_RESET_COMMAND, 0xB6);
984        assert_eq!(regs::CALIBRATION_LEN, 42);
985        assert_eq!(regs::FIELD_LEN, 17);
986    }
987}