From 35f16c6003b4be69ee18d24440560ce8a700169c Mon Sep 17 00:00:00 2001 From: Sam Mason Date: Mon, 4 Dec 2023 14:03:31 +1100 Subject: [PATCH 01/20] stm32: add ADC f3_v1_1 --- embassy-stm32/src/adc/f3_v1_1.rs | 408 +++++++++++++++++++++++++++ embassy-stm32/src/adc/mod.rs | 21 +- embassy-stm32/src/adc/resolution.rs | 26 +- embassy-stm32/src/adc/sample_time.rs | 25 ++ 4 files changed, 466 insertions(+), 14 deletions(-) create mode 100644 embassy-stm32/src/adc/f3_v1_1.rs diff --git a/embassy-stm32/src/adc/f3_v1_1.rs b/embassy-stm32/src/adc/f3_v1_1.rs new file mode 100644 index 00000000..0bbfd313 --- /dev/null +++ b/embassy-stm32/src/adc/f3_v1_1.rs @@ -0,0 +1,408 @@ +use core::future::poll_fn; +use core::marker::PhantomData; +use core::task::Poll; + +use embassy_futures::yield_now; +use embassy_hal_internal::into_ref; +use embassy_time::Instant; + +use super::Resolution; +use crate::adc::{Adc, AdcPin, Instance, SampleTime}; +use crate::interrupt::typelevel::Interrupt; +use crate::time::Hertz; +use crate::{interrupt, Peripheral}; + +const ADC_FREQ: Hertz = crate::rcc::HSI_FREQ; + +pub const VDDA_CALIB_MV: u32 = 3300; +pub const ADC_MAX: u32 = (1 << 12) - 1; +pub const VREF_INT: u32 = 1230; + +pub enum AdcPowerMode { + AlwaysOn, + DelayOff, + IdleOff, + DelayIdleOff, +} + +pub enum Prescaler { + Div1, + Div2, + Div3, + Div4, +} + +/// Interrupt handler. +pub struct InterruptHandler { + _phantom: PhantomData, +} + +impl interrupt::typelevel::Handler for InterruptHandler { + unsafe fn on_interrupt() { + if T::regs().sr().read().eoc() { + T::regs().cr1().modify(|w| w.set_eocie(false)); + } else { + return; + } + + T::state().waker.wake(); + } +} + +fn update_vref(op: i8) { + static VREF_STATUS: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0); + + if op > 0 { + if VREF_STATUS.fetch_add(1, core::sync::atomic::Ordering::SeqCst) == 0 { + T::regs().ccr().modify(|w| w.set_tsvrefe(true)); + } + } else { + if VREF_STATUS.fetch_sub(1, core::sync::atomic::Ordering::SeqCst) == 1 { + T::regs().ccr().modify(|w| w.set_tsvrefe(false)); + } + } +} + +pub struct Vref(core::marker::PhantomData); +impl AdcPin for Vref {} +impl super::sealed::AdcPin for Vref { + fn channel(&self) -> u8 { + 17 + } +} + +impl Vref { + /// The value that vref would be if vdda was at 3000mv + pub fn calibrated_value(&self) -> u16 { + crate::pac::VREFINTCAL.data().read().value() + } + + pub async fn calibrate(&mut self, adc: &mut Adc<'_, T>) -> Calibration { + let vref_val = adc.read(self).await; + Calibration { + vref_cal: self.calibrated_value(), + vref_val, + } + } +} + +pub struct Calibration { + vref_cal: u16, + vref_val: u16, +} + +impl Calibration { + /// The millivolts that the calibration value was measured at + pub const CALIBRATION_UV: u32 = 3_000_000; + + /// Returns the measured VddA in microvolts (uV) + pub fn vdda_uv(&self) -> u32 { + (Self::CALIBRATION_UV * self.vref_cal as u32) / self.vref_val as u32 + } + + /// Returns the measured VddA as an f32 + pub fn vdda_f32(&self) -> f32 { + (Self::CALIBRATION_UV as f32 / 1_000.0) * (self.vref_cal as f32 / self.vref_val as f32) + } + + /// Returns a calibrated voltage value as in microvolts (uV) + pub fn cal_uv(&self, raw: u16, resolution: super::Resolution) -> u32 { + (self.vdda_uv() / resolution.to_max_count()) * raw as u32 + } + + /// Returns a calibrated voltage value as an f32 + pub fn cal_f32(&self, raw: u16, resolution: super::Resolution) -> f32 { + raw as f32 * self.vdda_f32() / resolution.to_max_count() as f32 + } +} + +impl Drop for Vref { + fn drop(&mut self) { + update_vref::(-1) + } +} + +pub struct Temperature(core::marker::PhantomData); +impl AdcPin for Temperature {} +impl super::sealed::AdcPin for Temperature { + fn channel(&self) -> u8 { + 16 + } +} + +impl Drop for Temperature { + fn drop(&mut self) { + update_vref::(-1) + } +} + +impl<'d, T: Instance> Adc<'d, T> { + pub fn new( + adc: impl Peripheral

