1
+ use cramium_api:: I2cApi ;
2
+ use cramium_api:: I2cResult ;
3
+ use cram_hal_service:: I2c ;
4
+ use std:: thread:: sleep;
5
+ use std:: time:: Duration ;
6
+
7
+ struct Bmp180Calibration {
8
+ ac1 : i16 , ac2 : i16 , ac3 : i16 ,
9
+ ac4 : u16 , ac5 : u16 , ac6 : u16 ,
10
+ b1 : i16 , b2 : i16 ,
11
+ mb : i16 , mc : i16 , md : i16 ,
12
+ }
13
+ "bmp180_temp" => {
14
+ const BMP180_ADDR : u8 = 0x77 ;
15
+ const REG_CALIB_START : u8 = 0xAA ;
16
+ const REG_CTRL : u8 = 0xF4 ;
17
+ const REG_DATA_START : u8 = 0xF6 ;
18
+ const CMD_READ_TEMP : u8 = 0x2E ;
19
+
20
+ let mut i2c = I2c :: new ( ) ;
21
+
22
+ let mut cal_buf = [ 0u8 ; 22 ] ;
23
+ if let Err ( e) = i2c. i2c_read ( BMP180_ADDR , REG_CALIB_START , & mut cal_buf, true ) {
24
+ write ! ( ret, "Failed to read calibration data: {:?}\n " , e) . unwrap ( ) ;
25
+ return Ok ( Some ( ret) ) ;
26
+ }
27
+
28
+ // note: calibration data is Big Endian, hence the from_be_bytes
29
+ let cal = Bmp180Calibration {
30
+ ac1 : i16:: from_be_bytes ( [ cal_buf[ 0 ] , cal_buf[ 1 ] ] ) ,
31
+ ac2 : i16:: from_be_bytes ( [ cal_buf[ 2 ] , cal_buf[ 3 ] ] ) ,
32
+ ac3 : i16:: from_be_bytes ( [ cal_buf[ 4 ] , cal_buf[ 5 ] ] ) ,
33
+ ac4 : u16:: from_be_bytes ( [ cal_buf[ 6 ] , cal_buf[ 7 ] ] ) ,
34
+ ac5 : u16:: from_be_bytes ( [ cal_buf[ 8 ] , cal_buf[ 9 ] ] ) ,
35
+ ac6 : u16:: from_be_bytes ( [ cal_buf[ 10 ] , cal_buf[ 11 ] ] ) ,
36
+ b1 : i16:: from_be_bytes ( [ cal_buf[ 12 ] , cal_buf[ 13 ] ] ) ,
37
+ b2 : i16:: from_be_bytes ( [ cal_buf[ 14 ] , cal_buf[ 15 ] ] ) ,
38
+ mb : i16:: from_be_bytes ( [ cal_buf[ 16 ] , cal_buf[ 17 ] ] ) ,
39
+ mc : i16:: from_be_bytes ( [ cal_buf[ 18 ] , cal_buf[ 19 ] ] ) ,
40
+ md : i16:: from_be_bytes ( [ cal_buf[ 20 ] , cal_buf[ 21 ] ] ) ,
41
+ } ;
42
+
43
+
44
+ if let Err ( e) = i2c. i2c_write ( BMP180_ADDR , REG_CTRL , & [ CMD_READ_TEMP ] ) {
45
+ write ! ( ret, "Failed to start temp measurement: {:?}\n " , e) . unwrap ( ) ;
46
+ return Ok ( Some ( ret) ) ;
47
+ }
48
+
49
+ sleep ( Duration :: from_millis ( 5 ) ) ;
50
+
51
+ let mut temp_buffer = [ 0u8 ; 2 ] ;
52
+ if let Err ( e) = i2c. i2c_read ( BMP180_ADDR , REG_DATA_START , & mut temp_buffer, true ) {
53
+ write ! ( ret, "Failed to read temp data: {:?}\n " , e) . unwrap ( ) ;
54
+ return Ok ( Some ( ret) ) ;
55
+ }
56
+ let ut = i16:: from_be_bytes ( temp_buffer) as i32 ;
57
+
58
+ let x1 = ( ut - cal. ac6 as i32 ) * cal. ac5 as i32 >> 15 ;
59
+ let x2 = ( cal. mc as i32 * 2048 ) / ( x1 + cal. md as i32 ) ;
60
+ let b5 = x1 + x2;
61
+ let temp = ( ( b5 + 8 ) >> 4 ) as f32 / 10.0 ;
62
+
63
+ write ! ( ret, "BMP180 Temperature: {:.1}°C\n " , temp) . unwrap ( ) ;
64
+ }
0 commit comments