#timer #clock #delay #no-std

no-std embedded-timers

Softwaretimers and -delays (ms/us) based on a Clock implementation

1 unstable release

0.2.0 Feb 16, 2024

#688 in Embedded development


Used in coap-zero

OLFL-1.3

23KB
331 lines

embedded-timers

This crate provides Softwaretimers and -delays bases on a Clock implementation.

Those Timers are implementing the embedded-hal Timer traits to be easily usable for application and driver code.

Usage

The user has to provide a Clock implementation like:

#[derive(Debug)]
pub struct MilliSecondClock;

impl embedded_timers::clock::Clock for MilliSecondClock {
    fn try_now(
        &self,
    ) -> Result<embedded_timers::clock::Instant, embedded_timers::clock::ClockError> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap();

        Ok(now)
    }
}

The time base of the actual clock implementation will determinate the time base for all delays and timers.

Delay

From the clock, a delay can be crated. This will perform a busy waiting delay.

use embedded_timers::clock::Clock;
use embedded_hal::blocking::delay::DelayMs;
#[derive(Debug)]
pub struct MilliSecondClock;


let clock = MilliSecondClock;
let mut delay = clock.new_delay();

loop {
    println!("This shows every second");
    delay.delay_ms(1000_u32);
}

Timer

The crate provides a convenient timer interface with functionality to check if the timer is_running or is_expired and how much duration_left.

use embedded_timers::clock::Clock;
use embedded_timers::Timer;
use embedded_hal::timer::CountDown;
#[derive(Debug)]
pub struct MilliSecondClock;

let clock = MilliSecondClock;
let mut timer = clock.new_timer();

timer.start(std::time::Duration::from_secs(1));

loop {
    if let Ok(expired) = timer.is_expired() {
        if expired {
            println!("This shows every second");
            timer.start(std::time::Duration::from_secs(1));
        }
    }
}

The embedded_timers::Timer also implements embedded_hal::timer::CountDown as this is a common interface for embedded timers.

use embedded_timers::clock::Clock;
use embedded_timers::Timer;
use embedded_hal::timer::CountDown;
use embedded_hal::blocking::delay::DelayMs;
#[derive(Debug)]
pub struct MilliSecondClock;

let clock = MilliSecondClock;
let mut timer = clock.new_timer();
let mut delay = clock.new_delay();

timer.start(std::time::Duration::from_secs(1));

loop {
    match timer.wait() {
        Err(nb::Error::WouldBlock) => {
            println!("Timer still running");
            delay.delay_ms(50_u32);
        }
        Err(_) => panic!("TIMER ERROR"),
        Ok(_) => {
            println!("This shows every second");
            timer.start(std::time::Duration::from_secs(1));
        }
    }
}

License

Open Logistics Foundation License
Version 1.3, January 2023

See the LICENSE file in the top-level directory.

Contact

Fraunhofer IML Embedded Rust Group - embedded-rust@iml.fraunhofer.de

Dependencies

~71KB