Skip to content

Commit

Permalink
I2C: Replace millisecond with microsecond timeouts
Browse files Browse the repository at this point in the history
  • Loading branch information
9names committed Jan 11, 2024
1 parent dcd6c9f commit 103da0f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
5 changes: 5 additions & 0 deletions src/delay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ impl McycleDelay {
let elapsed_cycles = Self::cycles_since(previous_cycle_count);
(elapsed_cycles * 1000) / self.core_frequency as u64
}

pub fn us_since(&mut self, previous_cycle_count: u64) -> u64 {
let elapsed_cycles = Self::cycles_since(previous_cycle_count);
(elapsed_cycles * 1_000_000) / self.core_frequency as u64
}
}

// embedded-hal 1.0 traits
Expand Down
14 changes: 7 additions & 7 deletions src/i2c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ pub struct I2c<I2C, PINS> {
i2c: I2C,
/// sda and scl pins for this i2c interface
pins: PINS,
/// timeout (in milliseconds)
/// timeout (in microseconds)
timeout: u16,
}

Expand Down Expand Up @@ -178,8 +178,8 @@ where
(self.i2c, self.pins)
}

/// Set the timeout (in milliseconds) when waiting for fifo (rx and tx).
/// This defaults to 2048
/// Set the timeout (in microseconds) when waiting for fifo (rx and tx).
/// This defaults to 2000us (2 milliseconds)
pub fn set_timeout(&mut self, timeout: u16) {
self.timeout = timeout;
}
Expand Down Expand Up @@ -246,7 +246,7 @@ where
for value in tmp.iter_mut() {
let start_time = McycleDelay::get_cycle_count();
while self.i2c.i2c_fifo_config_1.read().rx_fifo_cnt().bits() == 0 {
if delay.ms_since(start_time) > self.timeout.into() {
if delay.us_since(start_time) > self.timeout.into() {
return Err(Error::Timeout);
}
}
Expand Down Expand Up @@ -315,7 +315,7 @@ where
for value in tmp.iter() {
let start_time = McycleDelay::get_cycle_count();
while self.i2c.i2c_fifo_config_1.read().tx_fifo_cnt().bits() == 0 {
if delay.ms_since(start_time) > self.timeout.into() {
if delay.us_since(start_time) > self.timeout.into() {
return Err(Error::Timeout);
}
}
Expand All @@ -327,15 +327,15 @@ where
let start_time = McycleDelay::get_cycle_count();
while self.i2c.i2c_fifo_config_1.read().tx_fifo_cnt().bits() < 2 {
// wait for write fifo to be empty
if delay.ms_since(start_time) > self.timeout.into() {
if delay.us_since(start_time) > self.timeout.into() {
return Err(Error::Timeout);
}
}

let start_time = McycleDelay::get_cycle_count();
while self.i2c.i2c_bus_busy.read().sts_i2c_bus_busy().bit_is_set() {
// wait for transfer to finish
if delay.ms_since(start_time) > self.timeout.into() {
if delay.us_since(start_time) > self.timeout.into() {
return Err(Error::Timeout);
}
}
Expand Down

0 comments on commit 103da0f

Please sign in to comment.