Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Time

std/time is the cross-target time API. The same source code works on MCU targets and future host targets.

Sleeping

use std/time

time.sleep_ms(1000)        // sleep 1 second
time.sleep_us(500)         // sleep 500 microseconds

These are blocking calls. On MCU targets, they lower through the hardware timer. The CPU is not spinning; most MCU implementations use WFE/WFI or timer interrupts internally.

Measuring Time

use std/time

let start = time.now()    // Instant

do_work()

let elapsed = start.elapsed()    // Duration

Duration

use std/time

let d1 = time.Duration.from_millis(250)
let d2 = time.Duration.from_micros(1500)
let d3 = time.Duration.from_secs(5)

let ms = d1.as_millis()    // u64
let us = d1.as_micros()    // u64

Timeout Pattern

use std/time

let deadline = time.now().add(time.Duration.from_millis(500))

while not sensor.data_ready() {
    if time.now().after(deadline) {
        return Err("sensor timeout")
    }
    time.sleep_ms(1)
}

Notes on MCU vs. Host

std/time provides the same API everywhere:

  • On MCU targets, time.now() uses the hardware timer. On RP2040, this is the 64-bit timer running from a 1 MHz reference.
  • On host targets (future), time.now() uses OS monotonic clock facilities.
  • micro/timer is reserved for direct hardware timer/alarm/counter control. Use std/time for ordinary sleep and measurement.

Do and Don’t

// Do: use std/time for ordinary sleep and time measurement
time.sleep_ms(100)
let start = time.now()

// Do: use Duration values to express time quantities clearly
let timeout = time.Duration.from_millis(500)

// Avoid: busy-loop delays; use time.sleep_ms/us instead
// while counter < 1_000_000 { counter += 1 }  // imprecise and burns CPU

// Avoid: micro/timer for ordinary delays; that is for hardware timer control