Skip to content

Commit ac64582

Browse files
dnerichardeoin
authored andcommitted
Fix off-by-one-tick in timer period calculation
1 parent 2d3653c commit ac64582

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/timer.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ macro_rules! hal {
424424
}
425425

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

@@ -929,17 +930,17 @@ mod tests {
929930
#[test]
930931
fn timeout_ticks_register_values() {
931932
assert_eq!(calculate_timeout_ticks_register_values(0), (0, 0));
932-
assert_eq!(calculate_timeout_ticks_register_values(50000), (0, 50000));
933-
assert_eq!(calculate_timeout_ticks_register_values(100000), (1, 50000));
934-
assert_eq!(calculate_timeout_ticks_register_values(65535), (0, 65535));
935-
assert_eq!(calculate_timeout_ticks_register_values(65536), (1, 32768));
933+
assert_eq!(calculate_timeout_ticks_register_values(50000), (0, 49999));
934+
assert_eq!(calculate_timeout_ticks_register_values(100000), (1, 49999));
935+
assert_eq!(calculate_timeout_ticks_register_values(65535), (0, 65534));
936+
assert_eq!(calculate_timeout_ticks_register_values(65536), (1, 32767));
936937
assert_eq!(
937938
calculate_timeout_ticks_register_values(1000000),
938-
(15, 62500)
939+
(15, 62499)
939940
);
940941
assert_eq!(
941942
calculate_timeout_ticks_register_values(u32::MAX),
942-
(u16::MAX, u16::MAX)
943+
(u16::MAX, u16::MAX - 1)
943944
);
944945
}
945946
}

0 commit comments

Comments
 (0)