-
Currently there seems to be no support for a delay between a I2C write and read which is pretty common for sensors I guess? Is this the right way of doing it? pub struct Ags02ma<I2C, D> {
pub i2c: I2C,
pub delay: D
}
#[derive(Debug)]
pub enum Ags02maError {
BusWriteError,
BusReadError
}
impl <I2C, D> Ags02ma<I2C, D> where I2C : Read + Write, D : DelayMs<u16> {
pub fn read_gas(&mut self) -> Result<u32, Ags02maError> {
let res = self.execute(1500, &[0x20])?;
Ok(res * 100)
}
pub fn read_tvoc(&mut self) -> Result<u32, Ags02maError> {
let res = self.execute(1500, &[0x11])?;
Ok(res & 0xffffff)
}
fn execute(&mut self, delay_ms: u16, cmd: &[u8]) -> Result<u32, Ags02maError> {
let mut buf = [0u8; 5];
self.i2c.write(0x1a, cmd).map_err(|_| Ags02maError::BusWriteError);
self.delay.delay_ms(delay_ms);
self.i2c.read(0x1a, &mut buf).map_err(|_| Ags02maError::BusReadError);
let mut temp: u32 = buf[0] as u32;
temp <<= 8;
temp |= buf[1] as u32;
temp <<= 8;
temp |= buf[2] as u32;
temp <<= 8;
temp |= buf[3] as u32;
return Ok(temp);
}
} This for the Ags02ma sensor. In the docs you should delay the read for 1500ms 😱 I also saw working async-hal (and also I2C) .. Not sure if the delay is blocking now? It would be nice if the microcontroller gets time to run something else (hence async) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I guess writing to the register triggers the measurement which might take up to 1500ms - then it's safe to read. It's a common pattern and I see no obvious problem with the code. The blocking delay could be replaced with an async delay. We don't have support for async I2C yet but it should be fine to mix async/sync here. Even with a blocking delay interrupts will still be served |
Beta Was this translation helpful? Give feedback.
I guess writing to the register triggers the measurement which might take up to 1500ms - then it's safe to read. It's a common pattern and I see no obvious problem with the code.
The blocking delay could be replaced with an async delay. We don't have support for async I2C yet but it should be fine to mix async/sync here.
Even with a blocking delay interrupts will still be served