+ 'd, + _irq: impl interrupt::typelevel::Binding> + 'd, + ) -> Self { + into_ref!(adc); + + T::enable_and_reset(); + + //let r = T::regs(); + //r.cr2().write(|w| w.set_align(true)); + + T::Interrupt::unpend(); + unsafe { + T::Interrupt::enable(); + } + + Self { adc } + } + + fn freq() -> Hertz { + let div = T::regs().ccr().read().adcpre() + 1; + ADC_FREQ / div as u32 + } + + pub async fn set_resolution(&mut self, res: Resolution) { + let was_on = Self::is_on(); + if was_on { + self.stop_adc().await; + } + + T::regs().cr1().modify(|w| w.set_res(res.into())); + + if was_on { + self.start_adc().await; + } + } + + pub fn resolution(&self) -> Resolution { + T::regs().cr1().read().res().into() + } + + pub fn enable_vref(&self) -> Vref { + update_vref::(1); + + Vref(core::marker::PhantomData) + } + + pub fn enable_temperature(&self) -> Temperature { + T::regs().ccr().modify(|w| w.set_tsvrefe(true)); + + Temperature::(core::marker::PhantomData) + } + + /// Perform a single conversion. + async fn convert(&mut self) -> u16 { + let was_on = Self::is_on(); + + if !was_on { + self.start_adc().await; + } + + self.wait_sample_ready().await; + + T::regs().sr().write(|_| {}); + T::regs().cr1().modify(|w| { + w.set_eocie(true); + w.set_scan(false); + }); + T::regs().cr2().modify(|w| { + w.set_swstart(true); + w.set_cont(false); + }); // swstart cleared by HW + + let res = poll_fn(|cx| { + T::state().waker.register(cx.waker()); + + if T::regs().sr().read().eoc() { + let res = T::regs().dr().read().rdata(); + Poll::Ready(res) + } else { + Poll::Pending + } + }) + .await; + + if !was_on { + self.stop_adc().await; + } + + res + } + + #[inline(always)] + fn is_on() -> bool { + T::regs().sr().read().adons() || T::regs().cr2().read().adon() + } + + pub async fn start_adc(&self) { + //defmt::trace!("Turn ADC on"); + T::regs().cr2().modify(|w| w.set_adon(true)); + //defmt::trace!("Waiting for ADC to turn on"); + + let mut t = Instant::now(); + + while !T::regs().sr().read().adons() { + yield_now().await; + if t.elapsed() > embassy_time::Duration::from_millis(1000) { + t = Instant::now(); + //defmt::trace!("ADC still not on"); + } + } + + //defmt::trace!("ADC on"); + } + + pub async fn stop_adc(&self) { + if T::regs().cr2().read().adon() { + //defmt::trace!("ADC should be on, wait for it to start"); + while !T::regs().csr().read().adons1() { + yield_now().await; + } + } + + //defmt::trace!("Turn ADC off"); + + T::regs().cr2().modify(|w| w.set_adon(false)); + + //defmt::trace!("Waiting for ADC to turn off"); + + while T::regs().csr().read().adons1() { + yield_now().await; + } + } + + pub async fn read(&mut self, pin: &mut impl AdcPin) -> u16 { + self.set_sample_sequence(&[pin.channel()]).await; + self.convert().await + } + + async fn wait_sample_ready(&self) { + //trace!("Waiting for sample channel to be ready"); + while T::regs().sr().read().rcnr() { + yield_now().await; + } + } + + pub async fn set_sample_time(&mut self, pin: &mut impl AdcPin, sample_time: SampleTime) { + if Self::get_channel_sample_time(pin.channel()) != sample_time { + self.stop_adc().await; + unsafe { + Self::set_channel_sample_time(pin.channel(), sample_time); + } + self.start_adc().await; + } + } + + pub fn get_sample_time(&self, pin: &impl AdcPin) -> SampleTime { + Self::get_channel_sample_time(pin.channel()) + } + + /// Sets the channel sample time + /// + /// ## SAFETY: + /// - ADON == 0 i.e ADC must not be enabled when this is called. + unsafe fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { + let sample_time = sample_time.into(); + + match ch { + 0..=9 => T::regs().smpr3().modify(|reg| reg.set_smp(ch as _, sample_time)), + 10..=19 => T::regs() + .smpr2() + .modify(|reg| reg.set_smp(ch as usize - 10, sample_time)), + 20..=29 => T::regs() + .smpr1() + .modify(|reg| reg.set_smp(ch as usize - 20, sample_time)), + 30..=31 => T::regs() + .smpr0() + .modify(|reg| reg.set_smp(ch as usize - 30, sample_time)), + _ => panic!("Invalid channel to sample"), + } + } + + fn get_channel_sample_time(ch: u8) -> SampleTime { + match ch { + 0..=9 => T::regs().smpr3().read().smp(ch as _), + 10..=19 => T::regs().smpr2().read().smp(ch as usize - 10), + 20..=29 => T::regs().smpr1().read().smp(ch as usize - 20), + 30..=31 => T::regs().smpr0().read().smp(ch as usize - 30), + _ => panic!("Invalid channel to sample"), + } + .into() + } + + /// Sets the sequence to sample the ADC. Must be less than 28 elements. + async fn set_sample_sequence(&self, sequence: &[u8]) { + assert!(sequence.len() <= 28); + let mut iter = sequence.iter(); + T::regs().sqr1().modify(|w| w.set_l((sequence.len() - 1) as _)); + for (idx, ch) in iter.by_ref().take(6).enumerate() { + T::regs().sqr5().modify(|w| w.set_sq(idx, *ch)); + } + for (idx, ch) in iter.by_ref().take(6).enumerate() { + T::regs().sqr4().modify(|w| w.set_sq(idx, *ch)); + } + for (idx, ch) in iter.by_ref().take(6).enumerate() { + T::regs().sqr3().modify(|w| w.set_sq(idx, *ch)); + } + for (idx, ch) in iter.by_ref().take(6).enumerate() { + T::regs().sqr2().modify(|w| w.set_sq(idx, *ch)); + } + for (idx, ch) in iter.by_ref().take(4).enumerate() { + T::regs().sqr1().modify(|w| w.set_sq(idx, *ch)); + } + } + + fn get_res_clks(res: Resolution) -> u32 { + match res { + Resolution::TwelveBit => 12, + Resolution::TenBit => 11, + Resolution::EightBit => 9, + Resolution::SixBit => 7, + } + } + + fn get_sample_time_clks(sample_time: SampleTime) -> u32 { + match sample_time { + SampleTime::Cycles4 => 4, + SampleTime::Cycles9 => 9, + SampleTime::Cycles16 => 16, + SampleTime::Cycles24 => 24, + SampleTime::Cycles48 => 48, + SampleTime::Cycles96 => 96, + SampleTime::Cycles192 => 192, + SampleTime::Cycles384 => 384, + } + } + + pub fn sample_time_for_us(&self, us: u32) -> SampleTime { + let res_clks = Self::get_res_clks(self.resolution()); + let us_clks = us * Self::freq().0 / 1_000_000; + let clks = us_clks.saturating_sub(res_clks); + match clks { + 0..=4 => SampleTime::Cycles4, + 5..=9 => SampleTime::Cycles9, + 10..=16 => SampleTime::Cycles16, + 17..=24 => SampleTime::Cycles24, + 25..=48 => SampleTime::Cycles48, + 49..=96 => SampleTime::Cycles96, + 97..=192 => SampleTime::Cycles192, + 193.. => SampleTime::Cycles384, + } + } + + pub fn us_for_cfg(&self, res: Resolution, sample_time: SampleTime) -> u32 { + let res_clks = Self::get_res_clks(res); + let sample_clks = Self::get_sample_time_clks(sample_time); + (res_clks + sample_clks) * 1_000_000 / Self::freq().0 + } +} + +impl<'d, T: Instance> Drop for Adc<'d, T> { + fn drop(&mut self) { + while !T::regs().sr().read().adons() {} + + T::regs().cr2().modify(|w| w.set_adon(false)); + + T::disable(); + } +} diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 3e2980bf..dbe53c80 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -3,6 +3,7 @@ #[cfg(not(adc_f3_v2))] #[cfg_attr(adc_f1, path = "f1.rs")] #[cfg_attr(adc_f3, path = "f3.rs")] +#[cfg_attr(adc_f3_v1_1, path = "f3_v1_1.rs")] #[cfg_attr(adc_v1, path = "v1.rs")] #[cfg_attr(adc_v2, path = "v2.rs")] #[cfg_attr(any(adc_v3, adc_g0), path = "v3.rs")] @@ -26,20 +27,20 @@ use crate::peripherals; pub struct Adc<'d, T: Instance> { #[allow(unused)] adc: crate::PeripheralRef<'d, T>, - #[cfg(not(adc_f3_v2))] + #[cfg(not(any(adc_f3_v2, adc_f3_v1_1)))] sample_time: SampleTime, } pub(crate) mod sealed { - #[cfg(any(adc_f1, adc_f3, adc_v1))] + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] use embassy_sync::waitqueue::AtomicWaker; - #[cfg(any(adc_f1, adc_f3, adc_v1))] + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] pub struct State { pub waker: AtomicWaker, } - #[cfg(any(adc_f1, adc_f3, adc_v1))] + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] impl State { pub const fn new() -> Self { Self { @@ -54,11 +55,11 @@ pub(crate) mod sealed { pub trait Instance: InterruptableInstance { fn regs() -> crate::pac::adc::Adc; - #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))] + #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))] fn common_regs() -> crate::pac::adccommon::AdcCommon; #[cfg(adc_f3)] fn frequency() -> crate::time::Hertz; - #[cfg(any(adc_f1, adc_f3, adc_v1))] + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] fn state() -> &'static State; } @@ -74,9 +75,9 @@ pub(crate) mod sealed { } } -#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0)))] +#[cfg(not(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0)))] pub trait Instance: sealed::Instance + crate::Peripheral

{} -#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_g0))] +#[cfg(any(adc_f1, adc_v1, adc_v2, adc_v3, adc_v4, adc_f3, adc_f3_v1_1, adc_g0))] pub trait Instance: sealed::Instance + crate::Peripheral

+ crate::rcc::RccPeripheral {} pub trait AdcPin: sealed::AdcPin {} @@ -89,7 +90,7 @@ foreach_adc!( crate::pac::$inst } - #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))] + #[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_f3_v1_1, adc_g0)))] fn common_regs() -> crate::pac::adccommon::AdcCommon { return crate::pac::$common_inst } @@ -99,7 +100,7 @@ foreach_adc!( unsafe { crate::rcc::get_freqs() }.$clock.unwrap() } - #[cfg(any(adc_f1, adc_f3, adc_v1))] + #[cfg(any(adc_f1, adc_f3, adc_v1, adc_f3_v1_1))] fn state() -> &'static sealed::State { static STATE: sealed::State = sealed::State::new(); &STATE diff --git a/embassy-stm32/src/adc/resolution.rs b/embassy-stm32/src/adc/resolution.rs index 5668137b..b1597a82 100644 --- a/embassy-stm32/src/adc/resolution.rs +++ b/embassy-stm32/src/adc/resolution.rs @@ -1,5 +1,6 @@ -#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))] +#[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] #[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Resolution { TwelveBit, TenBit, @@ -9,6 +10,7 @@ pub enum Resolution { #[cfg(adc_v4)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Resolution { SixteenBit, FourteenBit, @@ -19,7 +21,7 @@ pub enum Resolution { impl Default for Resolution { fn default() -> Self { - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))] + #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] { Self::TwelveBit } @@ -40,12 +42,28 @@ impl From for crate::pac::adc::vals::Res { Resolution::TwelveBit => crate::pac::adc::vals::Res::TWELVEBIT, Resolution::TenBit => crate::pac::adc::vals::Res::TENBIT, Resolution::EightBit => crate::pac::adc::vals::Res::EIGHTBIT, - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))] + #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] Resolution::SixBit => crate::pac::adc::vals::Res::SIXBIT, } } } +impl From for Resolution { + fn from(res: crate::pac::adc::vals::Res) -> Resolution { + match res { + #[cfg(adc_v4)] + crate::pac::adc::vals::Res::SIXTEENBIT => Resolution::SixteenBit, + #[cfg(adc_v4)] + crate::pac::adc::vals::Res::FOURTEENBITV => Resolution::FourteenBit, + crate::pac::adc::vals::Res::TWELVEBIT => Resolution::TwelveBit, + crate::pac::adc::vals::Res::TENBIT => Resolution::TenBit, + crate::pac::adc::vals::Res::EIGHTBIT => Resolution::EightBit, + #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1, adc_f3_v3))] + crate::pac::adc::vals::Res::SIXBIT => Resolution::SixBit, + } + } +} + impl Resolution { pub fn to_max_count(&self) -> u32 { match self { @@ -56,7 +74,7 @@ impl Resolution { Resolution::TwelveBit => (1 << 12) - 1, Resolution::TenBit => (1 << 10) - 1, Resolution::EightBit => (1 << 8) - 1, - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3))] + #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1))] Resolution::SixBit => (1 << 6) - 1, } } diff --git a/embassy-stm32/src/adc/sample_time.rs b/embassy-stm32/src/adc/sample_time.rs index 6a661929..5a06f1a5 100644 --- a/embassy-stm32/src/adc/sample_time.rs +++ b/embassy-stm32/src/adc/sample_time.rs @@ -3,6 +3,7 @@ macro_rules! impl_sample_time { ($default_doc:expr, $default:ident, ($(($doc:expr, $variant:ident, $pac_variant:ident)),*)) => { #[doc = concat!("ADC sample time\n\nThe default setting is ", $default_doc, " ADC clock cycles.")] #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SampleTime { $( #[doc = concat!($doc, " ADC clock cycles.")] @@ -18,6 +19,14 @@ macro_rules! impl_sample_time { } } + impl From for SampleTime { + fn from(sample_time: crate::pac::adc::vals::SampleTime) -> SampleTime { + match sample_time { + $(crate::pac::adc::vals::SampleTime::$pac_variant => SampleTime::$variant),* + } + } + } + impl Default for SampleTime { fn default() -> Self { Self::$default @@ -121,3 +130,19 @@ impl_sample_time!( ("601.5", Cycles601_5, CYCLES601_5) ) ); + +#[cfg(any(adc_f3_v1_1))] +impl_sample_time!( + "4", + Cycles4, + ( + ("4", Cycles4, CYCLES4), + ("9", Cycles9, CYCLES9), + ("16", Cycles16, CYCLES16), + ("24", Cycles24, CYCLES24), + ("48", Cycles48, CYCLES48), + ("96", Cycles96, CYCLES96), + ("192", Cycles192, CYCLES192), + ("384", Cycles384, CYCLES384) + ) +); From 0b0ca62a95cd2dabbc7e160dc5d0fcfc1a7a76e8 Mon Sep 17 00:00:00 2001 From: JuliDi <20155974+JuliDi@users.noreply.github.com> Date: Mon, 4 Dec 2023 20:59:08 +0100 Subject: [PATCH 02/20] add speed optimization --- docs/modules/ROOT/pages/faq.adoc | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/modules/ROOT/pages/faq.adoc b/docs/modules/ROOT/pages/faq.adoc index df3f6665..8ac1febc 100644 --- a/docs/modules/ROOT/pages/faq.adoc +++ b/docs/modules/ROOT/pages/faq.adoc @@ -135,3 +135,19 @@ embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "e5fdd ---- Note that the git revision should match any other embassy patches or git dependencies that you are using! + +== How can I optimize the speed of my embassy-stm32 program? + +* Make sure RCC is set up to go as fast as possible +* Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled +* build with `--release` +* Set the following keys for the release profile in your `Cargo.toml``: + ** `opt-level=s` + ** `lto=fat` + ** `build-std=core` + ** `build-std-features=panic_immediate_abort` +* Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers` +* When using `InterruptExecutor`: + ** disable `executor-thread` + ** make `main`` spawn everything, then enable link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html#method.set_sleeponexit[SCB.SLEEPONEXIT] and `loop { cortex_m::asm::wfi() }` + ** *Note:* If you need 2 priority levels, using 2 interrupt executors is better than 1 thread executor + 1 interrupt executor. \ No newline at end of file From bf7115cb4425959acd01d3e9a1d640a47948b2f9 Mon Sep 17 00:00:00 2001 From: JuliDi <20155974+JuliDi@users.noreply.github.com> Date: Mon, 4 Dec 2023 21:20:18 +0100 Subject: [PATCH 03/20] remove unnecessary backtick --- docs/modules/ROOT/pages/faq.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/faq.adoc b/docs/modules/ROOT/pages/faq.adoc index 8ac1febc..0999b690 100644 --- a/docs/modules/ROOT/pages/faq.adoc +++ b/docs/modules/ROOT/pages/faq.adoc @@ -141,7 +141,7 @@ Note that the git revision should match any other embassy patches or git depende * Make sure RCC is set up to go as fast as possible * Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled * build with `--release` -* Set the following keys for the release profile in your `Cargo.toml``: +* Set the following keys for the release profile in your `Cargo.toml`: ** `opt-level=s` ** `lto=fat` ** `build-std=core` From 1f6ffdcdd2e760d91ed10fa63f6819b71579b2b4 Mon Sep 17 00:00:00 2001 From: JuliDi <20155974+JuliDi@users.noreply.github.com> Date: Tue, 5 Dec 2023 10:10:47 +0100 Subject: [PATCH 04/20] fix Cargo.toml and config.toml keys --- docs/modules/ROOT/pages/faq.adoc | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/modules/ROOT/pages/faq.adoc b/docs/modules/ROOT/pages/faq.adoc index 0999b690..cab9fb9d 100644 --- a/docs/modules/ROOT/pages/faq.adoc +++ b/docs/modules/ROOT/pages/faq.adoc @@ -142,10 +142,11 @@ Note that the git revision should match any other embassy patches or git depende * Make sure link:https://docs.rs/cortex-m/latest/cortex_m/peripheral/struct.SCB.html[flash cache] is enabled * build with `--release` * Set the following keys for the release profile in your `Cargo.toml`: - ** `opt-level=s` - ** `lto=fat` - ** `build-std=core` - ** `build-std-features=panic_immediate_abort` + ** `opt-level = "s"` + ** `lto = "fat"` +* Set the following keys in the `[unstable]` section of your `.cargo/config.toml` + ** `build-std = ["core"]` + ** `build-std-features = ["panic_immediate_abort"]` * Enable feature `embassy-time/generic-queue`, disable feature `embassy-executor/integrated-timers` * When using `InterruptExecutor`: ** disable `executor-thread` From cd62d2cd84176cd7a70ea164e34a3f2245c1fbd1 Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Wed, 6 Dec 2023 21:10:16 +0100 Subject: [PATCH 05/20] Added embassy in the wild docs page with two projects --- docs/modules/ROOT/nav.adoc | 1 + docs/modules/ROOT/pages/embassy_in_the_wild.adoc | 8 ++++++++ 2 files changed, 9 insertions(+) create mode 100644 docs/modules/ROOT/pages/embassy_in_the_wild.adoc diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index 8d7f6f41..f79e1d54 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -12,4 +12,5 @@ * xref:examples.adoc[Examples] * xref:developer.adoc[Developer] ** xref:developer_stm32.adoc[Developer: STM32] +* xref:embassy_in_the_wild.adoc[Embassy in the wild] * xref:faq.adoc[Frequently Asked Questions] diff --git a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc new file mode 100644 index 00000000..c1c09c38 --- /dev/null +++ b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc @@ -0,0 +1,8 @@ += Embassy in the wild! + +Here are known examples of real-world projects which make use of Embassy. Feel free to link:https://github.com/embassy-rs/embassy/blob/main/docs/modules/ROOT/pages/embassy_in_the_wild.adoc[add more]! + +* link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] +** Targets some STM32 MCUs +* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] +** Targets the ESP32-S3 MCU \ No newline at end of file From 10c9e2e7238f07665333264afa132736cee09f8d Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Wed, 6 Dec 2023 21:11:34 +0100 Subject: [PATCH 06/20] Added description for Card/IO --- docs/modules/ROOT/pages/embassy_in_the_wild.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc index c1c09c38..a69aa701 100644 --- a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc +++ b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc @@ -4,5 +4,5 @@ Here are known examples of real-world projects which make use of Embassy. Feel f * link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] ** Targets some STM32 MCUs -* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] +* link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device ** Targets the ESP32-S3 MCU \ No newline at end of file From 195b492158b7db8b81c4cf6bbc436884590d334b Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Wed, 6 Dec 2023 21:13:56 +0100 Subject: [PATCH 07/20] Update docs/modules/ROOT/pages/embassy_in_the_wild.adoc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Dániel Buga --- docs/modules/ROOT/pages/embassy_in_the_wild.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc index a69aa701..5c12227b 100644 --- a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc +++ b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc @@ -5,4 +5,4 @@ Here are known examples of real-world projects which make use of Embassy. Feel f * link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] ** Targets some STM32 MCUs * link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device -** Targets the ESP32-S3 MCU \ No newline at end of file +** Targets the ESP32-S3 or ESP32-C6 MCU \ No newline at end of file From 7561696a57ce77146078e481dc75dd3ab9e1c76d Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Wed, 6 Dec 2023 21:47:52 +0100 Subject: [PATCH 08/20] Added lora-rs links --- docs/modules/ROOT/pages/embassy_in_the_wild.adoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc index a69aa701..625bd0b2 100644 --- a/docs/modules/ROOT/pages/embassy_in_the_wild.adoc +++ b/docs/modules/ROOT/pages/embassy_in_the_wild.adoc @@ -5,4 +5,5 @@ Here are known examples of real-world projects which make use of Embassy. Feel f * link:https://github.com/cbruiz/printhor/[Printhor: The highly reliable but not necessarily functional 3D printer firmware] ** Targets some STM32 MCUs * link:https://github.com/card-io-ecg/card-io-fw[Card/IO firmware] - firmware for an open source ECG device -** Targets the ESP32-S3 MCU \ No newline at end of file +** Targets the ESP32-S3 MCU +* The link:https://github.com/lora-rs/lora-rs[lora-rs] project includes link:https://github.com/lora-rs/lora-rs/tree/main/examples/stm32l0/src/bin[various standalone examples] for NRF52840, RP2040, STM32L0 and STM32WL \ No newline at end of file From 536e91d263ecfcf684f91598e5ca987ae0acc820 Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Wed, 6 Dec 2023 23:51:13 +0100 Subject: [PATCH 09/20] Added a step-by-step guide to starting a new embassy project Based off an example, noting what to copy, what to change and why Briefly summarizing how to require embassy crates via github All steps tested and proven working at the time of writing --- docs/modules/ROOT/nav.adoc | 1 + docs/modules/ROOT/pages/new_project.adoc | 179 +++++++++++++++++++++++ 2 files changed, 180 insertions(+) create mode 100644 docs/modules/ROOT/pages/new_project.adoc diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index 8d7f6f41..70a4a415 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -1,6 +1,7 @@ * xref:getting_started.adoc[Getting started] ** xref:basic_application.adoc[Basic application] ** xref:project_structure.adoc[Project Structure] +** xref:new_project.adoc[Starting a new Embassy project] * xref:layer_by_layer.adoc[Bare metal to async] * xref:runtime.adoc[Executor] * xref:delaying_a_task.adoc[Delaying a Task] diff --git a/docs/modules/ROOT/pages/new_project.adoc b/docs/modules/ROOT/pages/new_project.adoc new file mode 100644 index 00000000..ae819aa8 --- /dev/null +++ b/docs/modules/ROOT/pages/new_project.adoc @@ -0,0 +1,179 @@ += Starting a new Embassy project + +Once you’ve successfully xref:getting_started.adoc[run some example projects], the next step is to make a standalone Embassy project. The easiest way to do this is to adapt an example for a similar chip to the one you’re targeting. + +As an example, let’s create a new embassy project from scratch for a STM32G474. The same instructions are applicable for any supported chip with some minor changes. + +Run: + +[source,bash] +---- +mkdir embassy-stm32g474 +cd embassy-stm32g474 +cargo init +---- + +to create an empty rust project: + +[source] +---- +embassy-stm32g474 +├── Cargo.toml +└── src + └── main.rs +---- + +Looking in link:https://github.com/embassy-rs/embassy/tree/main/examples[the Embassy examples], we can see there’s a `stm32g4` folder. Find `src/blinky.rs` and copy its contents into our `src/main.rs`. + +== .cargo/config.toml + +Currently, we’d need to provide cargo with a target triple every time we run `cargo build` or `cargo run`. Let’s spare ourselves that work by copying `.cargo/config.toml` from `examples/stm32g4` into our project. + +[source] +---- +embassy-stm32g474 +├── .cargo +│   └── config.toml +├── Cargo.toml +└── src + └── main.rs +---- + +In addition to a target triple, `.cargo/config.toml` contains a `runner` key which allows us to conveniently run our project on hardware with `cargo run` via probe-rs. In order for this to work, we need to provide the correct chip ID. We can do this by checking `probe-rs chip list`: + +[source,bash] +---- +$ probe-rs chip list | grep -i stm32g474re + STM32G474RETx +---- + +and copying `STM32G474RETx` into `.cargo/config.toml` as so: + +[source,toml] +---- +[target.'cfg(all(target_arch = "arm", target_os = "none"))'] +# replace STM32G071C8Rx with your chip as listed in `probe-rs chip list` +runner = "probe-rs run --chip STM32G474RETx" +---- + +== Cargo.toml + +Now that cargo knows what target to compile for (and probe-rs knows what chip to run it on), we’re ready to add some dependencies. + +Looking in `examples/stm32g4/Cargo.toml`, we can see that the examples require a number of embassy crates. For blinky, we’ll only need three of them: `embassy-stm32`, `embassy-executor` and `embassy-time`. + +At the time of writing, the latest version of embassy isn‘t available on crates.io, so we need to install it straight from the git repository. The recommended way of doing so is as follows: + +* Copy the required `embassy-*` lines from the example `Cargo.toml` +* Make any necessary changes to `features`, e.g. requiring the `stm32g474re` feature of `embassy-stm32` +* Remove the `path = ""` keys in the `embassy-*` entries +* Create a `[patch.crates-io]` section, with entries for each embassy crate we need. These should all contain identical values: a link to the git repository, and a reference to the commit we’re checking out. Assuming you want the latest commit, you can find it by running `git ls-remote https://github.com/embassy-rs/embassy.git HEAD` + +NOTE: When using this method, it’s necessary that the `version` keys in `[dependencies]` match up with the versions defined in each crate’s `Cargo.toml` in the specificed `rev` under `[patch.crates.io]`. This means that when updating, you have to a pick a new revision, change everything in `[patch.crates.io]` to match it, and then correct any versions under `[dependencies]` which have changed. Hopefully this will no longer be necessary once embassy is released on crates.io! + +At the time of writing, this method produces the following results: + +[source,toml] +---- +[dependencies] +embassy-stm32 = {version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"]} +embassy-executor = { version = "0.3.3", features = ["nightly", "arch-cortex-m", "executor-thread", "defmt", "integrated-timers"] } +embassy-time = { version = "0.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } + +[patch.crates-io] +embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" } +embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" } +embassy-stm32 = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" } +---- + +There are a few other dependencies we need to build the project, but fortunately they’re much simpler to install. Copy their lines from the example `Cargo.toml` to the the `[dependencies]` section in the new `Cargo.toml`: + +[source,toml] +---- +defmt = "0.3.5" +defmt-rtt = "0.4.0" +cortex-m = {version = "0.7.7", features = ["critical-section-single-core"]} +cortex-m-rt = "0.7.3" +panic-probe = "0.3.1" +---- + +These are the bare minimum dependencies required to run `blinky.rs`, but it’s worth taking a look at the other dependencies specified in the example `Cargo.toml`, and noting what features are required for use with embassy – for example `futures = { version = "0.3.17", default-features = false, features = ["async-await"] }`. + +Finally, copy the `[profile.release]` section from the example `Cargo.toml` into ours. + +[source,toml] +---- +[profile.release] +debug = 2 +---- + +== rust-toolchain.toml + +Before we can build our project, we need to add an additional file to tell cargo to use the nightly toolchain. Copy the `rust-toolchain.toml` from the embassy repo to ours, and trim the list of targets down to only the target triple relevent for our project — in this case, `thumbv7em-none-eabi`: + +[source] +---- +embassy-stm32g474 +├── .cargo +│   └── config.toml +├── Cargo.toml +├── rust-toolchain.toml +└── src + └── main.rs +---- + +[source,toml] +---- +# Before upgrading check that everything is available on all tier1 targets here: +# https://rust-lang.github.io/rustup-components-history +[toolchain] +channel = "nightly-2023-11-01" +components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ] +targets = ["thumbv7em-none-eabi"] +---- + +== build.rs + +In order to produce a working binary for our target, cargo requires a custom build script. Copy `build.rs` from the example to our project: + +[source] +---- +embassy-stm32g474 +├── build.rs +├── .cargo +│ └── config.toml +├── Cargo.toml +├── rust-toolchain.toml +└── src + └── main.rs +---- + +== Building and running + +At this point, we‘re finally ready to build and run our project! Connect your board via a debug probe and run: + +[source,bash] +---- +cargo run --release +---- + +should result in a blinking LED (if there’s one attached to the pin in `src/main.rs` – change it if not!) and the following output: + +[source] +---- + Compiling embassy-stm32g474 v0.1.0 (/home/you/embassy-stm32g474) + Finished release [optimized + debuginfo] target(s) in 0.22s + Running `probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/embassy-stm32g474` + Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s ) + Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s +0.000000 TRACE BDCR configured: 00008200 +└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117 +0.000000 DEBUG rcc: Clocks { sys: Hertz(16000000), pclk1: Hertz(16000000), pclk1_tim: Hertz(16000000), pclk2: Hertz(16000000), pclk2_tim: Hertz(16000000), hclk1: Hertz(16000000), hclk2: Hertz(16000000), pll1_p: None, adc: None, adc34: None, rtc: Some(Hertz(32000)) } +└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130 +0.000000 INFO Hello World! +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14 +0.000091 INFO high +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19 +0.300201 INFO low +└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23 +---- \ No newline at end of file From 16e31747cc860b194719d7d276f1a0c08e417632 Mon Sep 17 00:00:00 2001 From: Barnaby Walters Date: Thu, 7 Dec 2023 00:54:39 +0100 Subject: [PATCH 10/20] Changed example project name --- docs/modules/ROOT/pages/new_project.adoc | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/docs/modules/ROOT/pages/new_project.adoc b/docs/modules/ROOT/pages/new_project.adoc index ae819aa8..ce139ed8 100644 --- a/docs/modules/ROOT/pages/new_project.adoc +++ b/docs/modules/ROOT/pages/new_project.adoc @@ -8,16 +8,15 @@ Run: [source,bash] ---- -mkdir embassy-stm32g474 -cd embassy-stm32g474 -cargo init +cargo new stm32g474-example +cd stm32g474-example ---- to create an empty rust project: [source] ---- -embassy-stm32g474 +stm32g474-example ├── Cargo.toml └── src └── main.rs @@ -31,7 +30,7 @@ Currently, we’d need to provide cargo with a target triple every time we run ` [source] ---- -embassy-stm32g474 +stm32g474-example ├── .cargo │   └── config.toml ├── Cargo.toml @@ -113,7 +112,7 @@ Before we can build our project, we need to add an additional file to tell cargo [source] ---- -embassy-stm32g474 +stm32g474-example ├── .cargo │   └── config.toml ├── Cargo.toml @@ -138,7 +137,7 @@ In order to produce a working binary for our target, cargo requires a custom bui [source] ---- -embassy-stm32g474 +stm32g474-example ├── build.rs ├── .cargo │ └── config.toml @@ -161,9 +160,9 @@ should result in a blinking LED (if there’s one attached to the pin in `src/ma [source] ---- - Compiling embassy-stm32g474 v0.1.0 (/home/you/embassy-stm32g474) + Compiling stm32g474-example v0.1.0 (/home/you/stm32g474-example) Finished release [optimized + debuginfo] target(s) in 0.22s - Running `probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/embassy-stm32g474` + Running `probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/stm32g474-example` Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s ) Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s 0.000000 TRACE BDCR configured: 00008200 From 8fa5a6b282792d7f9238964acc2916452b494965 Mon Sep 17 00:00:00 2001 From: James Munns Date: Thu, 7 Dec 2023 14:27:09 +0100 Subject: [PATCH 11/20] Tweak FAQ size profile suggestions If we want the smallest binary, we probably want codegen-units = 1, and disable incremental builds. --- docs/modules/ROOT/pages/faq.adoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/faq.adoc b/docs/modules/ROOT/pages/faq.adoc index df3f6665..2ec43891 100644 --- a/docs/modules/ROOT/pages/faq.adoc +++ b/docs/modules/ROOT/pages/faq.adoc @@ -47,7 +47,8 @@ The first step to managing your binary size is to set up your link:https://doc.r debug = false lto = true opt-level = "s" -incremental = true +incremental = false +codegen-units = 1 ---- All of these flags are elaborated on in the Rust Book page linked above. From c05149e5e4110bed416e8a8568cf446e9db8774d Mon Sep 17 00:00:00 2001 From: JuliDi <20155974+JuliDi@users.noreply.github.com> Date: Fri, 8 Dec 2023 13:00:21 +0100 Subject: [PATCH 12/20] add best practices first draft --- docs/modules/ROOT/nav.adoc | 5 +- docs/modules/ROOT/pages/best_practices.adoc | 53 +++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 docs/modules/ROOT/pages/best_practices.adoc diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index 2154799f..fabb80e3 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -2,6 +2,7 @@ ** xref:basic_application.adoc[Basic application] ** xref:project_structure.adoc[Project Structure] ** xref:new_project.adoc[Starting a new Embassy project] +** xref:best_practices.adoc[Best Practices] * xref:layer_by_layer.adoc[Bare metal to async] * xref:runtime.adoc[Executor] * xref:delaying_a_task.adoc[Delaying a Task] @@ -11,7 +12,7 @@ * xref:bootloader.adoc[Bootloader] * xref:examples.adoc[Examples] -* xref:developer.adoc[Developer] -** xref:developer_stm32.adoc[Developer: STM32] +* xref:developer.adoc[Developer Docs] +** xref:developer_stm32.adoc[Developer Docs: STM32] * xref:embassy_in_the_wild.adoc[Embassy in the wild] * xref:faq.adoc[Frequently Asked Questions] diff --git a/docs/modules/ROOT/pages/best_practices.adoc b/docs/modules/ROOT/pages/best_practices.adoc new file mode 100644 index 00000000..1e02f9ba --- /dev/null +++ b/docs/modules/ROOT/pages/best_practices.adoc @@ -0,0 +1,53 @@ += Best Practices + +Over time, a couple of best practices have emerged. The following list should serve as a guideline for developers writing embedded software in _Rust_, especially in the context of the _Embassy_ framework. + +== Passing Buffers by Reference +It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`], to a function or return one just like you would with a `std::Vec`. However, in most embedded applications you don't want to spend ressources on an allocator and end up placing buffers on the stack. +This, however, can easily blow up your stack if you are not careful. + +Consider the following example: +[,rust] +---- +fn process_buffer(mut buf: [u8; 1024]) -> [u8; 1024] { + // do stuff and return new buffer + for elem in buf.iter_mut() { + *elem = 0; + } + buf +} + +pub fn main() -> () { + let buf = [1u8; 1024]; + let buf_new = process_buffer(buf); + // do stuff with buf_new + () +} +---- +When calling `process_buffer` in your program, a copy of the buffer you pass to the function will be created, +consuming another 1024 bytes. +After the processing, another 1024 byte buffer will be placed on the stack to be returned to the caller. +(You can check the assembly, there will be two memcopy operations, e.g., `bl __aeabi_memcpy` when compiling for a Cortex-M processor.) + +*Possible Solution:* + +Pass the data by reference and not by value on both, the way in and the way out. +For example, you could return a slice of the input buffer as the output. +Requiring the lifetime of the input slice and the output slice to be the same, the memory safetly of this procedure will be enforced by the compiler. + +[,rust] +---- +fn process_buffer<'a>(buf: &'a mut [u8]) -> &'a mut[u8] { + for elem in buf.iter_mut() { + *elem = 0; + } + buf +} + +pub fn main() -> () { + let mut buf = [1u8; 1024]; + let buf_new = process_buffer(&mut buf); + // do stuff with buf_new + () +} +---- From 881cb16d2809cf84757b7ecabcad44be0d97fa14 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Fri, 8 Dec 2023 20:07:06 +0100 Subject: [PATCH 13/20] stm32/adc: move convert resolution from PAC to version-specific mod. --- embassy-stm32/src/adc/f3_v1_1.rs | 7 ++++++- embassy-stm32/src/adc/resolution.rs | 16 ---------------- 2 files changed, 6 insertions(+), 17 deletions(-) diff --git a/embassy-stm32/src/adc/f3_v1_1.rs b/embassy-stm32/src/adc/f3_v1_1.rs index 0bbfd313..6915a8f1 100644 --- a/embassy-stm32/src/adc/f3_v1_1.rs +++ b/embassy-stm32/src/adc/f3_v1_1.rs @@ -175,7 +175,12 @@ impl<'d, T: Instance> Adc<'d, T> { } pub fn resolution(&self) -> Resolution { - T::regs().cr1().read().res().into() + match T::regs().cr1().read().res() { + crate::pac::adc::vals::Res::TWELVEBIT => Resolution::TwelveBit, + crate::pac::adc::vals::Res::TENBIT => Resolution::TenBit, + crate::pac::adc::vals::Res::EIGHTBIT => Resolution::EightBit, + crate::pac::adc::vals::Res::SIXBIT => Resolution::SixBit, + } } pub fn enable_vref(&self) -> Vref { diff --git a/embassy-stm32/src/adc/resolution.rs b/embassy-stm32/src/adc/resolution.rs index b1597a82..383980b5 100644 --- a/embassy-stm32/src/adc/resolution.rs +++ b/embassy-stm32/src/adc/resolution.rs @@ -48,22 +48,6 @@ impl From for crate::pac::adc::vals::Res { } } -impl From for Resolution { - fn from(res: crate::pac::adc::vals::Res) -> Resolution { - match res { - #[cfg(adc_v4)] - crate::pac::adc::vals::Res::SIXTEENBIT => Resolution::SixteenBit, - #[cfg(adc_v4)] - crate::pac::adc::vals::Res::FOURTEENBITV => Resolution::FourteenBit, - crate::pac::adc::vals::Res::TWELVEBIT => Resolution::TwelveBit, - crate::pac::adc::vals::Res::TENBIT => Resolution::TenBit, - crate::pac::adc::vals::Res::EIGHTBIT => Resolution::EightBit, - #[cfg(any(adc_v1, adc_v2, adc_v3, adc_g0, adc_f3, adc_f3_v1_1, adc_f3_v3))] - crate::pac::adc::vals::Res::SIXBIT => Resolution::SixBit, - } - } -} - impl Resolution { pub fn to_max_count(&self) -> u32 { match self { From c27459c05251aada50b4de620b78d13dc071a765 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Fri, 8 Dec 2023 20:07:59 +0100 Subject: [PATCH 14/20] Update stm32-metapac. --- embassy-stm32/Cargo.toml | 4 ++-- embassy-stm32/build.rs | 4 ++++ embassy-stm32/src/adc/f1.rs | 2 +- embassy-stm32/src/can/mod.rs | 2 +- embassy-stm32/src/rcc/g4.rs | 2 ++ embassy-stm32/src/rcc/mod.rs | 4 ++-- 6 files changed, 12 insertions(+), 6 deletions(-) diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 292902ac..c5877570 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -58,7 +58,7 @@ rand_core = "0.6.3" sdio-host = "0.5.0" embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true } critical-section = "1.1" -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7117ad49c06fa00c388130a34977e029910083bd" } +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-019a5da1c47c092c199bc39a7f84fb444f2adcdf" } vcell = "0.1.3" bxcan = "0.7.0" nb = "1.0.0" @@ -76,7 +76,7 @@ critical-section = { version = "1.1", features = ["std"] } [build-dependencies] proc-macro2 = "1.0.36" quote = "1.0.15" -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-7117ad49c06fa00c388130a34977e029910083bd", default-features = false, features = ["metadata"]} +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-019a5da1c47c092c199bc39a7f84fb444f2adcdf", default-features = false, features = ["metadata"]} [features] diff --git a/embassy-stm32/build.rs b/embassy-stm32/build.rs index 7bfd290d..0eef43ac 100644 --- a/embassy-stm32/build.rs +++ b/embassy-stm32/build.rs @@ -930,6 +930,10 @@ fn main() { } else if pin.signal.starts_with("INN") { // TODO handle in the future when embassy supports differential measurements None + } else if pin.signal.starts_with("IN") && pin.signal.ends_with("b") { + // we number STM32L1 ADC bank 1 as 0..=31, bank 2 as 32..=63 + let signal = pin.signal.strip_prefix("IN").unwrap().strip_suffix("b").unwrap(); + Some(32u8 + signal.parse::().unwrap()) } else if pin.signal.starts_with("IN") { Some(pin.signal.strip_prefix("IN").unwrap().parse().unwrap()) } else { diff --git a/embassy-stm32/src/adc/f1.rs b/embassy-stm32/src/adc/f1.rs index ad0f1382..fb27bb87 100644 --- a/embassy-stm32/src/adc/f1.rs +++ b/embassy-stm32/src/adc/f1.rs @@ -148,7 +148,7 @@ impl<'d, T: Instance> Adc<'d, T> { reg.set_cont(false); reg.set_exttrig(true); reg.set_swstart(false); - reg.set_extsel(crate::pac::adc::vals::Extsel::SWSTART); + reg.set_extsel(7); // SWSTART }); // Configure the channel to sample diff --git a/embassy-stm32/src/can/mod.rs b/embassy-stm32/src/can/mod.rs index 4ff5aa0d..425f9ac2 100644 --- a/embassy-stm32/src/can/mod.rs +++ b/embassy-stm32/src/can/mod.rs @@ -1,6 +1,6 @@ #![macro_use] #[cfg_attr(can_bxcan, path = "bxcan.rs")] -#[cfg_attr(can_fdcan, path = "fdcan.rs")] +#[cfg_attr(any(can_fdcan_v1, can_fdcan_h7), path = "fdcan.rs")] mod _version; pub use _version::*; diff --git a/embassy-stm32/src/rcc/g4.rs b/embassy-stm32/src/rcc/g4.rs index 48b27255..7af05b48 100644 --- a/embassy-stm32/src/rcc/g4.rs +++ b/embassy-stm32/src/rcc/g4.rs @@ -315,6 +315,8 @@ pub(crate) unsafe fn init(config: Config) { adc: adc12_ck, adc34: adc345_ck, pll1_p: None, + pll1_q: None, // TODO + hse: None, // TODO rtc, }); } diff --git a/embassy-stm32/src/rcc/mod.rs b/embassy-stm32/src/rcc/mod.rs index 2e144dc7..40a5a619 100644 --- a/embassy-stm32/src/rcc/mod.rs +++ b/embassy-stm32/src/rcc/mod.rs @@ -119,7 +119,7 @@ pub struct Clocks { #[cfg(any(stm32g4, rcc_l4))] pub pll1_p: Option, - #[cfg(any(stm32h5, stm32h7, rcc_f2, rcc_f4, rcc_f410, rcc_f7, rcc_l4))] + #[cfg(any(stm32h5, stm32h7, stm32f2, stm32f4, stm32f7, rcc_l4, stm32g4))] pub pll1_q: Option, #[cfg(any(stm32h5, stm32h7))] pub pll2_p: Option, @@ -167,7 +167,7 @@ pub struct Clocks { #[cfg(any(stm32h5, stm32h7, rcc_l4, rcc_c0))] pub lse: Option, - #[cfg(any(stm32h5, stm32h7))] + #[cfg(any(stm32h5, stm32h7, stm32g4))] pub hse: Option, #[cfg(stm32h5)] From fe218ed978a76014b45410e188f974e20adba1a0 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Fri, 8 Dec 2023 20:24:15 +0100 Subject: [PATCH 15/20] tests/stm32: add L1 DAC/ADC test. --- tests/stm32/Cargo.toml | 17 ++++--- tests/stm32/src/bin/dac.rs | 5 +- tests/stm32/src/bin/dac_l1.rs | 86 +++++++++++++++++++++++++++++++++++ tests/stm32/src/common.rs | 9 ++-- 4 files changed, 105 insertions(+), 12 deletions(-) create mode 100644 tests/stm32/src/bin/dac_l1.rs diff --git a/tests/stm32/Cargo.toml b/tests/stm32/Cargo.toml index 8c2cfdf5..460c103b 100644 --- a/tests/stm32/Cargo.toml +++ b/tests/stm32/Cargo.toml @@ -10,14 +10,14 @@ stm32c031c6 = ["embassy-stm32/stm32c031c6", "cm0", "not-gpdma"] stm32f103c8 = ["embassy-stm32/stm32f103c8", "not-gpdma"] stm32f207zg = ["embassy-stm32/stm32f207zg", "chrono", "not-gpdma", "eth", "rng"] stm32f303ze = ["embassy-stm32/stm32f303ze", "chrono", "not-gpdma"] -stm32f429zi = ["embassy-stm32/stm32f429zi", "chrono", "eth", "stop", "can", "not-gpdma", "dac-adc-pin", "rng"] -stm32f446re = ["embassy-stm32/stm32f446re", "chrono", "stop", "can", "not-gpdma", "dac-adc-pin", "sdmmc"] +stm32f429zi = ["embassy-stm32/stm32f429zi", "chrono", "eth", "stop", "can", "not-gpdma", "dac", "rng"] +stm32f446re = ["embassy-stm32/stm32f446re", "chrono", "stop", "can", "not-gpdma", "dac", "sdmmc"] stm32f767zi = ["embassy-stm32/stm32f767zi", "chrono", "not-gpdma", "eth", "rng"] -stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac-adc-pin"] +stm32g071rb = ["embassy-stm32/stm32g071rb", "cm0", "not-gpdma", "dac"] stm32g491re = ["embassy-stm32/stm32g491re", "chrono", "stop", "not-gpdma", "rng"] stm32h563zi = ["embassy-stm32/stm32h563zi", "chrono", "eth", "rng"] stm32h753zi = ["embassy-stm32/stm32h753zi", "chrono", "not-gpdma", "eth", "rng"] -stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "chrono", "not-gpdma", "eth", "dac-adc-pin", "rng"] +stm32h755zi = ["embassy-stm32/stm32h755zi-cm7", "chrono", "not-gpdma", "eth", "dac", "rng"] stm32h7a3zi = ["embassy-stm32/stm32h7a3zi", "not-gpdma", "rng"] stm32l073rz = ["embassy-stm32/stm32l073rz", "cm0", "not-gpdma", "rng"] stm32l152re = ["embassy-stm32/stm32l152re", "chrono", "not-gpdma"] @@ -41,7 +41,7 @@ ble = ["dep:embassy-stm32-wpan", "embassy-stm32-wpan/ble"] mac = ["dep:embassy-stm32-wpan", "embassy-stm32-wpan/mac"] embassy-stm32-wpan = [] not-gpdma = [] -dac-adc-pin = [] +dac = [] cm0 = ["portable-atomic/unsafe-assume-single-core"] @@ -84,7 +84,12 @@ required-features = [ "can",] [[bin]] name = "dac" path = "src/bin/dac.rs" -required-features = [ "dac-adc-pin",] +required-features = [ "dac",] + +[[bin]] +name = "dac_l1" +path = "src/bin/dac_l1.rs" +required-features = [ "stm32l152re",] [[bin]] name = "eth" diff --git a/tests/stm32/src/bin/dac.rs b/tests/stm32/src/bin/dac.rs index cf43106b..9d64742d 100644 --- a/tests/stm32/src/bin/dac.rs +++ b/tests/stm32/src/bin/dac.rs @@ -1,7 +1,7 @@ #![no_std] #![no_main] -// required-features: dac-adc-pin +// required-features: dac #[path = "../common.rs"] mod common; @@ -22,12 +22,13 @@ async fn main(_spawner: Spawner) { // Initialize the board and obtain a Peripherals instance let p: embassy_stm32::Peripherals = embassy_stm32::init(config()); + let adc = peri!(p, ADC); let dac = peri!(p, DAC); let dac_pin = peri!(p, DAC_PIN); let mut adc_pin = unsafe { core::ptr::read(&dac_pin) }; let mut dac = DacCh1::new(dac, NoDma, dac_pin); - let mut adc = Adc::new(p.ADC1, &mut Delay); + let mut adc = Adc::new(adc, &mut Delay); #[cfg(feature = "stm32h755zi")] let normalization_factor = 256; diff --git a/tests/stm32/src/bin/dac_l1.rs b/tests/stm32/src/bin/dac_l1.rs new file mode 100644 index 00000000..f8b00aae --- /dev/null +++ b/tests/stm32/src/bin/dac_l1.rs @@ -0,0 +1,86 @@ +#![no_std] +#![no_main] + +// required-features: stm32l152re + +#[path = "../common.rs"] +mod common; +use core::f32::consts::PI; + +use common::*; +use defmt::assert; +use embassy_executor::Spawner; +use embassy_stm32::adc::Adc; +use embassy_stm32::dac::{DacCh1, Value}; +use embassy_stm32::dma::NoDma; +use embassy_stm32::{bind_interrupts, peripherals}; +use embassy_time::Timer; +use micromath::F32Ext; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + ADC1 => embassy_stm32::adc::InterruptHandler; +}); + +#[embassy_executor::main] +async fn main(_spawner: Spawner) { + // Initialize the board and obtain a Peripherals instance + let p: embassy_stm32::Peripherals = embassy_stm32::init(config()); + + let adc = peri!(p, ADC); + let dac = peri!(p, DAC); + let dac_pin = peri!(p, DAC_PIN); + let mut adc_pin = unsafe { core::ptr::read(&dac_pin) }; + + let mut dac = DacCh1::new(dac, NoDma, dac_pin); + let mut adc = Adc::new(adc, Irqs); + + #[cfg(feature = "stm32h755zi")] + let normalization_factor = 256; + #[cfg(any( + feature = "stm32f429zi", + feature = "stm32f446re", + feature = "stm32g071rb", + feature = "stm32l152re", + ))] + let normalization_factor: i32 = 16; + + dac.set(Value::Bit8(0)); + // Now wait a little to obtain a stable value + Timer::after_millis(30).await; + let offset = adc.read(&mut adc_pin).await; + + for v in 0..=255 { + // First set the DAC output value + let dac_output_val = to_sine_wave(v); + dac.set(Value::Bit8(dac_output_val)); + + // Now wait a little to obtain a stable value + Timer::after_millis(30).await; + + // Need to steal the peripherals here because PA4 is obviously in use already + let measured = adc.read(&mut unsafe { embassy_stm32::Peripherals::steal() }.PA4).await; + // Calibrate and normalize the measurement to get close to the dac_output_val + let measured_normalized = ((measured as i32 - offset as i32) / normalization_factor) as i16; + + info!("value / measured: {} / {}", dac_output_val, measured_normalized); + + // The deviations are quite enormous but that does not matter since this is only a quick test + assert!((dac_output_val as i16 - measured_normalized).abs() < 15); + } + + info!("Test OK"); + cortex_m::asm::bkpt(); +} + +fn to_sine_wave(v: u8) -> u8 { + if v >= 128 { + // top half + let r = PI * ((v - 128) as f32 / 128.0); + (r.sin() * 128.0 + 127.0) as u8 + } else { + // bottom half + let r = PI + PI * (v as f32 / 128.0); + (r.sin() * 128.0 + 127.0) as u8 + } +} diff --git a/tests/stm32/src/common.rs b/tests/stm32/src/common.rs index 155e1d9d..313380b3 100644 --- a/tests/stm32/src/common.rs +++ b/tests/stm32/src/common.rs @@ -101,14 +101,14 @@ define_peris!( define_peris!( UART = USART1, UART_TX = PC4, UART_RX = PC5, UART_TX_DMA = DMA1_CH1, UART_RX_DMA = DMA1_CH2, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH1, SPI_RX_DMA = DMA1_CH2, - DAC = DAC1, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, ); #[cfg(feature = "stm32f429zi")] define_peris!( UART = USART6, UART_TX = PG14, UART_RX = PG9, UART_TX_DMA = DMA2_CH6, UART_RX_DMA = DMA2_CH1, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA2_CH3, SPI_RX_DMA = DMA2_CH2, - DAC = DAC, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC, DAC_PIN = PA4, CAN = CAN1, CAN_RX = PD0, CAN_TX = PD1, @irq UART = {USART6 => embassy_stm32::usart::InterruptHandler;}, ); @@ -116,7 +116,7 @@ define_peris!( define_peris!( UART = USART1, UART_TX = PA9, UART_RX = PA10, UART_TX_DMA = DMA2_CH7, UART_RX_DMA = DMA2_CH5, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA2_CH3, SPI_RX_DMA = DMA2_CH2, - DAC = DAC, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC, DAC_PIN = PA4, CAN = CAN1, CAN_RX = PA11, CAN_TX = PA12, @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, ); @@ -130,7 +130,7 @@ define_peris!( define_peris!( UART = USART1, UART_TX = PB6, UART_RX = PB7, UART_TX_DMA = DMA1_CH0, UART_RX_DMA = DMA1_CH1, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PB5, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH0, SPI_RX_DMA = DMA1_CH1, - DAC = DAC1, DAC_PIN = PA4, + ADC = ADC1, DAC = DAC1, DAC_PIN = PA4, @irq UART = {USART1 => embassy_stm32::usart::InterruptHandler;}, ); #[cfg(feature = "stm32h7a3zi")] @@ -191,6 +191,7 @@ define_peris!( define_peris!( UART = USART3, UART_TX = PB10, UART_RX = PB11, UART_TX_DMA = DMA1_CH2, UART_RX_DMA = DMA1_CH3, SPI = SPI1, SPI_SCK = PA5, SPI_MOSI = PA7, SPI_MISO = PA6, SPI_TX_DMA = DMA1_CH3, SPI_RX_DMA = DMA1_CH2, + ADC = ADC, DAC = DAC, DAC_PIN = PA4, @irq UART = {USART3 => embassy_stm32::usart::InterruptHandler;}, ); #[cfg(feature = "stm32l552ze")] From 6c746dcf3944fdd2901697c2bab107033458e22c Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Fri, 8 Dec 2023 21:26:28 +0100 Subject: [PATCH 16/20] Document how to bind multiple interrupts and handlers in `bind_interrupts!`. --- embassy-nrf/src/lib.rs | 22 ++++++++++++++++++++++ embassy-rp/src/lib.rs | 11 +++++++++++ embassy-stm32/src/lib.rs | 23 +++++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/embassy-nrf/src/lib.rs b/embassy-nrf/src/lib.rs index 3274dafb..9093ad91 100644 --- a/embassy-nrf/src/lib.rs +++ b/embassy-nrf/src/lib.rs @@ -97,6 +97,28 @@ mod chip; /// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`) /// and implements the right [`Binding`]s for it. You can pass this struct to drivers to /// prove at compile-time that the right interrupts have been bound. +/// +/// Example of how to bind one interrupt: +/// +/// ```rust,ignore +/// use embassy_nrf::{bind_interrupts, spim, peripherals}; +/// +/// bind_interrupts!(struct Irqs { +/// SPIM3 => spim::InterruptHandler; +/// }); +/// ``` +/// +/// Example of how to bind multiple interrupts in a single macro invocation: +/// +/// ```rust,ignore +/// use embassy_nrf::{bind_interrupts, spim, twim, peripherals}; +/// +/// bind_interrupts!(struct Irqs { +/// SPIM3 => spim::InterruptHandler; +/// SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0 => twim::InterruptHandler; +/// }); +/// ``` + // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { diff --git a/embassy-rp/src/lib.rs b/embassy-rp/src/lib.rs index 66e4cfdc..5151323a 100644 --- a/embassy-rp/src/lib.rs +++ b/embassy-rp/src/lib.rs @@ -86,6 +86,17 @@ embassy_hal_internal::interrupt_mod!( /// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`) /// and implements the right [`Binding`]s for it. You can pass this struct to drivers to /// prove at compile-time that the right interrupts have been bound. +/// +/// Example of how to bind one interrupt: +/// +/// ```rust,ignore +/// use embassy_rp::{bind_interrupts, usb, peripherals}; +/// +/// bind_interrupts!(struct Irqs { +/// USBCTRL_IRQ => usb::InterruptHandler; +/// }); +/// ``` +/// // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index 13e189da..5d9b4e6a 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -90,6 +90,29 @@ pub use crate::_generated::interrupt; /// This defines the right interrupt handlers, and creates a unit struct (like `struct Irqs;`) /// and implements the right [`Binding`]s for it. You can pass this struct to drivers to /// prove at compile-time that the right interrupts have been bound. +/// +/// Example of how to bind one interrupt: +/// +/// ```rust,ignore +/// use embassy_stm32::{bind_interrupts, usb_otg, peripherals}; +/// +/// bind_interrupts!(struct Irqs { +/// OTG_FS => usb_otg::InterruptHandler; +/// }); +/// ``` +/// +/// Example of how to bind multiple interrupts, and multiple handlers to each interrupt, in a single macro invocation: +/// +/// ```rust,ignore +/// use embassy_stm32::{bind_interrupts, i2c, peripherals}; +/// +/// bind_interrupts!(struct Irqs { +/// I2C1 => i2c::EventInterruptHandler, i2c::ErrorInterruptHandler; +/// I2C2_3 => i2c::EventInterruptHandler, i2c::ErrorInterruptHandler, +/// i2c::EventInterruptHandler, i2c::ErrorInterruptHandler; +/// }); +/// ``` + // developer note: this macro can't be in `embassy-hal-internal` due to the use of `$crate`. #[macro_export] macro_rules! bind_interrupts { From 02b7a833d9855bd1db9665b8e9f311f0db93c156 Mon Sep 17 00:00:00 2001 From: Ulf Lilleengen Date: Fri, 8 Dec 2023 20:42:52 +0100 Subject: [PATCH 17/20] docs: document all public apis of embedded-hal-internal * Make some fields and functions non-public where possible. * Enable doc warnings for missing public API docs. --- embassy-hal-internal/src/atomic_ring_buffer.rs | 14 +++++++++++++- embassy-hal-internal/src/drop.rs | 7 ++++++- embassy-hal-internal/src/lib.rs | 1 + embassy-hal-internal/src/macros.rs | 5 +++++ embassy-hal-internal/src/peripheral.rs | 1 + embassy-hal-internal/src/ratio.rs | 1 + 6 files changed, 27 insertions(+), 2 deletions(-) diff --git a/embassy-hal-internal/src/atomic_ring_buffer.rs b/embassy-hal-internal/src/atomic_ring_buffer.rs index ea84925c..b4f2cec2 100644 --- a/embassy-hal-internal/src/atomic_ring_buffer.rs +++ b/embassy-hal-internal/src/atomic_ring_buffer.rs @@ -1,3 +1,4 @@ +//! Atomic reusable ringbuffer. use core::slice; use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; @@ -14,8 +15,9 @@ use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; /// One concurrent writer and one concurrent reader are supported, even at /// different execution priorities (like main and irq). pub struct RingBuffer { + #[doc(hidden)] pub buf: AtomicPtr, - pub len: AtomicUsize, + len: AtomicUsize, // start and end wrap at len*2, not at len. // This allows distinguishing "full" and "empty". @@ -24,11 +26,16 @@ pub struct RingBuffer { // // This avoids having to consider the ringbuffer "full" at len-1 instead of len. // The usual solution is adding a "full" flag, but that can't be made atomic + #[doc(hidden)] pub start: AtomicUsize, + #[doc(hidden)] pub end: AtomicUsize, } +/// A type which can only read from a ring buffer. pub struct Reader<'a>(&'a RingBuffer); + +/// A type which can only write to a ring buffer. pub struct Writer<'a>(&'a RingBuffer); impl RingBuffer { @@ -89,10 +96,12 @@ impl RingBuffer { Writer(self) } + /// Return length of buffer. pub fn len(&self) -> usize { self.len.load(Ordering::Relaxed) } + /// Check if buffer is full. pub fn is_full(&self) -> bool { let len = self.len.load(Ordering::Relaxed); let start = self.start.load(Ordering::Relaxed); @@ -101,6 +110,7 @@ impl RingBuffer { self.wrap(start + len) == end } + /// Check if buffer is empty. pub fn is_empty(&self) -> bool { let start = self.start.load(Ordering::Relaxed); let end = self.end.load(Ordering::Relaxed); @@ -238,6 +248,7 @@ impl<'a> Writer<'a> { [(unsafe { buf.add(end) }, n0), (buf, n1)] } + /// Mark n bytes as written and advance the write index. pub fn push_done(&mut self, n: usize) { trace!(" ringbuf: push {:?}", n); let end = self.0.end.load(Ordering::Relaxed); @@ -323,6 +334,7 @@ impl<'a> Reader<'a> { (unsafe { buf.add(start) }, n) } + /// Mark n bytes as read and allow advance the read index. pub fn pop_done(&mut self, n: usize) { trace!(" ringbuf: pop {:?}", n); diff --git a/embassy-hal-internal/src/drop.rs b/embassy-hal-internal/src/drop.rs index 7cd16aae..8383fcc1 100644 --- a/embassy-hal-internal/src/drop.rs +++ b/embassy-hal-internal/src/drop.rs @@ -1,16 +1,20 @@ +//! Types for controlling when drop is invoked. use core::mem; use core::mem::MaybeUninit; -#[must_use = "to delay the drop handler invokation to the end of the scope"] +/// A type to delay the drop handler invocation. +#[must_use = "to delay the drop handler invocation to the end of the scope"] pub struct OnDrop { f: MaybeUninit, } impl OnDrop { + /// Create a new instance. pub fn new(f: F) -> Self { Self { f: MaybeUninit::new(f) } } + /// Prevent drop handler from running. pub fn defuse(self) { mem::forget(self) } @@ -34,6 +38,7 @@ pub struct DropBomb { } impl DropBomb { + /// Create a new instance. pub fn new() -> Self { Self { _private: () } } diff --git a/embassy-hal-internal/src/lib.rs b/embassy-hal-internal/src/lib.rs index f3d59e58..89f20e99 100644 --- a/embassy-hal-internal/src/lib.rs +++ b/embassy-hal-internal/src/lib.rs @@ -1,6 +1,7 @@ #![no_std] #![allow(clippy::new_without_default)] #![doc = include_str!("../README.md")] +#![warn(missing_docs)] // This mod MUST go first, so that the others see its macros. pub(crate) mod fmt; diff --git a/embassy-hal-internal/src/macros.rs b/embassy-hal-internal/src/macros.rs index 97df3895..07cd8948 100644 --- a/embassy-hal-internal/src/macros.rs +++ b/embassy-hal-internal/src/macros.rs @@ -1,3 +1,4 @@ +/// Types for the peripheral singletons. #[macro_export] macro_rules! peripherals_definition { ($($(#[$cfg:meta])? $name:ident),*$(,)?) => { @@ -29,6 +30,7 @@ macro_rules! peripherals_definition { }; } +/// Define the peripherals struct. #[macro_export] macro_rules! peripherals_struct { ($($(#[$cfg:meta])? $name:ident),*$(,)?) => { @@ -87,6 +89,7 @@ macro_rules! peripherals_struct { }; } +/// Defining peripheral type. #[macro_export] macro_rules! peripherals { ($($(#[$cfg:meta])? $name:ident),*$(,)?) => { @@ -105,6 +108,7 @@ macro_rules! peripherals { }; } +/// Convenience converting into reference. #[macro_export] macro_rules! into_ref { ($($name:ident),*) => { @@ -114,6 +118,7 @@ macro_rules! into_ref { } } +/// Implement the peripheral trait. #[macro_export] macro_rules! impl_peripheral { ($type:ident) => { diff --git a/embassy-hal-internal/src/peripheral.rs b/embassy-hal-internal/src/peripheral.rs index 38b4c452..16d49edf 100644 --- a/embassy-hal-internal/src/peripheral.rs +++ b/embassy-hal-internal/src/peripheral.rs @@ -20,6 +20,7 @@ pub struct PeripheralRef<'a, T> { } impl<'a, T> PeripheralRef<'a, T> { + /// Create a new reference to a peripheral. #[inline] pub fn new(inner: T) -> Self { Self { diff --git a/embassy-hal-internal/src/ratio.rs b/embassy-hal-internal/src/ratio.rs index 9a8808a3..91dcfd47 100644 --- a/embassy-hal-internal/src/ratio.rs +++ b/embassy-hal-internal/src/ratio.rs @@ -1,3 +1,4 @@ +//! Types for dealing with rational numbers. use core::ops::{Add, Div, Mul}; use num_traits::{CheckedAdd, CheckedDiv, CheckedMul}; From 4d3fcd8d2d841dc4bce9f2f3308e9e9929a1330a Mon Sep 17 00:00:00 2001 From: Kaitlyn Kenwell Date: Fri, 8 Dec 2023 17:06:37 -0500 Subject: [PATCH 18/20] Assert CR2.USV on stm32wb55, wb35 series chips ref RM0434 p. 175 --- embassy-stm32/src/usb/usb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/embassy-stm32/src/usb/usb.rs b/embassy-stm32/src/usb/usb.rs index 9269ddd8..8b9a47f3 100644 --- a/embassy-stm32/src/usb/usb.rs +++ b/embassy-stm32/src/usb/usb.rs @@ -263,7 +263,7 @@ impl<'d, T: Instance> Driver<'d, T> { let regs = T::regs(); - #[cfg(stm32l5)] + #[cfg(any(stm32l5, stm32wb55, stm32wb35))] crate::pac::PWR.cr2().modify(|w| w.set_usv(true)); #[cfg(pwr_h5)] From 5973e69244e6b4a6f19af84bc004a139cf3f7688 Mon Sep 17 00:00:00 2001 From: Kaitlyn Kenwell Date: Fri, 8 Dec 2023 17:20:23 -0500 Subject: [PATCH 19/20] Conditionally compile line for all stm32wb chips --- embassy-stm32/src/usb/usb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/embassy-stm32/src/usb/usb.rs b/embassy-stm32/src/usb/usb.rs index 8b9a47f3..295dc919 100644 --- a/embassy-stm32/src/usb/usb.rs +++ b/embassy-stm32/src/usb/usb.rs @@ -263,7 +263,7 @@ impl<'d, T: Instance> Driver<'d, T> { let regs = T::regs(); - #[cfg(any(stm32l5, stm32wb55, stm32wb35))] + #[cfg(any(stm32l5, stm32wb))] crate::pac::PWR.cr2().modify(|w| w.set_usv(true)); #[cfg(pwr_h5)] From 4051aead0f50952d8b10242c00531e21f5b901f8 Mon Sep 17 00:00:00 2001 From: Dario Nieuwenhuis Date: Fri, 8 Dec 2023 23:29:48 +0100 Subject: [PATCH 20/20] stm32: update stm32-metapac. Fixes USB on STM32WB. --- embassy-stm32/Cargo.toml | 4 ++-- embassy-stm32/src/rcc/g4.rs | 1 + embassy-stm32/src/rcc/mod.rs | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 979d15c0..f8c4313e 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -58,7 +58,7 @@ rand_core = "0.6.3" sdio-host = "0.5.0" embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true } critical-section = "1.1" -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-019a5da1c47c092c199bc39a7f84fb444f2adcdf" } +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-8f5fcae8c289c1ad481cc3a2bb37db023a61599c" } vcell = "0.1.3" bxcan = "0.7.0" nb = "1.0.0" @@ -76,7 +76,7 @@ critical-section = { version = "1.1", features = ["std"] } [build-dependencies] proc-macro2 = "1.0.36" quote = "1.0.15" -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-019a5da1c47c092c199bc39a7f84fb444f2adcdf", default-features = false, features = ["metadata"]} +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-8f5fcae8c289c1ad481cc3a2bb37db023a61599c", default-features = false, features = ["metadata"]} [features] diff --git a/embassy-stm32/src/rcc/g4.rs b/embassy-stm32/src/rcc/g4.rs index 7af05b48..fca364c2 100644 --- a/embassy-stm32/src/rcc/g4.rs +++ b/embassy-stm32/src/rcc/g4.rs @@ -308,6 +308,7 @@ pub(crate) unsafe fn init(config: Config) { sys: sys_clk, hclk1: ahb_freq, hclk2: ahb_freq, + hclk3: ahb_freq, pclk1: apb1_freq, pclk1_tim: apb1_tim_freq, pclk2: apb2_freq, diff --git a/embassy-stm32/src/rcc/mod.rs b/embassy-stm32/src/rcc/mod.rs index 40a5a619..dc829a9a 100644 --- a/embassy-stm32/src/rcc/mod.rs +++ b/embassy-stm32/src/rcc/mod.rs @@ -95,6 +95,7 @@ pub struct Clocks { rcc_h7rm0433, rcc_h7ab, rcc_u5, + rcc_g4, rcc_wb, rcc_wl5, rcc_wle