Delays

Create a time delay.

Another piece of information you will need is how to create a time delay before moving to the next row. we want the time spent switching LED lines on and off to be much shorter than the time spent waiting with LEDs on.

For loop

A first attempt to implement the delay function without using any peripherals is to implement it as a for loop delay:


# #![allow(unused_variables)]
#fn main() {
fn delay(ms: u16) {
    const K: u16 = 16_000; // 16MHz microprocessor, needs to be tweaked
    for _ in 0..(K*ms) {}
}
#}

When compiled in release mode however, this is optimized away. To solve this we could explicitly add an operation inside the loop. The perfect candidate is the NOP.


# #![allow(unused_variables)]
#fn main() {
fn delay(ms: u16) {
    const K: u16 = 16_000; // 16MHz microprocessor, needs to be tweaked
    for _ in 0..(K*ms) {
        cortex_m::asm::nop();
    }
}
#}

Timers

A better way of implementing delays is by using timers. A one-shot timer (also called one pulse mode) works like an alarm clock. You set it once with the amount of time you want, and then wait until it goes off. Fortuinately for us, HAL crates usually have already solved this for us.

Microbit

The microbit has 3 timers, we will use the first: TIMER0. To use it, do the following:


# #![allow(unused_variables)]
#fn main() {
if let Some(p) = microbit::Peripherals::take() {
    let mut delay = Delay::new(p.TIMER0);
    delay.delay_ms(1000_u32);
}
#}