tof_control/device/
tmp1075.rs

1#![allow(unused)]
2use i2cdev::core::*;
3use i2cdev::linux::{LinuxI2CDevice, LinuxI2CError};
4
5// Register
6const TEMP: u16 = 0x00; // Temperature Result Register
7const CFGR: u16 = 0x01; // Configuration Register
8const LLIM: u16 = 0x02; // Low Limit Register
9const HLIM: u16 = 0x03; // High Limit Register
10                        // Configuration Register
11const CONFIG_OS: u16 = 0x80A0; // One-shot conversion mode
12const CONFIG_R_35: u16 = 0x60A0; // 35 ms conversion rate (Read-only)
13const CONFIG_F_1: u16 = 0x00A0; // 1 fault
14const CONFIG_F_2: u16 = 0x08A0; // 2 fault
15const CONFIG_F_4: u16 = 0x10A0; // 4 fault
16const CONFIG_F_6: u16 = 0x18A0; // 6 fault
17const CONFIG_POL_L: u16 = 0x00A0; // Active low ALERT pin
18const CONFIG_POL_H: u16 = 0x04A0; // Active high ALERT pin
19const CONFIG_TM_CM: u16 = 0x00A0; // ALERT pin functions in comparator mode
20const CONFIG_TM_IM: u16 = 0x02A0; // ALERT pin functions in interrupt mode
21const CONFIG_SD_CC: u16 = 0x00A0; // Device is in continuos conversion
22const CONFIG_SD_SM: u16 = 0x01A0; // Device is in shutdown conversion
23
24pub struct TMP1075 {
25    bus: u8,
26    address: u16,
27}
28
29impl TMP1075 {
30    pub fn new(bus: u8, address: u16) -> Self {
31        Self { bus, address }
32    }
33    pub fn config(&self) -> Result<(), LinuxI2CError> {
34        let mut dev = LinuxI2CDevice::new(&format!("/dev/i2c-{}", self.bus), self.address)?;
35        let config_reg = CONFIG_R_35 | CONFIG_F_1 | CONFIG_POL_L | CONFIG_TM_CM | CONFIG_SD_CC;
36
37        dev.smbus_write_i2c_block_data(CFGR as u8, &config_reg.to_be_bytes())
38    }
39    pub fn read(&self) -> Result<f32, LinuxI2CError> {
40        let mut dev = LinuxI2CDevice::new(&format!("/dev/i2c-{}", self.bus), self.address)?;
41        let temp_raw = dev.smbus_read_i2c_block_data(TEMP as u8, 2)?;
42        let mut temp_adc = (((temp_raw[0] as u16) << 4) | ((temp_raw[1] as u16) >> 4)) & 0xFFF;
43
44        Ok(self.adc_to_celsius(temp_adc))
45    }
46    fn adc_to_celsius(&self, mut adc: u16) -> f32 {
47        let mut sign: f32 = 1.0;
48        if adc >= 0x800 {
49            sign = -1.0;
50            adc = 0xFFF - adc;
51        }
52
53        sign * adc as f32 * 0.0625
54    }
55}