bmp280_rust_no_std 0.1.0

A no_std async BMP280 driver for ESP32 using embassy and esp-hal
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use libm::pow;
use esp_hal::i2c::master::I2c;
use embassy_time::{Duration, Timer};



#[derive(Debug, Clone, Copy)]
#[repr(u8)] // <--- We need this to make sure it detects it as a u8 and not a isize
pub enum BMPADDRESSES {
    Bmp280RegisterDigT1 = 0x88 as u8,
    Bmp280RegisterDigT2 = 0x8A as u8,
    Bmp280RegisterDigT3 = 0x8C as u8,
    Bmp280RegisterDigP1 = 0x8E as u8,
    Bmp280RegisterDigP2 = 0x90 as u8,
    Bmp280RegisterDigP3 = 0x92 as u8,
    Bmp280RegisterDigP4 = 0x94 as u8,
    Bmp280RegisterDigP5 = 0x96 as u8,
    Bmp280RegisterDigP6 = 0x98 as u8,
    Bmp280RegisterDigP7 = 0x9A as u8,
    Bmp280RegisterDigP8 = 0x9C as u8,
    Bmp280RegisterDigP9 = 0x9E as u8,
    Bmp280RegisterChipid = 0xD0 as u8,
    Bmp280RegisterVersion = 0xD1 as u8,
    Bmp280RegisterSoftreset = 0xE0 as u8,
    Bmp280RegisterCal26 = 0xE1 as u8,
    /**< R calibration = 0xE1-0xF0 */
    Bmp280RegisterStatus = 0xF3 as u8,
    Bmp280RegisterControl = 0xF4 as u8,
    Bmp280RegisterConfig = 0xF5 as u8,
    Bmp280RegisterPressuredata = 0xF7 as u8,
    Bmp280RegisterTempdata = 0xFA as u8,
}
#[derive(Debug, Clone, Copy)]
#[repr(u8)] // <--- We need this to make sure it detects it as a u8 and not a isize
pub enum SensorSampling {
    /** No over-sampling. */
    SamplingNone = 0x00,
    /** 1x over-sampling. */
    SamplingX1 = 0x01,
    /** 2x over-sampling. */
    SamplingX2 = 0x02,
    /** 4x over-sampling. */
    SamplingX4 = 0x03,
    /** 8x over-sampling. */
    SamplingX8 = 0x04,
    /** 16x over-sampling. */
    SamplingX16 = 0x05,
}

/** Operating mode for the sensor. */
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum SensorMode {
    /** Sleep mode. */
    ModeSleep = 0x00,
    /** Forced mode. */
    ModeForced = 0x01,
    /** Normal mode. */
    ModeNormal = 0x03,
    /** Software reset. */
    ModeSoftResetCode = 0xB6,
}

/** Filtering level for sensor data. */
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum SensorFilter {
    /** No filtering. */
    FilterOff = 0x00,
    /** 2x filtering. */
    FilterX2 = 0x01,
    /** 4x filtering. */
    FilterX4 = 0x02,
    /** 8x filtering. */
    FilterX8 = 0x03,
    /** 16x filtering. */
    FilterX16 = 0x04,
}

/** Standby duration in ms */
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum StandbyDuration {
    /** 1 ms standby. */
    StandbyMs1 = 0x00,
    /** 62.5 ms standby. */
    StandbyMs63 = 0x01,
    /** 125 ms standby. */
    StandbyMs125 = 0x02,
    /** 250 ms standby. */
    StandbyMs250 = 0x03,
    /** 500 ms standby. */
    StandbyMs500 = 0x04,
    /** 1000 ms standby. */
    StandbyMs1000 = 0x05,
    /** 2000 ms standby. */
    StandbyMs2000 = 0x06,
    /** 4000 ms standby. */
    StandbyMs4000 = 0x07,
}

pub struct bmp_uart {
    i2c: I2c<'static, esp_hal::Async>,
    chip_address: u8,

