-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbme280.rs
More file actions
299 lines (245 loc) · 9.85 KB
/
bme280.rs
File metadata and controls
299 lines (245 loc) · 9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! Driver for the Bosch BME280 temperature, humidity and air pressure sensor.
//!
//! ## Compatibility
//! **This driver only supports the BME280**. Other models like the BMP280, BME680 are **not** supported.
//!
//! These sensors work over the I2C protocol.
use super::EnvironmentSensor;
use crate::{
re_esp,
sysc::{OsError, OsResult},
};
use esp_idf_svc::hal::i2c::I2cDriver;
use pwmp_client::pwmp_msg::aliases::{AirPressure, Humidity, Temperature};
/// Driver handle for Bosch BME280 sensors.
pub struct BoschME280<'s> {
/// I2C driver handle for communication with the sensor.
i2c: I2cDriver<'s>,
/// I2C address of the sensor.
addr: u8,
/// Factory calibration data read from the sensor.
cal: CalibrationData,
}
/// Commands for BME280 sensors
#[derive(Clone, Copy)]
enum Command {
/// Read calibration data part 1
ReadCalibrationPart1,
/// Read calibration data part 2
ReadCalibrationPart2,
/// Set humidity control register
SetHumidityCtlRegister(u8),
/// Set temperature control register
SetMeasurementCtlRegister(u8),
/// Read the device ID register
ReadIdRegister,
/// Read the first data register.
ReadMeasurementsStartRegister,
}
/// Sensor calibration data.
///
/// Since every sensor has a slightly different accuracy, a calibration step is performed at the factory.
/// The calibration data is them stored in the sensor's memory after calibration.
///
/// The values are used to compensate the raw measurements read from the sensor, which results in more accurate readings.
/// The compensation formulas are provided in the BME280 datasheet.
#[derive(Default)]
struct CalibrationData {
// Temperature
t1: f32,
t2: f32,
t3: f32,
// Pressure
p1: f32,
p2: f32,
p3: f32,
p4: f32,
p5: f32,
p6: f32,
p7: f32,
p8: f32,
p9: f32,
// Humidity
h1: f32,
h2: f32,
h3: f32,
h4: f32,
h5: f32,
h6: f32,
}
impl<'s> BoschME280<'s> {
/// Known default address
pub const DEV_ADDRS: [u8; 2] = [0x76, 0x77];
const BUS_TIMEOUT: u32 = 1000;
/// Initialize the driver with the given I2C driver handle.
pub fn new_with_driver(driver: I2cDriver<'s>, addr: u8) -> Result<Self, OsError> {
log::debug!("Loading driver");
let mut dev = Self {
i2c: driver,
addr,
cal: CalibrationData::default(),
};
/*
* Basic setup
*
* The BMx280 sensors require some additional setup to work.
*/
// read the factory calibration data
dev.read_calibration_data()?;
// set temperature and humidity oversampling to 16x
// also set the reading mode to normal
dev.write(Command::SetHumidityCtlRegister(0b0000_0101))?;
dev.write(Command::SetMeasurementCtlRegister(0b1011_0111))?;
match dev.model()? {
Some(model) => log::debug!("Detected '{model}'"),
None => log::warn!("Device model is unknown and may not be supported"),
}
Ok(dev)
}
/// Detect the sensor model by reading the device ID register.
fn model(&mut self) -> OsResult<Option<&'static str>> {
let mut buffer = [0u8; 1];
self.write_read(Command::ReadIdRegister, &mut buffer)?;
match buffer[0] {
0x60 => Ok(Some("BME280")),
_ => Ok(None),
}
}
/// Read the factory calibration data from the sensor.
fn read_calibration_data(&mut self) -> OsResult<()> {
let mut calib_buf_1 = [0u8; 26]; // 0x88 to 0xA1
self.write_read(Command::ReadCalibrationPart1, &mut calib_buf_1)?;
let mut calib_buf_2 = [0u8; 7]; // 0xE1 to 0xE7
self.write_read(Command::ReadCalibrationPart2, &mut calib_buf_2)?;
self.cal = CalibrationData {
t1: f32::from(u16::from_le_bytes([calib_buf_1[0], calib_buf_1[1]])),
t2: f32::from(i16::from_le_bytes([calib_buf_1[2], calib_buf_1[3]])),
t3: f32::from(i16::from_le_bytes([calib_buf_1[4], calib_buf_1[5]])),
p1: f32::from(u16::from_le_bytes([calib_buf_1[6], calib_buf_1[7]])),
p2: f32::from(i16::from_le_bytes([calib_buf_1[8], calib_buf_1[9]])),
p3: f32::from(i16::from_le_bytes([calib_buf_1[10], calib_buf_1[11]])),
p4: f32::from(i16::from_le_bytes([calib_buf_1[12], calib_buf_1[13]])),
p5: f32::from(i16::from_le_bytes([calib_buf_1[14], calib_buf_1[15]])),
p6: f32::from(i16::from_le_bytes([calib_buf_1[16], calib_buf_1[17]])),
p7: f32::from(i16::from_le_bytes([calib_buf_1[18], calib_buf_1[19]])),
p8: f32::from(i16::from_le_bytes([calib_buf_1[20], calib_buf_1[21]])),
p9: f32::from(i16::from_le_bytes([calib_buf_1[22], calib_buf_1[23]])),
h1: f32::from(calib_buf_1[25]),
h2: f32::from(i16::from_le_bytes([calib_buf_2[0], calib_buf_2[1]])),
h3: f32::from(calib_buf_2[2]),
h4: f32::from(i16::from(calib_buf_2[3]) << 4 | (i16::from(calib_buf_2[4]) & 0x0F)),
h5: f32::from(i16::from(calib_buf_2[5]) << 4 | (i16::from(calib_buf_2[4]) >> 4)),
h6: f32::from(calib_buf_2[6].cast_signed()),
};
Ok(())
}
/// Read the raw measurements from the sensor.
///
/// These are not final and need to be compensated using the calibration data to get accurate readings.
#[allow(clippy::cast_precision_loss)]
fn read_raw_measurements(&mut self) -> OsResult<(f32, f32, f32)> {
let mut buffer = [0; 8];
self.write_read(Command::ReadMeasurementsStartRegister, &mut buffer)?;
let raw_p = (u32::from(buffer[0]) << 12
| u32::from(buffer[1]) << 4
| u32::from(buffer[2]) >> 4) as f32;
let raw_t = (u32::from(buffer[3]) << 12
| u32::from(buffer[4]) << 4
| u32::from(buffer[5]) >> 4) as f32;
let raw_h = (u32::from(buffer[6]) << 8 | u32::from(buffer[7])) as f32;
Ok((raw_t, raw_h, raw_p))
}
/// Calculate the `t_fine` value from the raw temperature measurement, which is used for compensation of all measurements.
const fn calc_t_fine(&self, raw_t: f32) -> f32 {
let var1 = (raw_t / 16384.0 - self.cal.t1 / 1024.0) * self.cal.t2;
let var2 = ((raw_t / 131_072.0 - self.cal.t1 / 8192.0)
* (raw_t / 131_072.0 - self.cal.t1 / 8192.0))
* self.cal.t3;
var1 + var2
}
/// Send a non-returning command to the sensor.
///
/// If the command returns data, use [`write_read()`](Self::write_read) instead.
fn write(&mut self, command: Command) -> OsResult<()> {
let (cmd, len) = command.serialize();
re_esp!(
self.i2c.write(self.addr, &cmd[..len], Self::BUS_TIMEOUT),
I2c
)
}
/// Send a command to the sensor and read the response into the provided buffer.
///
/// If the command does not return data, use [`write()`](Self::write) instead.
fn write_read(&mut self, command: Command, buffer: &mut [u8]) -> OsResult<()> {
let (cmd, len) = command.serialize();
re_esp!(
self.i2c
.write_read(self.addr, &cmd[..len], buffer, Self::BUS_TIMEOUT,),
I2c
)
}
}
impl EnvironmentSensor for BoschME280<'_> {
fn read_temperature(&mut self) -> OsResult<Temperature> {
let raw_t = self.read_raw_measurements()?.0;
// temperature compensation
let t_fine = self.calc_t_fine(raw_t);
let temperature_c = t_fine / 5120.0;
Ok(temperature_c)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn read_humidity(&mut self) -> OsResult<Humidity> {
let (raw_t, raw_h, _) = self.read_raw_measurements()?;
// humidity compensation
let t_fine = self.calc_t_fine(raw_t);
let mut h = t_fine - 76800.0;
h = (raw_h - self.cal.h4.mul_add(64.0, self.cal.h5 / 16384.0 * h))
* (self.cal.h2 / 65536.0
* (self.cal.h6 / 67_108_864.0 * h)
.mul_add((self.cal.h3 / 67_108_864.0).mul_add(h, 1.0), 1.0));
h = h * (1.0 - self.cal.h1 * h / 524_288.0);
h = h.floor().clamp(0., 100.);
Ok(h as u8)
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn read_air_pressure(&mut self) -> OsResult<Option<AirPressure>> {
let (raw_t, _, raw_p) = self.read_raw_measurements()?;
// pressure compensation
let t_fine = self.calc_t_fine(raw_t);
let mut p_var1 = (t_fine / 2.0) - 64000.0;
let mut p_var2 = p_var1 * p_var1 * self.cal.p6 / 32768.0;
p_var2 += p_var1 * self.cal.p5 * 2.0;
p_var2 = self.cal.p4.mul_add(65536.0, p_var2 / 4.0);
p_var1 = self
.cal
.p2
.mul_add(p_var1, self.cal.p3 * p_var1 * p_var1 / 524_288.0)
/ 524_288.0;
p_var1 = (1.0 + p_var1 / 32768.0) * self.cal.p1;
let pressure_pa = if p_var1 > 0.0 {
let mut p = 1_048_576.0 - raw_p;
p = (p - (p_var2 / 4096.0)) * 6250.0 / p_var1;
p_var1 = self.cal.p9 * p * p / 2_147_483_648.0;
p_var2 = p * self.cal.p8 / 32768.0;
p + (p_var1 + p_var2 + self.cal.p7) / 16.0
} else {
0.0
};
let hpa = pressure_pa / 100.0;
let hpa = hpa.floor().clamp(0., 65535.0) as u16;
Ok(Some(hpa))
}
}
impl Command {
/// Serialize the command into raw bytes and a length.
const fn serialize(self) -> ([u8; 2], usize) {
match self {
Self::ReadCalibrationPart1 => ([0x88, 0], 1),
Self::ReadCalibrationPart2 => ([0xE1, 0], 1),
Self::SetHumidityCtlRegister(d) => ([0xF2, d], 2),
Self::SetMeasurementCtlRegister(d) => ([0xF4, d], 2),
Self::ReadIdRegister => ([0xD0, 0], 1),
Self::ReadMeasurementsStartRegister => ([0xF7, 0], 1),
}
}
}