Skip to content

Commit

Permalink
Merge pull request #55 from s7rul/development
Browse files Browse the repository at this point in the history
Implemented Transactional for TWI (I²C)
  • Loading branch information
michalfita authored Jul 30, 2023
2 parents 8b3258d + ad4b0b3 commit c9fef17
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- [Integration](https://crates.io/crates/mcan-core) with the
[`mcan`](https://crates.io/crates/mcan) crate.
- Implementation of blocking::i2c::Transactional trait from [embedded-hal](https://crates.io/crates/embedded-hal) for TWI device.

### Changed

Expand Down
56 changes: 56 additions & 0 deletions hal/src/serial/twi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,59 @@ impl<M: TwiMeta> blocking::i2c::WriteRead for Twi<M> {
Ok(())
}
}

#[derive(PartialEq)]
enum TransactionalState {
Reading,
Writing,
Uninitialized,
}

impl<M: TwiMeta> blocking::i2c::Transactional for Twi<M> {
type Error = TwiError;

fn exec<'a>(
&mut self,
address: u8,
operations: &mut [blocking::i2c::Operation<'a>],
) -> Result<(), Self::Error> {
let mut state = TransactionalState::Uninitialized;

for operation in operations {
match operation {
blocking::i2c::Operation::Read(buffer) => {
// If not already reading setup for read.
if state != TransactionalState::Reading {
self.setup_transaction(address, TwiAction::Read);
self.start_transaction();
state = TransactionalState::Reading;
}

self.read(buffer)?;
}
blocking::i2c::Operation::Write(buffer) => {
// If not already writing setup for write.
if state != TransactionalState::Writing {
self.setup_transaction(address, TwiAction::Write);
state = TransactionalState::Writing;
}

self.write(buffer)?;
}
}
}

// end transaction
match state {
TransactionalState::Reading => {
self.finalize_transaction(TwiAction::Read)?;
}
TransactionalState::Writing => {
self.finalize_transaction(TwiAction::Write)?;
}
TransactionalState::Uninitialized => (), // Since no operation was done do not finalize transaction.
}

Ok(())
}
}

0 comments on commit c9fef17

Please sign in to comment.