Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix off-by-one-tick in timer period calculation #491

Merged
merged 1 commit into from
Apr 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ macro_rules! hal {
}

/// Sets the timer's prescaler and auto reload register so that the timer will reach
/// the ARR after `ticks` amount of timer clock ticks.
/// the ARR after `ticks - 1` amount of timer clock ticks.
///
/// ```
/// // Set auto reload register to 50000 and prescaler to divide by 2.
Expand Down Expand Up @@ -567,7 +567,8 @@ fn calculate_timeout_ticks_register_values(ticks: u32) -> (u16, u16) {
// resulting in a value that always fits in 16 bits.
let psc = u16(ticks / (1 << 16)).unwrap();
// Note (unwrap): Never panics because the divisor is always such that the result fits in 16 bits.
let arr = u16(ticks / (u32(psc) + 1)).unwrap();
// Also note that the timer counts `0..=arr`, so subtract 1 to get the correct period.
let arr = u16(ticks / (u32(psc) + 1)).unwrap().saturating_sub(1);
(psc, arr)
}

Expand Down Expand Up @@ -929,17 +930,17 @@ mod tests {
#[test]
fn timeout_ticks_register_values() {
assert_eq!(calculate_timeout_ticks_register_values(0), (0, 0));
assert_eq!(calculate_timeout_ticks_register_values(50000), (0, 50000));
assert_eq!(calculate_timeout_ticks_register_values(100000), (1, 50000));
assert_eq!(calculate_timeout_ticks_register_values(65535), (0, 65535));
assert_eq!(calculate_timeout_ticks_register_values(65536), (1, 32768));
assert_eq!(calculate_timeout_ticks_register_values(50000), (0, 49999));
assert_eq!(calculate_timeout_ticks_register_values(100000), (1, 49999));
assert_eq!(calculate_timeout_ticks_register_values(65535), (0, 65534));
assert_eq!(calculate_timeout_ticks_register_values(65536), (1, 32767));
assert_eq!(
calculate_timeout_ticks_register_values(1000000),
(15, 62500)
(15, 62499)
);
assert_eq!(
calculate_timeout_ticks_register_values(u32::MAX),
(u16::MAX, u16::MAX)
(u16::MAX, u16::MAX - 1)
);
}
}
Loading