Skip to content

Commit

Permalink
fix i2c-nonblocking
Browse files Browse the repository at this point in the history
  • Loading branch information
dotcypress committed Jan 7, 2025
1 parent 72d7218 commit 3598a5d
Show file tree
Hide file tree
Showing 3 changed files with 181 additions and 160 deletions.
36 changes: 35 additions & 1 deletion src/i2c/blocking.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! I2C
use crate::gpio::*;
use crate::i2c::config::Config;
use crate::i2c::{self, Error, I2c, I2cDirection, I2cExt, SCLPin, SDAPin};
use crate::i2c::{
self, Error, I2c, I2cDirection, I2cExt, I2cPeripheral, I2cPeripheralEvent, SCLPin, SDAPin,
};
use crate::rcc::*;
use crate::stm32::{I2C1, I2C2};

Expand Down Expand Up @@ -517,6 +519,38 @@ macro_rules! i2c {
Ok(())
}
}

impl<SDA, SCL> I2cPeripheral for I2c<$I2CX, SDA, SCL> where
SDA: SDAPin<$I2CX>,
SCL: SCLPin<$I2CX>
{
type Error = Error;

fn poll(&mut self) -> Result<Option<I2cPeripheralEvent>, Self::Error> {
self.slave_addressed().map(|event| {
event.map(|(addr, dir)| match dir {
I2cDirection::MasterWriteSlaveRead => I2cPeripheralEvent::Read(addr as _),
I2cDirection::MasterReadSlaveWrite => I2cPeripheralEvent::Write(addr as _),
})
})
}

fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
self.slave_sbc(false);
self.slave_read(buf)
}

fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
self.slave_sbc(true);
self.slave_write(buf)
}

fn flush(&mut self) -> Result<(), Self::Error> {
self.clear_irq(i2c::Event::Rxne);
self.clear_irq(i2c::Event::AddressMatch);
Ok(())
}
}
}
}

Expand Down
14 changes: 14 additions & 0 deletions src/i2c/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,17 @@ pub struct I2c<I2C, SDA, SCL> {
data: [u8; 255], // during transfer the driver will be the owner of the buffer
current_direction: I2cDirection,
}

pub enum I2cPeripheralEvent {
Read(u8),
Write(u8),
}

pub trait I2cPeripheral {
type Error;

fn poll(&mut self) -> Result<Option<I2cPeripheralEvent>, Self::Error>;
fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error>;
fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
fn flush(&mut self) -> Result<(), Self::Error>;
}
Loading

0 comments on commit 3598a5d

Please sign in to comment.