Skip to content

Instantly share code, notes, and snippets.

@japaric

japaric/i2c.rs Secret

Last active November 20, 2016 00:34
Show Gist options
  • Save japaric/1dd1c2ad532bf238d7debab9b6b2a97c to your computer and use it in GitHub Desktop.
Save japaric/1dd1c2ad532bf238d7debab9b6b2a97c to your computer and use it in GitHub Desktop.
enum Address {
U7(u8),
U10(u16),
}
pub trait I2c {
type Err;
type Sess: Session<Err = Sess::Err>;
/// "Connect" to a slave I2C device
///
/// NOTE(impl) this takes care of sending START and STOP
fn connect<F>(&mut self,
address: Address,
session: F)
-> Result<(), Self::Err>
where F: FnOnce(&mut Self::Sess) -> Result<(), Self::Err>;
}
/// An I2C "session"
pub trait Session {
type Err;
/// Reads a single byte from the slave
fn read(&mut self) -> Result<u8, Self::Err>;
/// Reads `buffer.len()` bytes from the slave into `buffer`
fn read_exact(&mut self, buffer: &mut [u8]) -> Result<(), Self::Err>;
/// Writes/sends a single byte to the slave
fn write(&mut self, byte: u8) -> Result<(), Self::Err>;
/// Writes/sends `bytes` to the slave
fn write_all(&mut self, bytes: &[u8]) -> Result<(), Self::Err>;
}
fn main() -> Result<(), _> {
let mut i2c: impl I2c = ..;
// Read the acceleration from an accelerometer
let mut buffer = [0; 6];
i2c.connect(Address::U7(ACCELEROMETER_SLAVE_ADDRESS), |sess| {
sess.write(ACCELEROMETER_REGISTER_ADDRESS)?;
sess.read_exact(&mut buffer)
})?;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment