2

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};
Hardware
  • 33
  • 5

2 Answers2

1

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?

IcyTv
  • 405
  • 4
  • 12
1

Initially looking at various modules and structs within the stm32f1xx_hal, I wasn't sure how to initialize structs that I needed to pass to functions. While looking at the MonoTimer struct provided from an answer to my question I found DWT. I can see the total elapsed CPU cycles with DWT. I could use this with MonoTimer (I think) to get an implementation closer than I was initially looking for. But having the CPU cycle count is actaully more beneficial for my use case.

Here's the relevant code I'm using to get CPU cycle count:

// Get access to device and core peripherals
let dp = pac::Peripherals::take().unwrap();
let mut cp = cortex_m::Peripherals::take().unwrap();

// Enabled cycle counter
cp.DCB.enable_trace();
cp.DWT.enable_cycle_counter();


// Output cycles
loop {
    let cycles = DWT::cycle_count();
    rprintln!("{:?}", cycles);
    delay.delay_ms(1000u16);
}
Hardware
  • 33
  • 5