Skip to content

Commit 3598a5d

Browse files
committed
fix i2c-nonblocking
1 parent 72d7218 commit 3598a5d

File tree

3 files changed

+181
-160
lines changed

3 files changed

+181
-160
lines changed

src/i2c/blocking.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
//! I2C
22
use crate::gpio::*;
33
use crate::i2c::config::Config;
4-
use crate::i2c::{self, Error, I2c, I2cDirection, I2cExt, SCLPin, SDAPin};
4+
use crate::i2c::{
5+
self, Error, I2c, I2cDirection, I2cExt, I2cPeripheral, I2cPeripheralEvent, SCLPin, SDAPin,
6+
};
57
use crate::rcc::*;
68
use crate::stm32::{I2C1, I2C2};
79

@@ -517,6 +519,38 @@ macro_rules! i2c {
517519
Ok(())
518520
}
519521
}
522+
523+
impl<SDA, SCL> I2cPeripheral for I2c<$I2CX, SDA, SCL> where
524+
SDA: SDAPin<$I2CX>,
525+
SCL: SCLPin<$I2CX>
526+
{
527+
type Error = Error;
528+
529+
fn poll(&mut self) -> Result<Option<I2cPeripheralEvent>, Self::Error> {
530+
self.slave_addressed().map(|event| {
531+
event.map(|(addr, dir)| match dir {
532+
I2cDirection::MasterWriteSlaveRead => I2cPeripheralEvent::Read(addr as _),
533+
I2cDirection::MasterReadSlaveWrite => I2cPeripheralEvent::Write(addr as _),
534+
})
535+
})
536+
}
537+
538+
fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
539+
self.slave_sbc(false);
540+
self.slave_read(buf)
541+
}
542+
543+
fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
544+
self.slave_sbc(true);
545+
self.slave_write(buf)
546+
}
547+
548+
fn flush(&mut self) -> Result<(), Self::Error> {
549+
self.clear_irq(i2c::Event::Rxne);
550+
self.clear_irq(i2c::Event::AddressMatch);
551+
Ok(())
552+
}
553+
}
520554
}
521555
}
522556

src/i2c/mod.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,17 @@ pub struct I2c<I2C, SDA, SCL> {
124124
data: [u8; 255], // during transfer the driver will be the owner of the buffer
125125
current_direction: I2cDirection,
126126
}
127+
128+
pub enum I2cPeripheralEvent {
129+
Read(u8),
130+
Write(u8),
131+
}
132+
133+
pub trait I2cPeripheral {
134+
type Error;
135+
136+
fn poll(&mut self) -> Result<Option<I2cPeripheralEvent>, Self::Error>;
137+
fn read(&mut self, buf: &mut [u8]) -> Result<(), Self::Error>;
138+
fn write(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
139+
fn flush(&mut self) -> Result<(), Self::Error>;
140+
}

0 commit comments

Comments
 (0)