From a4371e9544f284927aae3b0de0ff5318f81acc80 Mon Sep 17 00:00:00 2001 From: Caleb Jamison Date: Thu, 9 Feb 2023 19:22:06 -0500 Subject: [PATCH 1/2] Add from_hz function for Duration. --- embassy-time/src/duration.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/embassy-time/src/duration.rs b/embassy-time/src/duration.rs index d3c6f42a9..846a9c3d5 100644 --- a/embassy-time/src/duration.rs +++ b/embassy-time/src/duration.rs @@ -81,6 +81,11 @@ impl Duration { } } + /// Creates a duration corresponding to the specified Hz. + pub const fn from_hz(hz: u64) -> Duration { + Duration { ticks: TICK_HZ / hz } + } + /// Adds one Duration to another, returning a new Duration or None in the event of an overflow. pub fn checked_add(self, rhs: Duration) -> Option { self.ticks.checked_add(rhs.ticks).map(|ticks| Duration { ticks }) From bd7b3bd455fc5946a3944bd931acfdf255929cb6 Mon Sep 17 00:00:00 2001 From: Caleb Jamison Date: Thu, 9 Feb 2023 20:57:27 -0500 Subject: [PATCH 2/2] Clamp ticks to 1 and round to nearest. --- embassy-time/src/duration.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/embassy-time/src/duration.rs b/embassy-time/src/duration.rs index 846a9c3d5..9d0bab2dd 100644 --- a/embassy-time/src/duration.rs +++ b/embassy-time/src/duration.rs @@ -82,8 +82,17 @@ impl Duration { } /// Creates a duration corresponding to the specified Hz. + /// NOTE: Giving this function a hz >= the TICK_HZ of your platform will clamp the Duration to 1 + /// tick. Doing so will not deadlock, but will certainly not produce the desired output. pub const fn from_hz(hz: u64) -> Duration { - Duration { ticks: TICK_HZ / hz } + let ticks = { + if hz >= TICK_HZ { + 1 + } else { + (TICK_HZ + hz / 2) / hz + } + }; + Duration { ticks } } /// Adds one Duration to another, returning a new Duration or None in the event of an overflow.