Search code examples
rustembeddedrust-embedded

Get elapsed time since some instant in embedded rust


I started making a program in rust, and I want to be able to get the elapsed time since some instant. Here's how the std library does it.

use std::time::{Duration, Instant};
use std::thread::sleep;

fn main() {
   let now = Instant::now();

   // we sleep for 2 seconds
   sleep(Duration::new(2, 0));
   // it prints '2'
   println!("{}", now.elapsed().as_secs());
}

I don't have std in embedded rust so how can I get around this? I'm using the stm32f1xx hal with an stm32f103c8t6. I've tried to have a look at various timer related modules in the hal, aswell as the embedded time crate. But I'm having no luck getting anything to work. Any help would be appreciated.

I've scraped together some random lines of code from things other people have done that are loosely related.

let mut counter = Timer::new(dp.TIM2, &clocks).counter_us();
counter.start(1_000_000_u32.micros()).unwrap();
let mut timer = Timer::syst(cp.SYST, &clocks);
let mut counter = Timer::counter_us(timer);

But I can't even initialize a counter without errors, even though relevant functions, structs, etc. Should all be imported.

error[E0599]: no function or associated item named `new` found for struct `Timer` in the current scope
  --> src/main.rs:87:30
   |
87 |     let mut counter = Timer::new(dp.TIM2, &clocks).counter_us();
   |                              ^^^ function or associated item not found in `Timer<_>`

use panic_halt as _;

use cortex_m_rt::entry;
use embedded_hal::digital::v2::OutputPin;
use stm32f1xx_hal as hal;
use hal::{pac, TIM2, timer::Timer, delay::Delay, prelude::*};

use rtt_target::{rprintln, rtt_init_print};

Solution

  • How does something like this sound?

    
    let some_clock = SomeClock;
    let start = some_clock.try_now().unwrap();
    
    // Do something
    
    let duration = some_clock.try_now().unwrap() - start;
    
    

    This is pretty much what the documentation shows. Do you have some struct that implements the embedded_time::Clock trait?

    Otherwise how about using the MonoTimer?