use crate::{
BitFlagsHigh, ConfigHigh, ConversionRate, Error, Register, SlaveAddr, Tmp006,
DEVICE_BASE_ADDRESS,
};
use embedded_hal::i2c;
impl ConfigHigh {
fn with_high(self, mask: u8) -> Self {
ConfigHigh {
bits: self.bits | mask,
}
}
fn with_low(self, mask: u8) -> Self {
ConfigHigh {
bits: self.bits & !mask,
}
}
}
impl Default for ConfigHigh {
fn default() -> Self {
ConfigHigh { bits: 0 }
.with_high(BitFlagsHigh::MOD)
.with_high(BitFlagsHigh::CR1)
}
}
impl<I2C, E> Tmp006<I2C>
where
I2C: i2c::I2c<Error = E>,
{
pub fn new(i2c: I2C, address: SlaveAddr) -> Self {
Tmp006 {
i2c,
address: address.addr(DEVICE_BASE_ADDRESS),
config: ConfigHigh::default(),
}
}
pub fn destroy(self) -> I2C {
self.i2c
}
pub fn enable(&mut self) -> Result<(), Error<E>> {
let config = self.config;
self.write_config(config.with_high(BitFlagsHigh::MOD))
}
pub fn disable(&mut self) -> Result<(), Error<E>> {
let config = self.config;
self.write_config(config.with_low(BitFlagsHigh::MOD))
}
pub fn reset(&mut self) -> Result<(), Error<E>> {
let config = self.config;
self.write_config(config.with_high(BitFlagsHigh::SW_RESET))?;
self.config = ConfigHigh::default();
Ok(())
}
pub fn enable_drdy_pin(&mut self) -> Result<(), Error<E>> {
let config = self.config;
self.write_config(config.with_high(BitFlagsHigh::DRDY_EN))
}
pub fn disable_drdy_pin(&mut self) -> Result<(), Error<E>> {
let config = self.config;
self.write_config(config.with_low(BitFlagsHigh::DRDY_EN))
}
pub fn set_conversion_rate(&mut self, rate: ConversionRate) -> Result<(), Error<E>> {
use crate::BitFlagsHigh as BF;
use crate::ConversionRate as CR;
let config = match rate {
CR::Cps4 => self
.config
.with_low(BF::CR2)
.with_low(BF::CR1)
.with_low(BF::CR0),
CR::Cps2 => self
.config
.with_low(BF::CR2)
.with_low(BF::CR1)
.with_high(BF::CR0),
CR::Cps1 => self
.config
.with_low(BF::CR2)
.with_high(BF::CR1)
.with_low(BF::CR0),
CR::Cps0_5 => self
.config
.with_low(BF::CR2)
.with_high(BF::CR1)
.with_high(BF::CR0),
CR::Cps0_25 => self
.config
.with_high(BF::CR2)
.with_low(BF::CR1)
.with_low(BF::CR0),
};
self.write_config(config)
}
fn write_config(&mut self, config: ConfigHigh) -> Result<(), Error<E>> {
self.i2c
.write(self.address, &[Register::CONFIG, config.bits, 0])
.map_err(Error::I2C)?;
self.config = config;
Ok(())
}
}