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

Reading a timer

Let’s start with a basic operation: starting and then read a timer.

#![no_std]
#![no_main]
use aux::{blink_led, setup_xosc_on_clks};
use cortex_m::asm;
pub use cortex_m_rt::entry;
use defmt::info;

mod aux;

#[entry]
fn main() -> ! {
    unsafe {
        // GPIO 16 to visually signal board startup to us
        blink_led();

        setup_xosc_on_clks();

        // TICKS: TIMER0_CTRL Register
        // Without this the watchdog timer won't tick
        // (i.e.: won't go down)
        core::ptr::write_volatile(0x40108018 as *mut u32, 1);

        // TICKS: TIMER0_CYCLES Register
        // A divider that must result in a 1MHz clock.
        // If using the XOSC of reference board which 12MHz
        // this needs to be 12.
        core::ptr::write_volatile(0x4010801c as *mut u32, 12);

        // TIMER0: TIMEHR Register
        // Optional: set some initial value on the high counter
        // core::ptr::write_volatile(0x400b0000 as *mut u32, 7);
    };
    loop {
        let (timer_hr, timer_lr) = unsafe {
            // TIMER0: TIMELR Register
            let timer_lr =
                core::ptr::read_volatile(0x400b000c as *const u32) as u64;

            // TIMER0: TIMEHR Register
            let timer_hr =
                core::ptr::read_volatile(0x400b0008 as *const u32) as u64;

            (timer_hr, timer_lr)
        };

        info!("TIME0_LR: {} ", timer_lr);
        info!("TIME0_HR: {} ", timer_hr);

        let timer_combined = timer_hr << 32 | timer_lr;
        info!("TIMER0: {} ", timer_combined);

        for _ in 1..10_000_000 {
            asm::nop();
        }
    }
}