Skip to content

Commit

Permalink
Use named constants to clarify delay-stepdown behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesmunns committed Nov 30, 2023
1 parent a8c72e9 commit ca8ef80
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions embedded-hal/src/delay.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
//! Delays.
/// Nanoseconds per microsecond
const NANOS_PER_MICRO: u32 = 1_000;
/// Nanoseconds per millisecond
const NANOS_PER_MILLI: u32 = 1_000_000;

/// Delay with up to nanosecond precision.
pub trait DelayNs {
/// Pauses execution for at minimum `ns` nanoseconds. Pause can be longer
Expand All @@ -9,22 +14,30 @@ pub trait DelayNs {
/// Pauses execution for at minimum `us` microseconds. Pause can be longer
/// if the implementation requires it due to precision/timing issues.
fn delay_us(&mut self, mut us: u32) {
while us > 4_294_967 {
us -= 4_294_967;
self.delay_ns(4_294_967_000);
const MAX_MICROS: u32 = u32::MAX / NANOS_PER_MICRO;

// Avoid potential overflow if micro -> micro conversion is too large
while us > MAX_MICROS {
us -= MAX_MICROS;
self.delay_ns(MAX_MICROS * NANOS_PER_MICRO);
}
self.delay_ns(us * 1_000);

self.delay_ns(us * NANOS_PER_MICRO);
}

/// Pauses execution for at minimum `ms` milliseconds. Pause can be longer
/// if the implementation requires it due to precision/timing issues.
#[inline]
fn delay_ms(&mut self, mut ms: u32) {
while ms > 4294 {
ms -= 4294;
self.delay_ns(4_294_000_000);
const MAX_MILLIS: u32 = u32::MAX / NANOS_PER_MILLI;

// Avoid potential overflow if milli -> micro conversion is too large
while ms > MAX_MILLIS {
ms -= MAX_MILLIS;
self.delay_ns(MAX_MILLIS * NANOS_PER_MILLI);
}
self.delay_ns(ms * 1_000_000);

self.delay_ns(ms * NANOS_PER_MILLI);
}
}

Expand Down

0 comments on commit ca8ef80

Please sign in to comment.