1//! helper struct to calculate divider & cycles settings for timers.
2use crate::time::{Hertz, Nanoseconds};
34/// Helper type for computing cycles and divider given frequency
5#[derive(Debug, Clone, Copy)]
6pub struct TimerParams {
7pub divider: u16,
8pub cycles: u32,
9}
1011impl TimerParams {
12/// calculates TimerParams from a given frequency based timeout.
13pub fn new(timeout: Hertz, src_freq: Hertz) -> Self {
14let ticks: u32 = src_freq.to_Hz() / timeout.to_Hz().max(1);
15Self::new_from_ticks(ticks)
16 }
1718/// calculates TimerParams from a given period based timeout.
19pub fn new_ns(timeout: Nanoseconds, src_freq: Hertz) -> Self {
20let ticks: u32 =
21 (timeout.to_nanos() as u64 * src_freq.to_Hz() as u64 / 1_000_000_000_u64) as u32;
22Self::new_from_ticks(ticks)
23 }
2425fn new_from_ticks(ticks: u32) -> Self {
26let divider = ((ticks >> 16) + 1).next_power_of_two();
27let divider = match divider {
281 | 2 | 4 | 8 | 16 | 64 | 256 | 1024 => divider,
29// There are a couple of gaps, so we round up to the next largest
30 // divider; we'll need to count twice as many but it will work.
3132 => 64,
32128 => 256,
33512 => 1024,
34// Catch all case; this is lame. Would be great to detect this
35 // and fail at compile time.
36_ => 1024,
37 };
3839let cycles: u32 = ticks / divider;
4041if cycles > u16::MAX as u32 {
42panic!("cycles {} is out of range for a 16 bit counter", cycles);
43 }
4445 TimerParams {
46 divider: divider as u16,
47 cycles,
48 }
49 }
50}
5152#[cfg(test)]
53mod tests {
54use crate::fugit::{ExtU32, RateExtU32};
55use crate::timer_params::TimerParams;
5657#[test]
58fn timer_params_hz_and_us_same_1hz() {
59let tp_from_hz = TimerParams::new(1.Hz(), 48.MHz());
60let tp_from_us = TimerParams::new_ns(1_000_000.micros(), 48.MHz());
6162assert_eq!(tp_from_hz.divider, tp_from_us.divider);
63assert_eq!(tp_from_hz.cycles, tp_from_us.cycles);
64 }
6566#[test]
67fn timer_params_hz_and_us_same_3hz() {
68let tp_from_hz = TimerParams::new(3.Hz(), 48.MHz());
69let tp_from_us = TimerParams::new_ns(333_333.micros(), 48.MHz());
7071// There's some rounding error here, but it is extremely small (1 cycle
72 // difference)
73assert_eq!(tp_from_hz.divider, tp_from_us.divider);
74assert!((tp_from_hz.cycles as i32 - tp_from_us.cycles as i32).abs() <= 1);
75 }
76}