Skip to main content

edrv_bme280/
lib.rs

1//! Driver for BME280 and BMP280.
2//!
3//! The only difference between the two sensors is that the BME280 also includes a humidity sensor.
4//!
5//! # Licence
6//!
7//! This crate is distributed as `MIT OR Apache-2.0`. It also references Bosch's
8//! BSD-3-Clause driver; the retained notice is in `LICENSE-BOSCH`.
9
10#![cfg_attr(not(test), no_std)]
11
12use embedded_hal_async::delay::DelayNs;
13
14pub const ADDRESS: u8 = 0x76;
15
16pub const CHIP_ID_BME280: u8 = 0x60;
17pub const CHIP_ID_BMP280: u8 = 0x58;
18
19/// Control-register writes performed by `init`, **in this exact order**.
20///
21/// The order is a hardware requirement, not a style choice. Bosch's BME280 API
22/// documents that "humidity related changes will be only effective after a write
23/// operation to ctrl_meas register", so `CTRL_HUM` must be written *before*
24/// `CTRL_MEAS`. Written the other way round, the humidity oversampling setting is
25/// silently ignored and `osrs_h` stays at its reset default, which is `0`
26/// (skipped) - so humidity would never be measured at all.
27///
28/// These are two single-byte writes rather than one burst over `0xF2..=0xF5`,
29/// because `0xF3` is the read-only `status` register. (The BME680 can burst its
30/// equivalent `0x71..=0x75` block, but only because all five of those registers
31/// are writable.)
32#[allow(clippy::unusual_byte_groupings)]
33pub const CONTROL_WRITES: [(u8, u8); 2] = [
34    // osrs_h = x1.
35    (regs::CTRL_HUM, 0b001),
36    // osrs_t = x1, osrs_p = x1, mode = sleep. The 3/3/2 grouping mirrors
37    // CTRL_MEAS exactly: osrs_t[7:5], osrs_p[4:2], mode[1:0]. The part is left
38    // idle deliberately: `read_measurement` triggers a forced conversion and
39    // waits for it, which is what makes a returned measurement trustworthy.
40    (regs::CTRL_MEAS, 0b001_001_00),
41];
42
43/// `CTRL_MEAS` with x1 oversampling on temperature and pressure, and
44/// `mode = forced`: triggers exactly one conversion and then returns to sleep.
45///
46/// Same 3/3/2 field grouping as [`CONTROL_WRITES`], hence the allow.
47#[allow(clippy::unusual_byte_groupings)]
48pub(crate) const CTRL_MEAS_FORCED: u8 = 0b001_001_01;
49
50/// Datasheet measurement time at x1 oversampling on all three channels.
51///
52/// The formula is `1.25 + 2.3*osrs_t + (2.3*osrs_p + 0.575) + (2.3*osrs_h + 0.575)`
53/// ms, which is about 9.3 ms at x1/x1/x1. Rounded up.
54const MEASUREMENT_TIME_MS: u32 = 10;
55
56/// Extra 1 ms polling budget after the fixed wait, before giving up.
57const MEASUREMENT_POLL_LIMIT_MS: u32 = 20;
58
59pub mod blocking;
60
61pub mod regs {
62    pub const TEMP_MSB: u8 = 0xFA;
63    pub const TEMP_LSB: u8 = 0xFB;
64    pub const TEMP_XLSB: u8 = 0xFC;
65
66    pub const PRESS_MSB: u8 = 0xF7;
67    pub const PRESS_LSB: u8 = 0xF8;
68    pub const PRESS_XLSB: u8 = 0xF9;
69
70    pub const HUM_MSB: u8 = 0xFD;
71    pub const HUM_LSB: u8 = 0xFE;
72    pub const HUM_XLSB: u8 = 0xFD;
73
74    pub const CHIP_ID: u8 = 0xD0;
75
76    pub const CALIB_00: u8 = 0x88;
77
78    pub const CONFIG: u8 = 0xF5;
79    pub const CTRL_MEAS: u8 = 0xF4;
80    pub const CTRL_HUM: u8 = 0xF2;
81
82    pub const STATUS: u8 = 0xF3;
83
84    /// `status`: a conversion is currently running.
85    pub const STATUS_MEASURING: u8 = 0x08;
86    /// `status`: the NVM calibration data is being copied into the image
87    /// registers. Reading calibration before this clears gives garbage.
88    pub const STATUS_IM_UPDATE: u8 = 0x01;
89
90    /// `press_msb`: start of the 8-byte pressure/temperature/humidity block.
91    pub const DATA_MSB: u8 = 0xF7;
92    /// Length of that block: `press(3) + temp(3) + hum(2)`.
93    pub const DATA_LEN: usize = 8;
94    pub const RESET: u8 = 0xE0;
95}
96
97#[derive(Debug)]
98pub enum Error<E> {
99    Bus(E),
100    CalibrationDataError,
101    ConversionError,
102    InvalidDevice,
103    UnsupportedMeasurement,
104    /// The device did not report a completed conversion within the driver's
105    /// polling limit. Added in 0.1.1; the enum is not `#[non_exhaustive]`, so a
106    /// caller matching exhaustively must handle it.
107    Timeout,
108}
109
110impl<E> From<E> for Error<E> {
111    fn from(error: E) -> Self {
112        Error::Bus(error)
113    }
114}
115
116#[derive(Debug, Default)]
117pub struct CalibrationData {
118    pub dig_t1: u16,
119    pub dig_t2: i16,
120    pub dig_t3: i16,
121    pub dig_p1: u16,
122    pub dig_p2: i16,
123    pub dig_p3: i16,
124    pub dig_p4: i16,
125    pub dig_p5: i16,
126    pub dig_p6: i16,
127    pub dig_p7: i16,
128    pub dig_p8: i16,
129    pub dig_p9: i16,
130    // BME280 only
131    pub dig_h1: u8,
132    pub dig_h2: i16,
133    pub dig_h3: u8,
134    pub dig_h4: i16,
135    pub dig_h5: i16,
136    pub dig_h6: i8,
137}
138
139impl CalibrationData {
140    /// Placeholder used until `init` reads the real values from the device.
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    fn from_raw(raw: &[u8]) -> Self {
146        CalibrationData {
147            dig_t1: u16::from_le_bytes([raw[0], raw[1]]),
148            dig_t2: i16::from_le_bytes([raw[2], raw[3]]),
149            dig_t3: i16::from_le_bytes([raw[4], raw[5]]),
150            dig_p1: u16::from_le_bytes([raw[6], raw[7]]),
151            dig_p2: i16::from_le_bytes([raw[8], raw[9]]),
152            dig_p3: i16::from_le_bytes([raw[10], raw[11]]),
153            dig_p4: i16::from_le_bytes([raw[12], raw[13]]),
154            dig_p5: i16::from_le_bytes([raw[14], raw[15]]),
155            dig_p6: i16::from_le_bytes([raw[16], raw[17]]),
156            dig_p7: i16::from_le_bytes([raw[18], raw[19]]),
157            dig_p8: i16::from_le_bytes([raw[20], raw[21]]),
158            dig_p9: i16::from_le_bytes([raw[22], raw[23]]),
159            // BME280 only
160            dig_h1: raw[25],
161            dig_h2: i16::from_le_bytes([raw[26], raw[27]]),
162            dig_h3: raw[28],
163            dig_h4: i16::from_le_bytes([raw[29], raw[30] & 0x0F]),
164            dig_h5: i16::from_le_bytes([raw[30] >> 4, raw[31]]),
165            dig_h6: raw[32] as i8,
166        }
167    }
168}
169
170#[derive(Debug)]
171pub struct Measurements {
172    /// in 1/100 DegC
173    pub temperature: i32,
174    /// in 1/100 pascal
175    pub pressure: u32,
176    /// in 1/100 %RH
177    pub humidity: u32,
178}
179
180impl Measurements {
181    pub fn temperature_celsius(&self) -> f32 {
182        self.temperature as f32 / 100.0
183    }
184
185    pub fn pressure_hpa(&self) -> f32 {
186        self.pressure as f32 / 100.0 / 100.0
187    }
188
189    pub fn pressure_pa(&self) -> u32 {
190        self.pressure / 100
191    }
192
193    pub fn humidity_percent(&self) -> f32 {
194        self.humidity as f32 / 100.0
195    }
196}
197
198// - MARK: Async driver
199
200/// Async BME280 driver, compatible with BMP280
201pub struct BME280<I2C: embedded_hal_async::i2c::I2c> {
202    addr: u8,
203    i2c: I2C,
204    pub is_bme280: bool,
205    pub calib: CalibrationData,
206}
207
208impl<I2C: embedded_hal_async::i2c::I2c> BME280<I2C> {
209    pub fn new(i2c: I2C, addr: u8) -> Self {
210        Self {
211            addr,
212            i2c,
213            is_bme280: true,
214            calib: CalibrationData::new(),
215        }
216    }
217    pub fn new_primary(i2c: I2C) -> Self {
218        Self::new(i2c, ADDRESS)
219    }
220
221    pub async fn init(&mut self) -> Result<(), Error<I2C::Error>> {
222        let chip_id = self.read_reg(regs::CHIP_ID).await?;
223
224        if chip_id == CHIP_ID_BME280 || chip_id == CHIP_ID_BMP280 {
225            // BME280 or BMP280
226            self.is_bme280 = chip_id == CHIP_ID_BME280;
227        } else {
228            return Err(Error::InvalidDevice);
229        }
230
231        // `CONTROL_WRITES` carries the required order and the reason for it.
232        for (reg, value) in CONTROL_WRITES {
233            self.write_reg(reg, value).await?;
234        }
235
236        let mut raw = [0u8; 38];
237        self.read_regs(regs::CALIB_00, &mut raw).await?;
238
239        self.calib = CalibrationData::from_raw(&raw);
240
241        Ok(())
242    }
243
244    /// soft reset
245    pub async fn reset(&mut self, mut delay: impl DelayNs) -> Result<(), Error<I2C::Error>> {
246        self.write_reg(regs::RESET, 0xB6).await?;
247
248        delay.delay_ms(10).await;
249        Ok(())
250    }
251
252    pub async fn read_raw_temperature(&mut self) -> Result<i32, Error<I2C::Error>> {
253        let mut buf = [0u8; 3];
254        self.read_regs(regs::TEMP_MSB, &mut buf).await?;
255
256        let temp_msb = buf[0] as i32;
257        let temp_lsb = buf[1] as i32;
258        let temp_xlsb = buf[2] as i32;
259
260        Ok((temp_msb << 12) | (temp_lsb << 4) | (temp_xlsb >> 4))
261    }
262
263    pub async fn read_raw_pressure(&mut self) -> Result<i32, Error<I2C::Error>> {
264        let mut buf = [0u8; 3];
265        self.read_regs(regs::PRESS_MSB, &mut buf).await?;
266
267        let press_msb = buf[0] as i32;
268        let press_lsb = buf[1] as i32;
269        let press_xlsb = buf[2] as i32;
270
271        Ok((press_msb << 12) | (press_lsb << 4) | (press_xlsb >> 4))
272    }
273
274    pub async fn read_raw_humidity(&mut self) -> Result<i32, Error<I2C::Error>> {
275        if !self.is_bme280 {
276            return Err(Error::UnsupportedMeasurement);
277        }
278
279        let mut buf = [0u8; 2];
280        self.read_regs(regs::HUM_MSB, &mut buf).await?;
281
282        let hum_msb = buf[0] as i32;
283        let hum_lsb = buf[1] as i32;
284
285        Ok((hum_msb << 8) | hum_lsb)
286    }
287
288    /// Trigger a measurement, wait for the device to finish it, then read the
289    /// compensated result.
290    ///
291    /// **Waiting here is the whole point.** Until a conversion completes, the
292    /// BME280's data registers hold `0x80000` - its 20-bit "measurement skipped"
293    /// marker - and those placeholder bytes decode through the compensation
294    /// maths to values that look *plausible* rather than obviously wrong: about
295    /// 2.4 degC low, and a pressure about a **third** low, because `t_fine` is
296    /// derived from the bogus temperature. Versions before 0.1.1 read the
297    /// registers straight after `init` and returned exactly that, with no error
298    /// and no other symptom.
299    ///
300    /// The sequence is therefore:
301    ///
302    /// 1. write `mode = forced`, so exactly one conversion runs;
303    /// 2. wait the datasheet's measurement time;
304    /// 3. confirm `status.measuring` has cleared, as a belt-and-braces check;
305    /// 4. read the whole pressure/temperature/humidity block in **one burst**,
306    ///    as Bosch's `bme280_get_sensor_data` does, so the three values always
307    ///    come from the same conversion.
308    ///
309    /// Step 2 is a fixed wait rather than an immediate poll on purpose: right
310    /// after the write the device may not have set `measuring` yet, so polling
311    /// straight away can see "not measuring" and read the *previous* result.
312    ///
313    /// `delay` paces steps 2 and 3. The driver programs x1 oversampling on all
314    /// three channels, which the datasheet's measurement-time formula puts at
315    /// about 9.3 ms.
316    pub async fn read_measurement(&mut self, mut delay: impl DelayNs) -> Result<Measurements, Error<I2C::Error>> {
317        self.start_forced_measurement().await?;
318        self.wait_for_measurement(&mut delay).await?;
319
320        let mut raw = [0u8; regs::DATA_LEN];
321        self.read_regs(regs::DATA_MSB, &mut raw).await?;
322
323        Ok(self.compensate(&raw))
324    }
325
326    /// Write `mode = forced`, keeping the x1 oversampling programmed by `init`.
327    async fn start_forced_measurement(&mut self) -> Result<(), Error<I2C::Error>> {
328        self.write_reg(regs::CTRL_MEAS, CTRL_MEAS_FORCED).await
329    }
330
331    /// Wait out the conversion, then verify it really finished.
332    async fn wait_for_measurement(&mut self, delay: &mut impl DelayNs) -> Result<(), Error<I2C::Error>> {
333        // The datasheet's measurement-time formula at x1/x1/x1 is ~9.3 ms.
334        delay.delay_ms(MEASUREMENT_TIME_MS).await;
335
336        let mut extra = 0;
337        while self.read_reg(regs::STATUS).await? & regs::STATUS_MEASURING != 0 {
338            if extra >= MEASUREMENT_POLL_LIMIT_MS {
339                return Err(Error::Timeout);
340            }
341            delay.delay_ms(1).await;
342            extra += 1;
343        }
344        Ok(())
345    }
346
347    /// Decode the 8-byte `press | temp | hum` block and compensate it.
348    ///
349    /// Field order follows Bosch's `parse_sensor_data`.
350    fn compensate(&self, raw: &[u8; regs::DATA_LEN]) -> Measurements {
351        let adc_p = ((raw[0] as i32) << 12) | ((raw[1] as i32) << 4) | ((raw[2] as i32) >> 4);
352        let adc_t = ((raw[3] as i32) << 12) | ((raw[4] as i32) << 4) | ((raw[5] as i32) >> 4);
353        let adc_h = ((raw[6] as i32) << 8) | (raw[7] as i32);
354
355        // Returns temperature in DegC, resolution is 0.01 DegC.
356        // t_fine carries fine temperature as global value
357        let (t_fine, t) = convert_temperature(adc_t, &self.calib);
358
359        // Pressure in Q24.8 Pa; converted to centi-pascal below.
360        let p = convert_pressure(adc_p, t_fine, &self.calib);
361        let p = p * 100 / 256;
362
363        // BME280 only
364        let mut h = 0;
365        if self.is_bme280 {
366            let h0 = convert_humidity(adc_h, t_fine, &self.calib);
367
368            // convert Q22.10 to centi
369            h = h0 * 100 / 1024;
370        }
371
372        Measurements {
373            temperature: t,
374            pressure: p as u32,
375            humidity: h,
376        }
377    }
378
379    pub async fn read_reg(&mut self, reg: u8) -> Result<u8, Error<I2C::Error>> {
380        let mut buf = [0u8; 1];
381        self.i2c.write_read(self.addr, &[reg], &mut buf).await?;
382        Ok(buf[0])
383    }
384
385    pub async fn write_reg(&mut self, reg: u8, val: u8) -> Result<(), Error<I2C::Error>> {
386        self.i2c.write(self.addr, &[reg, val]).await?;
387        Ok(())
388    }
389
390    pub async fn read_regs(&mut self, reg: u8, buf: &mut [u8]) -> Result<(), Error<I2C::Error>> {
391        self.i2c.write_read(self.addr, &[reg], buf).await?;
392        Ok(())
393    }
394}
395
396// - MARK: Helper functions
397
398/// Returns temperature in DegC, resolution is 0.01 DegC. Output value of “5123” equals 51.23 DegC.
399/// t_fine carries fine temperature as global value
400/// Returns (t_fine, t)
401#[inline]
402fn convert_temperature(adc_t: i32, calib_data: &CalibrationData) -> (i32, i32) {
403    let var1 = (((adc_t >> 3) - ((calib_data.dig_t1 as i32) << 1)) * (calib_data.dig_t2 as i32)) >> 11;
404    let var2 = (((((adc_t >> 4) - (calib_data.dig_t1 as i32)) * ((adc_t >> 4) - (calib_data.dig_t1 as i32))) >> 12)
405        * (calib_data.dig_t3 as i32))
406        >> 14;
407
408    let t_fine = var1 + var2;
409
410    let t = (t_fine * 5 + 128) >> 8;
411
412    (t_fine, t)
413}
414
415/// Returns pressure in Pa as unsigned 32 bit integer in Q24.8 format (24 integer bits and 8 fractional bits).
416/// Output value of “24674867” represents 24674867/256 = 96386.2 Pa = 963.862 hPa
417// NOTE: i32 overflows
418#[inline]
419fn convert_pressure(adc_p: i32, t_fine: i32, calib_data: &CalibrationData) -> i64 {
420    let mut var1 = t_fine as i64 - 128000;
421    let mut var2 = var1 * var1 * calib_data.dig_p6 as i64;
422    var2 += (var1 * calib_data.dig_p5 as i64) << 17;
423    var2 += (calib_data.dig_p4 as i64) << 35;
424    var1 = ((var1 * var1 * calib_data.dig_p3 as i64) >> 8) + ((var1 * calib_data.dig_p2 as i64) << 12);
425    var1 = (((1i64 << 47) + var1) * (calib_data.dig_p1 as i64)) >> 33;
426
427    if var1 == 0 {
428        0
429    } else {
430        let mut p = 1048576 - adc_p as i64;
431        p = (((p << 31) - var2) * 3125) / var1;
432        var1 = (calib_data.dig_p9 as i64 * (p >> 13) * (p >> 13)) >> 25;
433        var2 = (calib_data.dig_p8 as i64 * p) >> 19;
434
435        p = ((p + var1 + var2) >> 8) + ((calib_data.dig_p7 as i64) << 4);
436        p
437    }
438}
439
440/// Returns Q22.10 format
441#[inline]
442fn convert_humidity(adc_h: i32, t_fine: i32, calib_data: &CalibrationData) -> u32 {
443    let dig_h1 = calib_data.dig_h1 as i32;
444    let dig_h2 = calib_data.dig_h2 as i32;
445    let dig_h3 = calib_data.dig_h3 as i32;
446    let dig_h4 = calib_data.dig_h4 as i32;
447    let dig_h5 = calib_data.dig_h5 as i32;
448    let dig_h6 = calib_data.dig_h6 as i32;
449
450    let v_x1_u32r = t_fine - 76800;
451    let v_x1_u32r = ((((adc_h << 14) - (dig_h4 << 20) - (dig_h5 * v_x1_u32r)) + 16384) >> 15)
452        * (((((((v_x1_u32r * (dig_h6)) >> 10) * (((v_x1_u32r * dig_h3) >> 11) + 32768)) >> 10) + 2097152) * dig_h2
453            + 8192)
454            >> 14);
455    let v_x1_u32r = v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * dig_h1) >> 4);
456
457    // limit check
458
459    let v_x1_u32r = i32::min(v_x1_u32r, 419430400);
460    let v_x1_u32r = i32::max(v_x1_u32r, 0);
461
462    (v_x1_u32r >> 12) as u32
463}