embassy/embassy-stm32/src/rcc/mco.rs

82 lines
2.3 KiB
Rust
Raw Normal View History

2023-09-19 04:22:57 +02:00
use core::marker::PhantomData;
use embassy_hal_internal::into_ref;
use crate::gpio::sealed::AFType;
use crate::gpio::Speed;
2023-10-06 23:36:16 +02:00
#[cfg(not(stm32wl))]
2023-09-19 04:22:57 +02:00
pub use crate::pac::rcc::vals::{Mco1 as Mco1Source, Mco2 as Mco2Source};
2023-10-06 23:36:16 +02:00
#[cfg(stm32wl)]
pub use crate::pac::rcc::vals::{Mcopre, Mcosel};
2023-09-19 04:22:57 +02:00
use crate::pac::RCC;
use crate::{peripherals, Peripheral};
pub(crate) mod sealed {
pub trait McoInstance {
type Source;
2023-10-06 23:36:16 +02:00
type Prescaler;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: Self::Prescaler);
2023-09-19 04:22:57 +02:00
}
}
pub trait McoInstance: sealed::McoInstance + 'static {}
pin_trait!(McoPin, McoInstance);
macro_rules! impl_peri {
2023-10-06 23:36:16 +02:00
($peri:ident, $source:ident, $prescaler:ident, $set_source:ident, $set_prescaler:ident) => {
2023-09-19 04:22:57 +02:00
impl sealed::McoInstance for peripherals::$peri {
type Source = $source;
2023-10-06 23:36:16 +02:00
type Prescaler = $prescaler;
2023-09-19 04:22:57 +02:00
2023-10-06 23:36:16 +02:00
unsafe fn apply_clock_settings(source: Self::Source, prescaler: Self::Prescaler) {
2023-09-19 04:22:57 +02:00
RCC.cfgr().modify(|w| {
w.$set_source(source);
w.$set_prescaler(prescaler);
});
}
}
impl McoInstance for peripherals::$peri {}
};
}
2023-10-06 23:36:16 +02:00
#[cfg(not(stm32wl))]
impl_peri!(MCO1, Mco1Source, u8, set_mco1, set_mco1pre);
#[cfg(not(stm32wl))]
impl_peri!(MCO2, Mco2Source, u8, set_mco2, set_mco2pre);
#[cfg(stm32wl)]
impl_peri!(MCO, Mcosel, Mcopre, set_mcosel, set_mcopre);
2023-09-19 04:22:57 +02:00
pub struct Mco<'d, T: McoInstance> {
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: McoInstance> Mco<'d, T> {
/// Create a new MCO instance.
///
2023-10-06 23:36:16 +02:00
/// `prescaler` must be between 1 and 15 for implementations not using Presel enum.
2023-09-19 04:22:57 +02:00
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
pin: impl Peripheral<P = impl McoPin<T>> + 'd,
source: T::Source,
2023-10-06 23:36:16 +02:00
prescaler: T::Prescaler,
2023-09-19 04:22:57 +02:00
) -> Self {
into_ref!(pin);
2023-10-06 23:36:16 +02:00
#[cfg(not(stm32wl))]
2023-09-19 04:22:57 +02:00
assert!(
1 <= prescaler && prescaler <= 15,
"Mco prescaler must be between 1 and 15. Refer to the reference manual for more information."
);
critical_section::with(|_| unsafe {
T::apply_clock_settings(source, prescaler);
pin.set_as_af(pin.af_num(), AFType::OutputPushPull);
pin.set_speed(Speed::VeryHigh);
});
Self { phantom: PhantomData }
}
}