    dig_t1: u16,
    dig_t2: i16,
    dig_t3: i16,

    dig_p1: u16,
    dig_p2: i16,
    dig_p3: i16,
    dig_p4: i16,
    dig_p5: i16,
    dig_p6: i16,
    dig_p7: i16,
    dig_p8: i16,
    dig_p9: i16,
    t_fine: i32,

    sensor_mode: SensorMode,
    temp_sampling: SensorSampling,
    pressure_sampling: SensorSampling,
    filter: SensorFilter,
    duration: StandbyDuration,
}

impl bmp_uart {
    pub async fn new(i2c: I2c<'static, esp_hal::Async>, chip_address: u8) -> Self {
        Self {
            i2c,
            chip_address,
            dig_p1: 0,
            dig_p2: 0,
            dig_p3: 0,
            dig_p4: 0,
            dig_p5: 0,
            dig_p6: 0,
            dig_p7: 0,
            dig_p8: 0,
            dig_p9: 0,
            dig_t1: 0,
            dig_t2: 0,
            dig_t3: 0,
            t_fine: 0,
            // Default values
            sensor_mode: SensorMode::ModeNormal,
            temp_sampling: SensorSampling::SamplingX2,
            pressure_sampling: SensorSampling::SamplingX4,
            filter: SensorFilter::FilterX2,
            duration: StandbyDuration::StandbyMs125,
        }
    }
    // async fn print_self_data(&mut self) {
    //     //   info!("sel.i2c:{} self.chip_address:{} ",self.i2c,self.chip_address);
    //     // info!("Chip address: {=u8:#x} as u8", self.chip_address); // https://defmt.ferrous-systems.com/hints read about how to print a u8 as hex value
    // }

    pub async fn check_chip(&mut self) -> bool {
        Timer::after(Duration::from_millis(30)).await;

        let mut read_buff = [0u8; 1];
        let chip_reading = self
            .i2c
            .write_read_async(
                self.chip_address,
                &[BMPADDRESSES::Bmp280RegisterChipid as u8],
                &mut read_buff,
            )
            .await;
        // info!("the read buffer is {}",read_buff);
        match chip_reading {
            Ok(_) => {
                // todo!()
            }
            Err(e) => {
                // info!("Error {}", e)
            }
        }
        if read_buff[0] != 0x58 {
            // checking if the chips address that is being read it same as the given one
            // info!("Chip id doesn't match check your sensor and hardware");
            return false;
        } else {
            // info!("true");
            return true;
        }
        // true
    }
    pub async fn change_settings(
        &mut self,
        sensor_mode: SensorMode,
        temperature_sampling: SensorSampling,
        pressure_sampling: SensorSampling,
        filter: SensorFilter,
        duration: StandbyDuration,
    ) {
        self.sensor_mode = sensor_mode;
        self.temp_sampling = temperature_sampling;
        self.pressure_sampling = pressure_sampling;
        self.filter = filter;
        self.duration = duration;
    }

    pub async fn begin(&mut self) -> bool {
        if !self.check_chip().await {
            // todo!()
            false
            // Here we just won't do anything since the check_chip() will say if there is an error
        } else {
            self.read_coefficents().await;
            self.set_sampling().await;
            Timer::after(Duration::from_millis(100)).await;
            true
        }
    }
    async fn write_8(&mut self, register: u8, value: u8) {
        let mut buffer = [0u8; 2];

        buffer[0] = register; // putting the register in the 1st part of the buffer
        buffer[1] = value; // putting the value in the second part of the buffer

        self.i2c
            .write_async(self.chip_address as u8, &mut buffer)
            .await; // NEED TO ADD A PROPER ERROR HANDLING SYSTEM
    }

    async fn read_8(&mut self) -> u8 {
        // returning 0 if there is a problem

        let mut read_8_byte_buffer = [0u8; 1];
        let read_8_bytes = self
            .i2c
            .write_read_async(
                self.chip_address,
                &[BMPADDRESSES::Bmp280RegisterChipid as u8],
                &mut read_8_byte_buffer,
            )
            .await;
        match read_8_bytes {
            Ok(_) => read_8_byte_buffer[0],
            Err(e) => {
                // info!("An error accured error:{}", e);
                0
            }
        }
    }

