Examples · 18 of 339
18-rates
Frequency is a unit, like Duration.
tin run examples/18-rates.tin// Frequency is a unit, like Duration.
//
// `135Hz` is a Frequency and `7ms` a Duration. They turn into each other with
// `1 / x`, and a Duration times a Frequency is a plain number of cycles.
// Mixing them up is a compile error: `135Hz + 7ms`, `sleep(135Hz)`, `135Hz + 3`.
/// How a robot's control loop is scheduled.
type Loop = { name: string, rate: Frequency }
fn period(l: Loop): Duration => 1 / l.rate
fn ticksIn(l: Loop, window: Duration): int => int(floor(window * l.rate))
fn main() {
let loops = [
Loop { name: "balance", rate: 135Hz },
Loop { name: "vision", rate: 30Hz },
Loop { name: "planner", rate: 1 / 500ms },
]
for l in loops {
print("{l.name}: {l.rate}, every {period(l)}, {ticksIn(l, 2s)} ticks in 2s")
}
let fastest = loops.map(l => l.rate / 1Hz).reduce(0.0, (a, b) => max(a, b))
print("fastest: {fastest * 1Hz}")
} balance: 135Hz, every 7.407ms, 270 ticks in 2s
vision: 30Hz, every 33.333ms, 60 ticks in 2s
planner: 2Hz, every 500ms, 4 ticks in 2s
fastest: 135Hz