|
| 1 | +#![no_std] |
| 2 | +/** |
| 3 | + * This example shows a repeated timer combined with reading and displaying the current time in |
| 4 | + * clock ticks. |
| 5 | + **/ |
| 6 | +use core::fmt::Write; |
| 7 | +use libtock::console::Console; |
| 8 | +use libtock::result::TockResult; |
| 9 | +use libtock::timer::DriverContext; |
| 10 | +use libtock::timer::Duration; |
| 11 | +use libtock::Drivers; |
| 12 | + |
| 13 | +const DELAY_MS: usize = 500; |
| 14 | + |
| 15 | +#[libtock::main] |
| 16 | +async fn main() -> TockResult<()> { |
| 17 | + let Drivers { |
| 18 | + mut timer_context, |
| 19 | + console_driver, |
| 20 | + .. |
| 21 | + } = libtock::retrieve_drivers()?; |
| 22 | + let mut console = console_driver.create_console(); |
| 23 | + |
| 24 | + let mut previous_ticks = None; |
| 25 | + |
| 26 | + for i in 0.. { |
| 27 | + print_now(&mut console, &mut timer_context, &mut previous_ticks, i)?; |
| 28 | + let mut driver = timer_context.create_timer_driver(); |
| 29 | + let timer_driver = driver.activate()?; |
| 30 | + |
| 31 | + timer_driver.sleep(Duration::from_ms(DELAY_MS)).await?; |
| 32 | + } |
| 33 | + |
| 34 | + Ok(()) |
| 35 | +} |
| 36 | + |
| 37 | +fn print_now( |
| 38 | + console: &mut Console, |
| 39 | + timer_context: &mut DriverContext, |
| 40 | + previous_ticks: &mut Option<isize>, |
| 41 | + i: usize, |
| 42 | +) -> TockResult<()> { |
| 43 | + let mut timer_with_callback = timer_context.with_callback(|_, _| {}); |
| 44 | + let timer = timer_with_callback.init()?; |
| 45 | + let current_clock = timer.get_current_clock()?; |
| 46 | + let ticks = current_clock.num_ticks(); |
| 47 | + let frequency = timer.clock_frequency().hz(); |
| 48 | + writeln!( |
| 49 | + console, |
| 50 | + "[{}] Waited roughly {}. Now is {} = {:#010x} ticks ({:?} ticks since last time at {} Hz)", |
| 51 | + i, |
| 52 | + PrettyTime::from_ms(i * DELAY_MS), |
| 53 | + PrettyTime::from_ms(current_clock.ms_f64() as usize), |
| 54 | + ticks, |
| 55 | + previous_ticks.map(|previous| ticks - previous), |
| 56 | + frequency |
| 57 | + )?; |
| 58 | + *previous_ticks = Some(ticks); |
| 59 | + Ok(()) |
| 60 | +} |
| 61 | + |
| 62 | +struct PrettyTime { |
| 63 | + mins: usize, |
| 64 | + secs: usize, |
| 65 | + ms: usize, |
| 66 | +} |
| 67 | + |
| 68 | +impl PrettyTime { |
| 69 | + fn from_ms(ms: usize) -> PrettyTime { |
| 70 | + PrettyTime { |
| 71 | + ms: ms % 1000, |
| 72 | + secs: (ms / 1000) % 60, |
| 73 | + mins: ms / (60 * 1000), |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl core::fmt::Display for PrettyTime { |
| 79 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 80 | + if self.mins != 0 { |
| 81 | + write!(f, "{}m", self.mins)? |
| 82 | + } |
| 83 | + write!(f, "{}.{:03}s", self.secs, self.ms) |
| 84 | + } |
| 85 | +} |
0 commit comments