    async fn read_16(&mut self, register: u8) -> u16 {
        // returning 0 if there is a problem
        let mut buffer = [0u8; 2];

        let operation = self
            .i2c
            .write_read_async(self.chip_address, &[register], &mut buffer)
            .await;
        match operation {
            Ok(_) => (buffer[0] as u16) << 8 | (buffer[1] as u16),
            Err(e) => {
                // info!("An error accured error:{}", e);
                0
            }
        }
    }

    async fn read_16_le(&mut self, register: u8) -> u16 {
        let temp = self.read_16(register).await;
        return (temp >> 8) | (temp << 8);
    }

    async fn read_s16(&mut self, register: u8) -> i16 {
        self.read_16(register).await as i16
    }

    async fn read_s16_le(&mut self, register: u8) -> i16 {
        self.read_16_le(register).await as i16
    }

    async fn read_24(&mut self, register: u8) -> u32 {
        let mut buffer = [0u8; 3];
        buffer[0] = register;

        let operation = self
            .i2c
            .write_read_async(self.chip_address, &[buffer[0]], &mut buffer)
            .await;
        match operation {
            Ok(_) => (buffer[0] as u32) << 16 | (buffer[1] as u32) << 8 | (buffer[2] as u32),
            Err(e) => {
                // info!("An error accured error:{}", e);
                0
            }
        }
    }

