rp2350 0.1.0

Hardware Abstraction Layer for RP2350 microcontrollers
Documentation
//! TICKS (Tick Generator) HAL for RP2350
//!
//! This module provides access to the tick generators for various system
//! components including processors, timers, and watchdog.
//!
//! The tick generators derive a 1µs tick from the reference clock for use
//! by timers and the watchdog. The reference clock frequency is obtained
//! from the [`Clocks`](crate::clocks::Clocks) peripheral after initialization,
//! so the correct cycles-per-tick value is always used regardless of which
//! clock source (XOSC, ROSC, etc.) feeds `clk_ref`.
//!
//! ## Features
//!
//! - Per-component tick generators (PROC0, PROC1, TIMER0, TIMER1, WATCHDOG)
//! - Configurable cycles per tick (auto-computed from `clk_ref`)
//! - Running status
//!
//! ## Example
//!
//! ```ignore
//! use rp2350::clocks::ClockBuilder;
//! use rp2350::ticks::Ticks;
//!
//! let clocks = ClockBuilder::new().build(dp.CLOCKS, dp.XOSC, dp.PLL_SYS, dp.PLL_USB);
//! let ticks = Ticks::init(dp.TICKS, &clocks);
//!
//! // Initialize only the tick generators you need
//! ticks.init_timer0();
//! ticks.init_watchdog();
//!
//! // Low-level control is also available
//! ticks.set_timer1_cycles(24);
//! ticks.enable_timer1();
//!
//! // Check if running
//! if ticks.timer0_running() {
//!     // Tick generator is active
//! }
//! ```

use crate::Steal;
use crate::clocks::Clocks;
use pastey::paste;

/// TICKS peripheral wrapper
///
/// Provides access to tick generator configuration and control.
/// The cycles-per-tick value is computed from `clk_ref` at construction time.
pub struct Ticks {
    ticks: rp2350_pac::TICKS,
    /// Pre-computed cycles per 1µs tick, derived from `clk_ref`
    cycles_per_tick: u16,
}

impl Ticks {
    /// Initialize the TICKS peripheral.
    ///
    /// Computes the correct cycles-per-tick value from the reference clock
    /// frequency tracked by `clocks`.
    ///
    /// # Arguments
    /// * `ticks` - The TICKS peripheral from PAC
    /// * `clocks` - Reference to the initialized clock system
    #[inline]
    pub fn init(ticks: rp2350_pac::TICKS, clocks: &Clocks) -> Self {
        let cycles_per_tick = clocks.ref_freq() / 1_000_000;
        assert!(
            (1..=0x1FF).contains(&cycles_per_tick),
            "clk_ref of {} Hz is out of range for a 1µs tick",
            clocks.ref_freq()
        );
        Self {
            ticks,
            cycles_per_tick: cycles_per_tick as u16,
        }
    }

    /// Obtain a Ticks handle without ownership checks.
    ///
    /// The returned handle uses a zero `cycles_per_tick`. The caller is
    /// responsible for calling [`set_proc0_cycles()`](Self::set_proc0_cycles)
    /// etc. before enabling any tick generator.
    ///
    /// # Safety
    ///
    /// The caller must ensure no data races occur.
    #[inline]
    pub unsafe fn steal() -> Steal<Self> {
        Steal(Self {
            ticks: unsafe { rp2350_pac::TICKS::steal() },
            cycles_per_tick: 0,
        })
    }

    /// Get the configured cycles per tick
    #[inline]
    pub fn cycles_per_tick(&self) -> u16 {
        self.cycles_per_tick
    }

    /// Get reference to the underlying register block
    ///
    /// # Safety
    /// Direct register access can bypass the HAL's safety guarantees.
    /// The caller must ensure operations do not conflict with the HAL state.
    #[inline]
    pub unsafe fn regs(&self) -> &rp2350_pac::ticks::RegisterBlock {
        &self.ticks
    }

    /// Release the TICKS peripheral
    #[inline]
    pub fn release(self) -> rp2350_pac::TICKS {
        self.ticks
    }

    // Per-generator accessors are generated by `impl_tick_gen!` below.
}

// ============================================================================
// Per-generator accessors
// ============================================================================

macro_rules! impl_tick_gen {
    ($($name:ident => $prefix:ident),+ $(,)?) => {
        paste! {
            $(
                impl Ticks {
                    #[doc = concat!("Enable the ", stringify!($name), " tick generator.")]
                    #[inline]
                    pub fn [<enable_ $name>](&mut self) {
                        self.ticks.[<$prefix _ctrl>].set_enable();
                    }

                    #[doc = concat!("Disable the ", stringify!($name), " tick generator.")]
                    #[inline]
                    pub fn [<disable_ $name>](&mut self) {
                        self.ticks.[<$prefix _ctrl>].clr_enable();
                    }

                    #[doc = concat!("Check if the ", stringify!($name), " tick generator is running.")]
                    #[inline]
                    pub fn [<$name _running>](&self) -> bool {
                        self.ticks.[<$prefix _ctrl>].running()
                    }

                    #[doc = concat!("Check if the ", stringify!($name), " tick generator is enabled.")]
                    #[inline]
                    pub fn [<$name _enabled>](&self) -> bool {
                        self.ticks.[<$prefix _ctrl>].enable()
                    }

                    #[doc = concat!("Set the ", stringify!($name), " cycles per tick (9-bit, max 511).")]
                    #[inline]
                    pub fn [<set_ $name _cycles>](&mut self, cycles: u16) {
                        assert!(cycles <= 0x1FF, "cycles per tick must fit in 9 bits");
                        self.ticks.[<$prefix _cycles>].[<write_ $prefix _cycles>](cycles as u32);
                    }

                    #[doc = concat!("Get the ", stringify!($name), " cycles per tick.")]
                    #[inline]
                    pub fn [<$name _cycles>](&self) -> u16 {
                        self.ticks.[<$prefix _cycles>].[<$prefix _cycles>]() as u16
                    }

                    #[doc = concat!("Get the ", stringify!($name), " tick count.")]
                    #[inline]
                    pub fn [<$name _count>](&self) -> u16 {
                        self.ticks.[<$prefix _count>].[<$prefix _count>]() as u16
                    }

                    #[doc = concat!("Initialize the ", stringify!($name), " tick generator (disable, set cycles, enable).")]
                    #[inline]
                    pub fn [<init_ $name>](&mut self) {
                        assert!(self.cycles_per_tick > 0, "no tick rate configured (was this handle stolen?)");
                        self.[<disable_ $name>]();
                        self.[<set_ $name _cycles>](self.cycles_per_tick);
                        self.[<enable_ $name>]();
                    }
                }
            )+
        }
    };
}

impl_tick_gen!(
    proc0 => proc0,
    proc1 => proc1,
    timer0 => timer0,
    timer1 => timer1,
    watchdog => watchdog,
    riscv => riscv,
);