Skip to content

Commit

Permalink
Adapt to new I2C bus/device interface
Browse files Browse the repository at this point in the history
  • Loading branch information
eldruin committed Aug 18, 2022
1 parent 1ac9d6f commit d08b39c
Show file tree
Hide file tree
Showing 4 changed files with 192 additions and 145 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ spi = ["spidev"]
default = [ "gpio_cdev", "gpio_sysfs", "i2c", "spi" ]

[dependencies]
embedded-hal = "=1.0.0-alpha.8"
embedded-hal = {git = "https://github.com/Dirbaio/embedded-hal", branch="i2c-bus-device"}
embedded-hal-bus = {git= "https://github.com/eldruin/embedded-hal", branch="i2c-exclusive-device"}
gpio-cdev = { version = "0.5.1", optional = true }
sysfs_gpio = { version = "0.6.1", optional = true }
i2cdev = { version = "0.5.1", optional = true }
Expand Down
26 changes: 17 additions & 9 deletions examples/transactional-i2c.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use embedded_hal::i2c::blocking::{I2c, Operation as I2cOperation};
use linux_embedded_hal::I2cdev;
use embedded_hal::i2c::{
blocking::{I2cBus, I2cBusBase as _, I2cDevice},
Direction,
};
use embedded_hal_bus::i2c::blocking::ExclusiveDevice;
use linux_embedded_hal::I2cBus as LinuxI2cBus;

const ADDR: u8 = 0x12;

Expand All @@ -9,24 +13,28 @@ struct Driver<I2C> {

impl<I2C> Driver<I2C>
where
I2C: I2c,
I2C: I2cDevice,
I2C::Bus: I2cBus,
{
pub fn new(i2c: I2C) -> Self {
Driver { i2c }
}

fn read_something(&mut self) -> Result<u8, I2C::Error> {
let mut read_buffer = [0];
let mut ops = [
I2cOperation::Write(&[0xAB]),
I2cOperation::Read(&mut read_buffer),
];
self.i2c.transaction(ADDR, &mut ops).and(Ok(read_buffer[0]))
self.i2c.transaction(|bus| {
bus.start(ADDR, Direction::Write)?;
bus.write(&[0xAB])?;
bus.start(ADDR, Direction::Read)?;
bus.read(&mut read_buffer)
})?;
Ok(read_buffer[0])
}
}

fn main() {
let dev = I2cdev::new("/dev/i2c-1").unwrap();
let bus = LinuxI2cBus::new("/dev/i2c-1").unwrap();
let dev = ExclusiveDevice::new(bus);
let mut driver = Driver::new(dev);
let value = driver.read_something().unwrap();
println!("Read value: {}", value);
Expand Down
Loading

0 comments on commit d08b39c

Please sign in to comment.