2023-06-06 05:21:29 +02:00
|
|
|
use i2cdev::core::{I2CMessage, I2CTransfer};
|
2023-03-09 06:20:25 +01:00
|
|
|
use i2cdev::linux::{LinuxI2CDevice, LinuxI2CMessage};
|
2023-06-04 03:04:16 +02:00
|
|
|
use std::thread;
|
|
|
|
use std::time::Duration;
|
|
|
|
|
2023-03-09 06:20:25 +01:00
|
|
|
pub fn read_from_bus(
|
|
|
|
i2c_device: &str,
|
|
|
|
slave_address: u16,
|
2023-06-06 00:19:43 +02:00
|
|
|
memory_address: u8,
|
2023-03-09 06:20:25 +01:00
|
|
|
data_length: usize,
|
|
|
|
) -> Result<Vec<u8>, std::io::Error> {
|
|
|
|
let mut data = vec![0; data_length];
|
|
|
|
|
|
|
|
let mut dev = LinuxI2CDevice::new(i2c_device, slave_address)?;
|
|
|
|
let mut msgs = [
|
|
|
|
// Address to read from
|
2023-06-06 00:19:43 +02:00
|
|
|
LinuxI2CMessage::write(&[memory_address]),
|
2023-03-09 06:20:25 +01:00
|
|
|
// Read data into buffer
|
|
|
|
LinuxI2CMessage::read(&mut data),
|
|
|
|
];
|
|
|
|
|
|
|
|
match dev.transfer(&mut msgs) {
|
|
|
|
Ok(_) => Ok(data),
|
|
|
|
Err(e) => Err(e.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write_to_bus(
|
|
|
|
i2c_device: &str,
|
|
|
|
slave_address: u16,
|
2023-06-06 05:21:29 +02:00
|
|
|
memory_address: u8,
|
2023-03-09 06:20:25 +01:00
|
|
|
data: &[u8],
|
|
|
|
) -> Result<(), std::io::Error> {
|
|
|
|
let mut dev = LinuxI2CDevice::new(i2c_device, slave_address)?;
|
|
|
|
|
2023-06-04 03:04:16 +02:00
|
|
|
// Write 8 bytes at a time
|
2023-06-06 05:21:29 +02:00
|
|
|
for (i, chunk) in data.chunks_exact(8).enumerate() {
|
2023-06-04 03:04:16 +02:00
|
|
|
// Memory address
|
2023-06-06 05:21:29 +02:00
|
|
|
let address = memory_address + (i as u8) * 8;
|
2023-06-04 03:04:16 +02:00
|
|
|
let mut msgs = [
|
|
|
|
// Address to write to
|
2023-06-06 05:21:29 +02:00
|
|
|
LinuxI2CMessage::write(&[address]),
|
2023-06-04 03:04:16 +02:00
|
|
|
// Write data to chip
|
2023-06-06 05:21:29 +02:00
|
|
|
LinuxI2CMessage::write(chunk),
|
2023-06-04 03:04:16 +02:00
|
|
|
];
|
|
|
|
|
|
|
|
dev.transfer(&mut msgs)?;
|
|
|
|
|
|
|
|
thread::sleep(Duration::from_millis(20));
|
2023-06-06 00:19:43 +02:00
|
|
|
}
|
2023-06-04 03:04:16 +02:00
|
|
|
|
|
|
|
Ok(())
|
2023-03-09 06:20:25 +01:00
|
|
|
}
|