//! I2C/SPI interfaces extern crate embedded_hal as hal; use hal::blocking; use { private, Error }; /// I2C interface #[derive(Debug, Default)] pub struct I2cInterface { pub(crate) i2c: I2C, pub(crate) address : u8, } /// SPI interface #[derive(Debug, Default)] pub struct SpiInterface { pub(crate) spi: SPI, pub(crate) cs: CS } /// Write data pub trait WriteData : private::Sealed { /// Error type type Error; /// Write to an u8 register fn write_register(&mut self, register: u8, data: u16) -> Result<(), Error>; } impl WriteData for I2cInterface where I2C: blocking::i2c::Write { type Error = E; fn write_register(&mut self, register: u8, data: u16) -> Result<(), Error> { let payload: [u8; 3] = [register, (data >> 8) as u8, data as u8]; self.i2c .write(self.address, &payload) .map_err(Error::Comm) } } impl WriteData for SpiInterface where SPI: blocking::spi::Write, CS: hal::digital::OutputPin { type Error = E; fn write_register(&mut self, register: u8, data: u16) -> Result<(), Error> { self.cs.set_low(); let payload: [u8; 3] = [register + 0x80, (data >> 8) as u8, data as u8]; let result = self.spi .write(&payload) .map_err(Error::Comm); self.cs.set_high(); result } } /// Read data pub trait ReadData : private::Sealed { /// Error type type Error; /// Read an u8 register fn read_register(&mut self, register: u8) -> Result>; } impl ReadData for I2cInterface where I2C: blocking::i2c::WriteRead { type Error = E; fn read_register(&mut self, register: u8) -> Result> { let mut data = [0, 0]; self.i2c .write_read(self.address, &[register], &mut data) .map_err(Error::Comm) .and(Ok((u16::from(data[0]) << 8) | u16::from(data[1]))) } } impl ReadData for SpiInterface where SPI: blocking::spi::Transfer, CS: hal::digital::OutputPin { type Error = E; fn read_register(&mut self, register: u8) -> Result> { self.cs.set_low(); let mut data = [register, 0, 0]; let result = self.spi .transfer(&mut data) .map_err(Error::Comm); self.cs.set_high(); let result = result?; Ok((u16::from(result[0]) << 8) | u16::from(result[1])) } }