    async fn read_coefficents(&mut self) {
        // todo!();
        // continue from here line 229 https://github.com/adafruit/Adafruit_BMP280_Library/blob/master/Adafruit_BMP280.cpp

        // Temperature registers
        self.dig_t1 = self
            .read_16_le(BMPADDRESSES::Bmp280RegisterDigT1 as u8)
            .await;
        // reading s16_le
        self.dig_t2 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigT2 as u8)
            .await;
        self.dig_t3 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigT3 as u8)
            .await;

        self.dig_p1 = self
            .read_16_le(BMPADDRESSES::Bmp280RegisterDigP1 as u8)
            .await;
        // reading s16_le
        self.dig_p2 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP2 as u8)
            .await;
        self.dig_p3 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP3 as u8)
            .await;
        self.dig_p4 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP4 as u8)
            .await;
        self.dig_p5 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP5 as u8)
            .await;
        self.dig_p6 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP6 as u8)
            .await;
        self.dig_p7 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP7 as u8)
            .await;
        self.dig_p8 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP8 as u8)
            .await;
        self.dig_p9 = self
            .read_s16_le(BMPADDRESSES::Bmp280RegisterDigP9 as u8)
            .await;
    }

    async fn set_sampling(&mut self) {
        // todo!();

        // everything is hard coded so no
        /*
        *   _measReg.mode = mode;
               _measReg.osrs_t = tempSampling;
               _measReg.osrs_p = pressSampling;

               _configReg.filter = filter;
               _configReg.t_sb = duration;
        *
        * */

        /*
                    C++ CODE BELOW ME IS TRANSLATED TO ctrl_get
                     unsigned int get() { return (osrs_t << 5) | (osrs_p << 2) | mode; }
        --------------------------------------------------------------------------------------------------
                    C++ CODE BELOW ME IS TRANSLATED TO config_get
                     unsigned int get() { return (t_sb << 5) | (filter << 2) | spi3w_en; }
                  */

        let config_get: u8 = ((self.duration as u8) << 5) | ((self.filter as u8) << 2);
        let ctrl_get: u8 = ((self.temp_sampling as u8) << 5)
            | ((self.pressure_sampling as u8) << 2)
            | (self.sensor_mode as u8); // ← add this

        self.write_8(BMPADDRESSES::Bmp280RegisterConfig as u8, config_get)
            .await;
        self.write_8(BMPADDRESSES::Bmp280RegisterControl as u8, ctrl_get)
            .await;

        //NEED TO IMPLEMENT A .get to bitshift numbs since it I'm having troubles  i need to shift all the config data into a u8 and pass it as an arugment
        // CONTINUE FROM LINE 139
        // CONTINUE WITH SET SAMPLING YES I MADE AN ERROR BY CHOICE
        // https://github.com/adafruit/Adafruit_BMP280_Library/blob/master/Adafruit_BMP280.cpp#L125
    }

    pub async fn read_temperature(&mut self) -> Option<f32> {
        // returning None if there was an error

        // if no snesor id return NONE
        if self.check_chip().await == false {
            return None;
        }
        let mut adc_t: i32 = (self
            .read_24(BMPADDRESSES::Bmp280RegisterTempdata as u8)
            .await) as i32;
        adc_t >>= 4;

        let var_1 = ((adc_t >> 3) - ((self.dig_t1 as i32) << 1)) * (self.dig_t2 as i32) >> 11;

        let var_2 =
            (((adc_t >> 4) - (self.dig_t1 as i32)) * ((adc_t >> 4) - (self.dig_t1 as i32))) >> 12;

        let var_2 = (var_2 * (self.dig_t3 as i32)) >> 14;

        let t_fine = var_1 + var_2;
        self.t_fine = t_fine; // making sure the self.t_fine is the same so I can call in the read_pressure part

        let t: f32 = ((t_fine * 5 + 128) >> 8) as f32;
        // info!("temperature :{}",t/100.);
        Some(t / 100.)
    }

    pub async fn read_pressure(&mut self) -> Option<f32> {
        let temp = self.read_temperature().await;
        match temp {
            Some(_data) => {} // we just wanted to make sure if there was an error with chip read it will tell it forward
            None => {
                return None; // returning None if there is an error
            }
        }

        let mut adc_p = (self
            .read_24(BMPADDRESSES::Bmp280RegisterPressuredata as u8)
            .await) as i64; // PROBLEM MIGHT BE HERE
        adc_p >>= 4;

        let var_1 = (self.t_fine as i64) - 128000;
        let var_2 = var_1 * var_1 * (self.dig_p6 as i64);
        let var_2 = var_2 + ((var_1 * (self.dig_p5 as i64)) << 17);
        let var_2 = var_2 + ((self.dig_p4 as i64) << 35);
        let var_1 =
            ((var_1 * var_1 * (self.dig_p3 as i64) >> 8) + (var_1 * (self.dig_p2 as i64) << 12));
        let var_1 = ((((1 as i64) << 47) + var_1) * (self.dig_p1 as i64)) >> 33;

        if var_1 == 0 {
            return Some(0.); // avoid exception caused by division by zero
        }
        let p: i64 = 1048576 - adc_p;
        let p: i64 = (((p << 31) - var_2) * 3125) / var_1;
        let var_1 = ((self.dig_p9 as i64) * (p >> 13) * (p >> 13)) >> 25;
        let var_2 = ((self.dig_p8 as i64) * p) >> 19;
        let p: i64 = ((p + var_1 + var_2) >> 8) + ((self.dig_p7 as i64) << 4);

        Some((p as f32) / 256.)
    }
    /*
    Tthe sea_level_hpa means the hpa value of the sea level of the country or region
    add hpa value according to the sea level

    */
    pub async fn read_altitude(&mut self, sea_level_hpa: f32) -> Option<f64> {
        let temp = self.read_pressure().await;
        match temp {
            Some(pressure) => {
                let pressure = pressure / 100.;
                let altitude = 44330. * (1.0 - pow((pressure / sea_level_hpa) as f64, 0.1903)); // using libm pow function here libm is a no std libary
                Some(altitude) // returning altitude in meters
            } // we just wanted to make sure if there was an error with chip read it will tell it forward
            None => {
                return None; // returning None if there is an error
            }
        }
    }
}