From 0ba91ca555efc75dca603adbb51355c92b2fdb80 Mon Sep 17 00:00:00 2001 From: klownfish Date: Wed, 11 Sep 2024 11:55:16 +0200 Subject: [PATCH 01/12] WIP: u5 adc --- embassy-stm32/src/adc/mod.rs | 13 +- embassy-stm32/src/adc/u5.rs | 375 +++++++++++++++++++++++++++++++++++ 2 files changed, 383 insertions(+), 5 deletions(-) create mode 100644 embassy-stm32/src/adc/u5.rs diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 7a7d7cd8e..8ba586f5c 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -13,6 +13,7 @@ #[cfg_attr(any(adc_v3, adc_g0, adc_h5, adc_u0), path = "v3.rs")] #[cfg_attr(adc_v4, path = "v4.rs")] #[cfg_attr(adc_g4, path = "g4.rs")] +#[cfg_attr(adc_u5, path = "u5.rs")] mod _version; use core::marker::PhantomData; @@ -63,7 +64,7 @@ trait SealedInstance { } pub(crate) trait SealedAdcChannel { - #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))] fn setup(&mut self) {} #[allow(unused)] @@ -97,7 +98,8 @@ pub(crate) fn blocking_delay_us(us: u32) { adc_f3_v1_1, adc_g0, adc_u0, - adc_h5 + adc_h5, + adc_u5 )))] #[allow(private_bounds)] pub trait Instance: SealedInstance + crate::Peripheral

{ @@ -116,7 +118,8 @@ pub trait Instance: SealedInstance + crate::Peripheral

{ adc_f3_v1_1, adc_g0, adc_u0, - adc_h5 + adc_h5, + adc_u5 ))] #[allow(private_bounds)] pub trait Instance: SealedInstance + crate::Peripheral

+ crate::rcc::RccPeripheral { @@ -128,7 +131,7 @@ pub trait Instance: SealedInstance + crate::Peripheral

+ crate::rcc::R pub trait AdcChannel: SealedAdcChannel + Sized { #[allow(unused_mut)] fn degrade_adc(mut self) -> AnyAdcChannel { - #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))] self.setup(); AnyAdcChannel { @@ -183,7 +186,7 @@ macro_rules! impl_adc_pin { ($inst:ident, $pin:ident, $ch:expr) => { impl crate::adc::AdcChannel for crate::peripherals::$pin {} impl crate::adc::SealedAdcChannel for crate::peripherals::$pin { - #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4))] + #[cfg(any(adc_v1, adc_l0, adc_v2, adc_g4, adc_v4, adc_u5))] fn setup(&mut self) { ::set_as_analog(self); } diff --git a/embassy-stm32/src/adc/u5.rs b/embassy-stm32/src/adc/u5.rs new file mode 100644 index 000000000..9e6a94e5d --- /dev/null +++ b/embassy-stm32/src/adc/u5.rs @@ -0,0 +1,375 @@ +#[allow(unused)] +use pac::adc::vals::{Difsel, Exten, Pcsel}; +use pac::adccommon::vals::Presc; +use crate::peripherals::ADC4; + +use super::{ + blocking_delay_us, Adc, AdcChannel, AnyAdcChannel, Instance, Resolution, RxDma, SampleTime, SealedAdcChannel +}; +use crate::time::Hertz; +use crate::{pac, rcc, Peripheral}; + +// TODO: not correct +const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); +const VREF_CHANNEL: u8 = 19; +const TEMP_CHANNEL: u8 = 18; +const VBAT_CHANNEL: u8 = 17; + +/// Default VREF voltage used for sample conversion to millivolts. +pub const VREF_DEFAULT_MV: u32 = 3300; +/// VREF voltage used for factory calibration of VREFINTCAL register. +pub const VREF_CALIB_MV: u32 = 3300; + + +// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs +/// Internal voltage reference channel. +pub struct VrefInt; +impl AdcChannel for VrefInt {} +impl SealedAdcChannel for VrefInt { + fn channel(&self) -> u8 { + VREF_CHANNEL + } +} + +/// Internal temperature channel. +pub struct Temperature; +impl AdcChannel for Temperature {} +impl SealedAdcChannel for Temperature { + fn channel(&self) -> u8 { + TEMP_CHANNEL + } +} + +/// Internal battery voltage channel. +pub struct Vbat; +impl AdcChannel for Vbat {} +impl SealedAdcChannel for Vbat { + fn channel(&self) -> u8 { + VBAT_CHANNEL + } +} + +// NOTE (unused): The prescaler enum closely copies the hardware capabilities, +// but high prescaling doesn't make a lot of sense in the current implementation and is ommited. +#[allow(unused)] +enum Prescaler { + NotDivided, + DividedBy2, + DividedBy4, + DividedBy6, + DividedBy8, + DividedBy10, + DividedBy12, + DividedBy16, + DividedBy32, + DividedBy64, + DividedBy128, + DividedBy256, +} + +impl Prescaler { + fn from_ker_ck(frequency: Hertz) -> Self { + let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0; + match raw_prescaler { + 0 => Self::NotDivided, + 1 => Self::DividedBy2, + 2..=3 => Self::DividedBy4, + 4..=5 => Self::DividedBy6, + 6..=7 => Self::DividedBy8, + 8..=9 => Self::DividedBy10, + 10..=11 => Self::DividedBy12, + _ => unimplemented!(), + } + } + + fn divisor(&self) -> u32 { + match self { + Prescaler::NotDivided => 1, + Prescaler::DividedBy2 => 2, + Prescaler::DividedBy4 => 4, + Prescaler::DividedBy6 => 6, + Prescaler::DividedBy8 => 8, + Prescaler::DividedBy10 => 10, + Prescaler::DividedBy12 => 12, + Prescaler::DividedBy16 => 16, + Prescaler::DividedBy32 => 32, + Prescaler::DividedBy64 => 64, + Prescaler::DividedBy128 => 128, + Prescaler::DividedBy256 => 256, + } + } + + fn presc(&self) -> Presc { + match self { + Prescaler::NotDivided => Presc::DIV1, + Prescaler::DividedBy2 => Presc::DIV2, + Prescaler::DividedBy4 => Presc::DIV4, + Prescaler::DividedBy6 => Presc::DIV6, + Prescaler::DividedBy8 => Presc::DIV8, + Prescaler::DividedBy10 => Presc::DIV10, + Prescaler::DividedBy12 => Presc::DIV12, + Prescaler::DividedBy16 => Presc::DIV16, + Prescaler::DividedBy32 => Presc::DIV32, + Prescaler::DividedBy64 => Presc::DIV64, + Prescaler::DividedBy128 => Presc::DIV128, + Prescaler::DividedBy256 => Presc::DIV256, + } + } +} + +/// Number of samples used for averaging. +pub enum Averaging { + Disabled, + Samples2, + Samples4, + Samples8, + Samples16, + Samples32, + Samples64, + Samples128, + Samples256, + Samples512, + Samples1024, +} + +// TODO +// impl Instance for ADC4 { + +// } + +impl<'d, T: Instance> Adc<'d, T> { + /// Create a new ADC driver. + pub fn new(adc: impl Peripheral

+ 'd) -> Self { + embassy_hal_internal::into_ref!(adc); + rcc::enable_and_reset::(); + + let prescaler = Prescaler::from_ker_ck(T::frequency()); + + T::common_regs().ccr().modify(|w| w.set_presc(prescaler.presc())); + + let frequency = Hertz(T::frequency().0 / prescaler.divisor()); + info!("ADC frequency set to {} Hz", frequency.0); + + if frequency > MAX_ADC_CLK_FREQ { + panic!("Maximal allowed frequency for the ADC is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 ); + } + + let mut s = Self { + adc, + sample_time: SampleTime::from_bits(0), + }; + crate::pac::RCC.ahb2enr1().modify(|w| { + w.set_adc12en(true); + }); + blocking_delay_us(100); + + info!("chungus {}", line!()); + s.power_up(); + info!("chungus {}", line!()); + s.configure_differential_inputs(); + + info!("chungus {}", line!()); + s.calibrate(); + info!("chungus {}", line!()); + blocking_delay_us(1); + + info!("chungus {}", line!()); + s.enable(); + info!("chungus {}", line!()); + s.configure(); + info!("chungus {}", line!()); + + s + } + + fn power_up(&mut self) { + T::regs().isr().modify(|reg| { + reg.set_ldordy(true); + }); + info!("yummmum {}", T::regs().cr().as_ptr() as u32); + T::regs().cr().modify(|reg| { + info!("bajssis {}", reg.0); + reg.set_deeppwd(false); + info!("bajssis {}", reg.0); + reg.set_advregen(true); + info!("bajssis {}", reg.0); + }); + info!("kissis {}", T::regs().as_ptr() as u32); + info!("basdsadasadjsisssss{}", T::regs().isr().as_ptr() as u32); + while !T::regs().isr().read().ldordy() { + // info!("bajsisssss{}", T::regs().isr().read().0); + }; + + T::regs().isr().modify(|reg| { + reg.set_ldordy(true); + }); + } + + fn configure_differential_inputs(&mut self) { + T::regs().difsel().modify(|w| { + for n in 0..20 { + w.set_difsel(n, Difsel::SINGLEENDED); + } + }); + } + + fn calibrate(&mut self) { + T::regs().cr().modify(|w| { + w.set_adcallin(true); + w.set_aden(false) + }); + T::regs().calfact().modify(|w| { + w.set_capture_coef(false); + w.set_latch_coef(false) + }); + + T::regs().cr().modify(|w| w.set_adcal(true)); + while T::regs().cr().read().adcal() {} + } + + fn enable(&mut self) { + T::regs().isr().write(|w| w.set_adrdy(true)); + T::regs().cr().modify(|w| w.set_aden(true)); + while !T::regs().isr().read().adrdy() {} + T::regs().isr().write(|w| w.set_adrdy(true)); + } + + fn configure(&mut self) { + // single conversion mode, software trigger + T::regs().cfgr().modify(|w| { + w.set_cont(false); + w.set_exten(Exten::DISABLED); + }); + } + + /// Enable reading the voltage reference internal channel. + pub fn enable_vrefint(&self) -> VrefInt { + T::common_regs().ccr().modify(|reg| { + reg.set_vrefen(true); + }); + + VrefInt {} + } + + /// Enable reading the temperature internal channel. + pub fn enable_temperature(&self) -> Temperature { + T::common_regs().ccr().modify(|reg| { + reg.set_vsenseen(true); + }); + + Temperature {} + } + + /// Enable reading the vbat internal channel. + pub fn enable_vbat(&self) -> Vbat { + T::common_regs().ccr().modify(|reg| { + reg.set_vbaten(true); + }); + + Vbat {} + } + + /// Set the ADC sample time. + pub fn set_sample_time(&mut self, sample_time: SampleTime) { + self.sample_time = sample_time; + } + + /// Get the ADC sample time. + pub fn sample_time(&self) -> SampleTime { + self.sample_time + } + + /// Set the ADC resolution. + pub fn set_resolution(&mut self, resolution: Resolution) { + T::regs().cfgr().modify(|reg| reg.set_res(resolution.into())); + } + + /// Set hardware averaging. + pub fn set_averaging(&mut self, averaging: Averaging) { + let (enable, samples, right_shift) = match averaging { + Averaging::Disabled => (false, 0, 0), + Averaging::Samples2 => (true, 1, 1), + Averaging::Samples4 => (true, 3, 2), + Averaging::Samples8 => (true, 7, 3), + Averaging::Samples16 => (true, 15, 4), + Averaging::Samples32 => (true, 31, 5), + Averaging::Samples64 => (true, 63, 6), + Averaging::Samples128 => (true, 127, 7), + Averaging::Samples256 => (true, 255, 8), + Averaging::Samples512 => (true, 511, 9), + Averaging::Samples1024 => (true, 1023, 10), + }; + + T::regs().cfgr2().modify(|reg| { + reg.set_rovse(enable); + reg.set_osvr(samples); + reg.set_ovss(right_shift); + }) + } + + /// Perform a single conversion. + fn convert(&mut self) -> u16 { + T::regs().isr().modify(|reg| { + reg.set_eos(true); + reg.set_eoc(true); + }); + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + while !T::regs().isr().read().eos() { + // spin + } + + T::regs().dr().read().0 as u16 + } + + /// Read an ADC channel. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.read_channel(channel) + } + + fn configure_channel(channel: &mut impl AdcChannel, sample_time: SampleTime) { + channel.setup(); + + let channel = channel.channel(); + + Self::set_channel_sample_time(channel, sample_time); + + T::regs().cfgr2().modify(|w| w.set_lshift(0)); + T::regs() + .pcsel() + .modify(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED)); + } + + fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { + Self::configure_channel(channel, self.sample_time); + + T::regs().sqr1().modify(|reg| { + reg.set_sq(0, channel.channel()); + reg.set_l(0); + }); + + self.convert() + } + + fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { + let sample_time = sample_time.into(); + if ch <= 9 { + T::regs().smpr(0).modify(|reg| reg.set_smp(ch as _, sample_time)); + } else { + T::regs().smpr(1).modify(|reg| reg.set_smp((ch - 10) as _, sample_time)); + } + } + + fn cancel_conversions() { + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(true); + }); + while T::regs().cr().read().adstart() {} + } + } +} From 0fe9fa631a8f905809424bd7b31a7b74568eb5b6 Mon Sep 17 00:00:00 2001 From: klownfish Date: Tue, 17 Sep 2024 18:42:26 +0200 Subject: [PATCH 02/12] WIP: add u5 adc --- embassy-stm32/src/adc/mod.rs | 20 ++++++++-------- embassy-stm32/src/adc/u5.rs | 45 ++++++++++++++---------------------- 2 files changed, 26 insertions(+), 39 deletions(-) diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 9bf840f7c..3bd7c793d 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -4,7 +4,7 @@ #![allow(missing_docs)] // TODO #![cfg_attr(adc_f3_v2, allow(unused))] -#[cfg(not(any(adc_f3_v2, adc_u5)))] +#[cfg(not(any(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")] @@ -20,16 +20,14 @@ mod _version; use core::marker::PhantomData; #[allow(unused)] -#[cfg(not(any(adc_f3_v2, adc_u5)))] +#[cfg(not(any(adc_f3_v2)))] pub use _version::*; #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] use embassy_sync::waitqueue::AtomicWaker; -#[cfg(not(any(adc_u5)))] pub use crate::pac::adc::vals; -#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] +#[cfg(not(any(adc_f1, adc_f3_v2)))] pub use crate::pac::adc::vals::Res as Resolution; -#[cfg(not(any(adc_u5)))] pub use crate::pac::adc::vals::SampleTime; use crate::peripherals; @@ -39,7 +37,7 @@ dma_trait!(RxDma, Instance); pub struct Adc<'d, T: Instance> { #[allow(unused)] adc: crate::PeripheralRef<'d, T>, - #[cfg(not(any(adc_f3_v2, adc_f3_v1_1, adc_u5)))] + #[cfg(not(any(adc_f3_v2, adc_f3_v1_1)))] sample_time: SampleTime, } @@ -60,7 +58,7 @@ impl State { trait SealedInstance { #[allow(unused)] fn regs() -> crate::pac::adc::Adc; - #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] + #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0)))] #[allow(unused)] fn common_regs() -> crate::pac::adccommon::AdcCommon; #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] @@ -168,7 +166,7 @@ foreach_adc!( crate::pac::$inst } - #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0, adc_u5)))] + #[cfg(not(any(adc_f1, adc_v1, adc_l0, adc_f3_v2, adc_f3_v1_1, adc_g0)))] fn common_regs() -> crate::pac::adccommon::AdcCommon { return crate::pac::$common_inst } @@ -205,12 +203,12 @@ macro_rules! impl_adc_pin { /// Get the maximum reading value for this resolution. /// /// This is `2**n - 1`. -#[cfg(not(any(adc_f1, adc_f3_v2, adc_u5)))] +#[cfg(not(any(adc_f1, adc_f3_v2)))] pub const fn resolution_to_max_count(res: Resolution) -> u32 { match res { #[cfg(adc_v4)] Resolution::BITS16 => (1 << 16) - 1, - #[cfg(adc_v4)] + #[cfg(any(adc_v4, adc_u5))] Resolution::BITS14 => (1 << 14) - 1, #[cfg(adc_v4)] Resolution::BITS14V => (1 << 14) - 1, @@ -224,4 +222,4 @@ pub const fn resolution_to_max_count(res: Resolution) -> u32 { #[allow(unreachable_patterns)] _ => core::unreachable!(), } -} +} \ No newline at end of file diff --git a/embassy-stm32/src/adc/u5.rs b/embassy-stm32/src/adc/u5.rs index 9e6a94e5d..a86638a60 100644 --- a/embassy-stm32/src/adc/u5.rs +++ b/embassy-stm32/src/adc/u5.rs @@ -1,19 +1,19 @@ #[allow(unused)] use pac::adc::vals::{Difsel, Exten, Pcsel}; use pac::adccommon::vals::Presc; -use crate::peripherals::ADC4; +use pac::PWR; use super::{ - blocking_delay_us, Adc, AdcChannel, AnyAdcChannel, Instance, Resolution, RxDma, SampleTime, SealedAdcChannel + blocking_delay_us, Adc, AdcChannel, Instance, Resolution, SampleTime, SealedAdcChannel }; use crate::time::Hertz; use crate::{pac, rcc, Peripheral}; -// TODO: not correct const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); -const VREF_CHANNEL: u8 = 19; -const TEMP_CHANNEL: u8 = 18; -const VBAT_CHANNEL: u8 = 17; + +const VREF_CHANNEL: u8 = 1; +const VBAT_CHANNEL: u8 = 18; +const TEMP_CHANNEL: u8 = 19; /// Default VREF voltage used for sample conversion to millivolts. pub const VREF_DEFAULT_MV: u32 = 3300; @@ -140,9 +140,17 @@ pub enum Averaging { impl<'d, T: Instance> Adc<'d, T> { /// Create a new ADC driver. pub fn new(adc: impl Peripheral

+ 'd) -> Self { + // move to u5 init (RCC)? + PWR.svmcr().modify(|w| { + w.set_avm1en(true); + }); + while !PWR.svmsr().read().vdda1rdy() {} + PWR.svmcr().modify(|w| { + w.set_asv(true); + }); + embassy_hal_internal::into_ref!(adc); rcc::enable_and_reset::(); - let prescaler = Prescaler::from_ker_ck(T::frequency()); T::common_regs().ccr().modify(|w| w.set_presc(prescaler.presc())); @@ -158,26 +166,15 @@ impl<'d, T: Instance> Adc<'d, T> { adc, sample_time: SampleTime::from_bits(0), }; - crate::pac::RCC.ahb2enr1().modify(|w| { - w.set_adc12en(true); - }); - blocking_delay_us(100); - info!("chungus {}", line!()); s.power_up(); - info!("chungus {}", line!()); s.configure_differential_inputs(); - info!("chungus {}", line!()); s.calibrate(); - info!("chungus {}", line!()); blocking_delay_us(1); - info!("chungus {}", line!()); s.enable(); - info!("chungus {}", line!()); s.configure(); - info!("chungus {}", line!()); s } @@ -186,19 +183,11 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().isr().modify(|reg| { reg.set_ldordy(true); }); - info!("yummmum {}", T::regs().cr().as_ptr() as u32); T::regs().cr().modify(|reg| { - info!("bajssis {}", reg.0); reg.set_deeppwd(false); - info!("bajssis {}", reg.0); reg.set_advregen(true); - info!("bajssis {}", reg.0); }); - info!("kissis {}", T::regs().as_ptr() as u32); - info!("basdsadasadjsisssss{}", T::regs().isr().as_ptr() as u32); - while !T::regs().isr().read().ldordy() { - // info!("bajsisssss{}", T::regs().isr().read().0); - }; + while !T::regs().isr().read().ldordy() { }; T::regs().isr().modify(|reg| { reg.set_ldordy(true); @@ -372,4 +361,4 @@ impl<'d, T: Instance> Adc<'d, T> { while T::regs().cr().read().adstart() {} } } -} +} \ No newline at end of file From 3ce40f41fb25d7e473fc4a9584d6d9273ef08403 Mon Sep 17 00:00:00 2001 From: klownfish Date: Tue, 24 Sep 2024 19:03:20 +0200 Subject: [PATCH 03/12] WIP: add u5 adc4 --- embassy-stm32/build.rs | 9 +- embassy-stm32/src/adc/mod.rs | 38 +++ embassy-stm32/src/adc/u5.rs | 16 +- embassy-stm32/src/adc/u5_adc4.rs | 384 +++++++++++++++++++++++++++++++ embassy-stm32/src/lib.rs | 20 ++ 5 files changed, 450 insertions(+), 17 deletions(-) create mode 100644 embassy-stm32/src/adc/u5_adc4.rs diff --git a/embassy-stm32/build.rs b/embassy-stm32/build.rs index 19cf193d9..e4cd001e6 100644 --- a/embassy-stm32/build.rs +++ b/embassy-stm32/build.rs @@ -1188,13 +1188,12 @@ fn main() { // ======== // Generate dma_trait_impl! - let signals: HashMap<_, _> = [ + let mut signals: HashMap<_, _> = [ // (kind, signal) => trait (("adc", "ADC"), quote!(crate::adc::RxDma)), (("adc", "ADC1"), quote!(crate::adc::RxDma)), (("adc", "ADC2"), quote!(crate::adc::RxDma)), (("adc", "ADC3"), quote!(crate::adc::RxDma)), - (("adc", "ADC4"), quote!(crate::adc::RxDma)), (("ucpd", "RX"), quote!(crate::ucpd::RxDma)), (("ucpd", "TX"), quote!(crate::ucpd::TxDma)), (("usart", "RX"), quote!(crate::usart::RxDma)), @@ -1228,6 +1227,12 @@ fn main() { ] .into(); + if chip_name.starts_with("stm32u5") { + signals.insert(("adc", "ADC4"), quote!(crate::adc::RxDma4)); + } else { + signals.insert(("adc", "ADC4"), quote!(crate::adc::RxDma)); + } + for p in METADATA.peripherals { if let Some(regs) = &p.registers { // FIXME: stm32u5a crash on Cordic driver diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 3bd7c793d..80c942816 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -25,6 +25,10 @@ pub use _version::*; #[cfg(any(adc_f1, adc_f3, adc_v1, adc_l0, adc_f3_v1_1))] use embassy_sync::waitqueue::AtomicWaker; +#[cfg(adc_u5)] +#[path = "u5_adc4.rs"] +pub mod adc4; + pub use crate::pac::adc::vals; #[cfg(not(any(adc_f1, adc_f3_v2)))] pub use crate::pac::adc::vals::Res as Resolution; @@ -32,6 +36,8 @@ pub use crate::pac::adc::vals::SampleTime; use crate::peripherals; dma_trait!(RxDma, Instance); +#[cfg(adc_u5)] +dma_trait!(RxDma4, adc4::Instance); /// Analog to Digital driver. pub struct Adc<'d, T: Instance> { @@ -159,6 +165,38 @@ impl SealedAdcChannel for AnyAdcChannel { } } +#[cfg(adc_u5)] +foreach_adc!( + (ADC4, $common_inst:ident, $clock:ident) => { + impl crate::adc::adc4::SealedInstance for peripherals::ADC4 { + fn regs() -> crate::pac::adc::Adc4 { + crate::pac::ADC4 + } + } + + impl crate::adc::adc4::Instance for peripherals::ADC4 { + type Interrupt = crate::_generated::peripheral_interrupts::ADC4::GLOBAL; + } + }; + + ($inst:ident, $common_inst:ident, $clock:ident) => { + impl crate::adc::SealedInstance for peripherals::$inst { + fn regs() -> crate::pac::adc::Adc { + crate::pac::$inst + } + + fn common_regs() -> crate::pac::adccommon::AdcCommon { + return crate::pac::$common_inst + } + } + + impl crate::adc::Instance for peripherals::$inst { + type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL; + } + }; +); + +#[cfg(not(adc_u5))] foreach_adc!( ($inst:ident, $common_inst:ident, $clock:ident) => { impl crate::adc::SealedInstance for peripherals::$inst { diff --git a/embassy-stm32/src/adc/u5.rs b/embassy-stm32/src/adc/u5.rs index a86638a60..314cb02e2 100644 --- a/embassy-stm32/src/adc/u5.rs +++ b/embassy-stm32/src/adc/u5.rs @@ -11,7 +11,7 @@ use crate::{pac, rcc, Peripheral}; const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); -const VREF_CHANNEL: u8 = 1; +const VREF_CHANNEL: u8 = 0; const VBAT_CHANNEL: u8 = 18; const TEMP_CHANNEL: u8 = 19; @@ -132,23 +132,9 @@ pub enum Averaging { Samples1024, } -// TODO -// impl Instance for ADC4 { - -// } - impl<'d, T: Instance> Adc<'d, T> { /// Create a new ADC driver. pub fn new(adc: impl Peripheral

+ 'd) -> Self { - // move to u5 init (RCC)? - PWR.svmcr().modify(|w| { - w.set_avm1en(true); - }); - while !PWR.svmsr().read().vdda1rdy() {} - PWR.svmcr().modify(|w| { - w.set_asv(true); - }); - embassy_hal_internal::into_ref!(adc); rcc::enable_and_reset::(); let prescaler = Prescaler::from_ker_ck(T::frequency()); diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs new file mode 100644 index 000000000..5dec0caa9 --- /dev/null +++ b/embassy-stm32/src/adc/u5_adc4.rs @@ -0,0 +1,384 @@ +pub use crate::pac::adc::vals::Adc4Res as Resolution; +pub use crate::pac::adc::vals::Adc4SampleTime as SampleTime; +pub use crate::pac::adc::vals::Adc4Presc as Presc; +pub use crate::pac::adc::regs::Adc4Chselrmod0; + +#[allow(unused)] +use pac::adc::vals::{Adc4Exten, Adc4OversamplingRatio}; + +use super::{ + blocking_delay_us, AdcChannel, SealedAdcChannel +}; +use crate::time::Hertz; +use crate::{pac, rcc, Peripheral}; + +const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); + +/// Default VREF voltage used for sample conversion to millivolts. +pub const VREF_DEFAULT_MV: u32 = 3300; +/// VREF voltage used for factory calibration of VREFINTCAL register. +pub const VREF_CALIB_MV: u32 = 3300; + +const VREF_CHANNEL: u8 = 0; +const VCORE_CHANNEL: u8 = 12; +const TEMP_CHANNEL: u8 = 13; +const VBAT_CHANNEL: u8 = 14; +const DAC_CHANNEL: u8 = 21; + +// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs +/// Internal voltage reference channel. +pub struct VrefInt; +impl AdcChannel for VrefInt {} +impl SealedAdcChannel for VrefInt { + fn channel(&self) -> u8 { + VREF_CHANNEL + } +} + +/// Internal temperature channel. +pub struct Temperature; +impl AdcChannel for Temperature {} +impl SealedAdcChannel for Temperature { + fn channel(&self) -> u8 { + TEMP_CHANNEL + } +} + +/// Internal battery voltage channel. +pub struct Vbat; +impl AdcChannel for Vbat {} +impl SealedAdcChannel for Vbat { + fn channel(&self) -> u8 { + VBAT_CHANNEL + } +} + +/// Internal DAC channel. +pub struct Dac; +impl AdcChannel for Dac {} +impl SealedAdcChannel for Dac { + fn channel(&self) -> u8 { + DAC_CHANNEL + } +} + +/// Internal Vcore channel. +pub struct Vcore; +impl AdcChannel for Vcore {} +impl SealedAdcChannel for Vcore { + fn channel(&self) -> u8 { + VCORE_CHANNEL + } +} + +pub enum DacChannel { + OUT1, + OUT2 +} + +/// Number of samples used for averaging. +pub enum Averaging { + Disabled, + Samples2, + Samples4, + Samples8, + Samples16, + Samples32, + Samples64, + Samples128, + Samples256, +} + +pub const fn resolution_to_max_count(res: Resolution) -> u32 { + match res { + Resolution::BITS12 => (1 << 12) - 1, + Resolution::BITS10 => (1 << 10) - 1, + Resolution::BITS8 => (1 << 8) - 1, + Resolution::BITS6 => (1 << 6) - 1, + #[allow(unreachable_patterns)] + _ => core::unreachable!(), + } +} + +// NOTE (unused): The prescaler enum closely copies the hardware capabilities, +// but high prescaling doesn't make a lot of sense in the current implementation and is ommited. +#[allow(unused)] +enum Prescaler { + NotDivided, + DividedBy2, + DividedBy4, + DividedBy6, + DividedBy8, + DividedBy10, + DividedBy12, + DividedBy16, + DividedBy32, + DividedBy64, + DividedBy128, + DividedBy256, +} + +impl Prescaler { + fn from_ker_ck(frequency: Hertz) -> Self { + let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0; + match raw_prescaler { + 0 => Self::NotDivided, + 1 => Self::DividedBy2, + 2..=3 => Self::DividedBy4, + 4..=5 => Self::DividedBy6, + 6..=7 => Self::DividedBy8, + 8..=9 => Self::DividedBy10, + 10..=11 => Self::DividedBy12, + _ => unimplemented!(), + } + } + + fn divisor(&self) -> u32 { + match self { + Prescaler::NotDivided => 1, + Prescaler::DividedBy2 => 2, + Prescaler::DividedBy4 => 4, + Prescaler::DividedBy6 => 6, + Prescaler::DividedBy8 => 8, + Prescaler::DividedBy10 => 10, + Prescaler::DividedBy12 => 12, + Prescaler::DividedBy16 => 16, + Prescaler::DividedBy32 => 32, + Prescaler::DividedBy64 => 64, + Prescaler::DividedBy128 => 128, + Prescaler::DividedBy256 => 256, + } + } + + fn presc(&self) -> Presc { + match self { + Prescaler::NotDivided => Presc::DIV1, + Prescaler::DividedBy2 => Presc::DIV2, + Prescaler::DividedBy4 => Presc::DIV4, + Prescaler::DividedBy6 => Presc::DIV6, + Prescaler::DividedBy8 => Presc::DIV8, + Prescaler::DividedBy10 => Presc::DIV10, + Prescaler::DividedBy12 => Presc::DIV12, + Prescaler::DividedBy16 => Presc::DIV16, + Prescaler::DividedBy32 => Presc::DIV32, + Prescaler::DividedBy64 => Presc::DIV64, + Prescaler::DividedBy128 => Presc::DIV128, + Prescaler::DividedBy256 => Presc::DIV256, + } + } +} + +pub trait SealedInstance { + #[allow(unused)] + fn regs() -> crate::pac::adc::Adc4; +} + +pub trait Instance: SealedInstance + crate::Peripheral

+ crate::rcc::RccPeripheral { + type Interrupt: crate::interrupt::typelevel::Interrupt; +} + +pub struct Adc4<'d, T: Instance> { + adc: crate::PeripheralRef<'d, T>, +} + +impl<'d, T: Instance> Adc4<'d, T> { + /// Create a new ADC driver. + pub fn new(adc: impl Peripheral

+ 'd) -> Self { + embassy_hal_internal::into_ref!(adc); + rcc::enable_and_reset::(); + let prescaler = Prescaler::from_ker_ck(T::frequency()); + + T::regs().ccr().modify(|w| w.set_presc(prescaler.presc())); + + let frequency = Hertz(T::frequency().0 / prescaler.divisor()); + info!("ADC4 frequency set to {} Hz", frequency.0); + + if frequency > MAX_ADC_CLK_FREQ { + panic!("Maximal allowed frequency for ADC4 is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 ); + } + + let mut s = Self { + adc, + }; + + s.power_up(); + + s.calibrate(); + blocking_delay_us(1); + + s.enable(); + s.configure(); + + s + } + + fn power_up(&mut self) { + T::regs().isr().modify(|reg| { + reg.set_ldordy(true); + }); + T::regs().cr().modify(|reg| { + reg.set_advregen(true); + }); + while !T::regs().isr().read().ldordy() { }; + + T::regs().isr().modify(|reg| { + reg.set_ldordy(true); + }); + } + + fn calibrate(&mut self) { + T::regs().cr().modify(|w| w.set_adcal(true)); + while T::regs().cr().read().adcal() {} + T::regs().isr().modify(|w| w.set_eocal(true)); + } + + fn enable(&mut self) { + T::regs().isr().write(|w| w.set_adrdy(true)); + T::regs().cr().modify(|w| w.set_aden(true)); + while !T::regs().isr().read().adrdy() {} + T::regs().isr().write(|w| w.set_adrdy(true)); + } + + fn configure(&mut self) { + // single conversion mode, software trigger + T::regs().cfgr1().modify(|w| { + w.set_cont(false); + w.set_exten(Adc4Exten::DISABLED); + }); + + // only use one channel at the moment + T::regs().smpr().modify(|w| { + for i in 0..24 { + w.set_smpsel(i, false); + } + }); + } + + /// Enable reading the voltage reference internal channel. + pub fn enable_vrefint(&self) -> VrefInt { + T::regs().ccr().modify(|reg| { + reg.set_vrefen(true); + }); + + VrefInt {} + } + + /// Enable reading the temperature internal channel. + pub fn enable_temperature(&self) -> Temperature { + T::regs().ccr().modify(|reg| { + reg.set_vsensesel(true); + }); + + Temperature {} + } + + /// Enable reading the vbat internal channel. + pub fn enable_vbat(&self) -> Vbat { + T::regs().ccr().modify(|reg| { + reg.set_vbaten(true); + }); + + Vbat {} + } + + /// Enable reading the vbat internal channel. + pub fn enable_vcore(&self) -> Vcore { + Vcore {} + } + + /// Enable reading the vbat internal channel. + pub fn enable_dac_channel(&self, dac: DacChannel) -> Dac { + let mux; + match dac { + DacChannel::OUT1 => {mux = false}, + DacChannel::OUT2 => {mux = true} + } + T::regs().or().modify(|w| w.set_chn21sel(mux)); + Dac {} + } + + /// Set the ADC sample time. + pub fn set_sample_time(&mut self, sample_time: SampleTime) { + T::regs().smpr().modify(|w| { + w.set_smp(0, sample_time); + }); + } + + /// Get the ADC sample time. + pub fn sample_time(&self) -> SampleTime { + T::regs().smpr().read().smp(0) + } + + /// Set the ADC resolution. + pub fn set_resolution(&mut self, resolution: Resolution) { + T::regs().cfgr1().modify(|reg| reg.set_res(resolution.into())); + } + + /// Set hardware averaging. + pub fn set_averaging(&mut self, averaging: Averaging) { + let (enable, samples, right_shift) = match averaging { + Averaging::Disabled => (false, Adc4OversamplingRatio::OVERSAMPLE2X, 0), + Averaging::Samples2 => (true, Adc4OversamplingRatio::OVERSAMPLE2X, 1), + Averaging::Samples4 => (true, Adc4OversamplingRatio::OVERSAMPLE4X, 2), + Averaging::Samples8 => (true, Adc4OversamplingRatio::OVERSAMPLE8X, 3), + Averaging::Samples16 => (true, Adc4OversamplingRatio::OVERSAMPLE16X, 4), + Averaging::Samples32 => (true, Adc4OversamplingRatio::OVERSAMPLE32X, 5), + Averaging::Samples64 => (true, Adc4OversamplingRatio::OVERSAMPLE64X, 6), + Averaging::Samples128 => (true, Adc4OversamplingRatio::OVERSAMPLE128X, 7), + Averaging::Samples256 => (true, Adc4OversamplingRatio::OVERSAMPLE256X, 8), + }; + + T::regs().cfgr2().modify(|reg| { + reg.set_ovsr(samples); + reg.set_ovss(right_shift); + reg.set_ovse(enable) + }) + } + + /// Perform a single conversion. + fn convert(&mut self) -> u16 { + T::regs().isr().modify(|reg| { + reg.set_eos(true); + reg.set_eoc(true); + }); + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + while !T::regs().isr().read().eos() { + // spin + } + + T::regs().dr().read().0 as u16 + } + + /// Read an ADC channel. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { + self.read_channel(channel) + } + + fn configure_channel(channel: &mut impl AdcChannel) { + channel.setup(); + T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); + T::regs().chselrmod0().modify(|w| { + w.set_chsel(channel.channel() as usize, true); + }); + } + + fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { + Self::configure_channel(channel); + let ret = self.convert(); + ret + } + + fn cancel_conversions() { + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(true); + }); + while T::regs().cr().read().adstart() {} + } + } +} \ No newline at end of file diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index 451f595e0..232373087 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -218,6 +218,10 @@ pub struct Config { #[cfg(any(stm32l4, stm32l5, stm32u5))] pub enable_independent_io_supply: bool, + /// On the U5 series all analog peripherals are powere by a separate supply. + #[cfg(stm32u5)] + pub enable_independent_analog_supply: bool, + /// BDMA interrupt priority. /// /// Defaults to P0 (highest). @@ -257,6 +261,8 @@ impl Default for Config { enable_debug_during_sleep: true, #[cfg(any(stm32l4, stm32l5, stm32u5))] enable_independent_io_supply: true, + #[cfg(stm32u5)] + enable_independent_analog_supply: true, #[cfg(bdma)] bdma_interrupt_priority: Priority::P0, #[cfg(dma)] @@ -464,6 +470,20 @@ fn init_hw(config: Config) -> Peripherals { crate::pac::PWR.svmcr().modify(|w| { w.set_io2sv(config.enable_independent_io_supply); }); + if config.enable_independent_analog_supply { + crate::pac::PWR.svmcr().modify(|w| { + w.set_avm1en(true); + }); + while !crate::pac::PWR.svmsr().read().vdda1rdy() {} + crate::pac::PWR.svmcr().modify(|w| { + w.set_asv(true); + }); + } else { + crate::pac::PWR.svmcr().modify(|w| { + w.set_avm1en(false); + w.set_avm2en(false); + }); + } } // dead battery functionality is still present on these From fe868fc1948472666b6d8386a3191a074468a34e Mon Sep 17 00:00:00 2001 From: klownfish Date: Tue, 24 Sep 2024 19:12:41 +0200 Subject: [PATCH 04/12] add example for u5 ADC --- examples/stm32u5/src/bin/adc.rs | 69 +++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 examples/stm32u5/src/bin/adc.rs diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs new file mode 100644 index 000000000..f97facf9e --- /dev/null +++ b/examples/stm32u5/src/bin/adc.rs @@ -0,0 +1,69 @@ +#![no_std] +#![no_main] + + +use defmt::{*}; +use defmt_rtt as _; + +use embassy_stm32::adc; +use embassy_stm32::adc::adc4; +use panic_probe as _; + + +#[embassy_executor::main] +async fn main(spawner: embassy_executor::Spawner) { + let mut config = embassy_stm32::Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.hsi = true; + + config.rcc.pll1 = Some(Pll { + source: PllSource::HSI, // 16 MHz + prediv: PllPreDiv::DIV1, // 16 MHz + mul: PllMul::MUL10, // 160 MHz + divp: Some(PllDiv::DIV1), // don't care + divq: Some(PllDiv::DIV1), // don't care + divr: Some(PllDiv::DIV1), // 160 MHz + }); + + config.rcc.sys = Sysclk::PLL1_R; + config.rcc.voltage_range = VoltageScale::RANGE1; + config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB + config.rcc.mux.iclksel = mux::Iclksel::HSI48; // USB uses ICLK + + } + + let p = embassy_stm32::init(config); + info!("Hello World!"); + + let mut adc = adc::Adc::new(p.ADC1); + let mut adc_pin = p.PA3; + adc.set_resolution(adc::Resolution::BITS14); + adc.set_averaging(adc::Averaging::Samples1024); + adc.set_sample_time(adc::SampleTime::CYCLES1_5); + + let mut adc2 = adc::Adc::new(p.ADC2); + let mut adc_pin2 = p.PA5; + adc2.set_resolution(adc::Resolution::BITS14); + adc2.set_averaging(adc::Averaging::Samples1024); + adc2.set_sample_time(adc::SampleTime::CYCLES1_5); + + let mut adc4 = adc4::Adc4::new(p.ADC4); + let mut adc_pin4 = p.PD11; + adc4.set_resolution(adc4::Resolution::BITS12); + adc4.set_averaging(adc4::Averaging::Samples256); + adc4.set_sample_time(adc4::SampleTime::CYCLES1_5); + + loop { + embassy_time::Timer::after_millis(100).await; + let raw :u16 = adc.blocking_read(&mut adc_pin); + let max = adc::resolution_to_max_count(adc::Resolution::BITS14); + let volt: f32 = 3.3 * raw as f32 / max as f32; + info!("Read ADC1 {}", volt); + + let raw4 :u16 = adc4.blocking_read(&mut adc_pin4); + let max4 = adc4::resolution_to_max_count(adc4::Resolution::BITS12); + let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; + info!("Read ADC4 {}", volt4); + } +} \ No newline at end of file From 8c1b4faae1bd39594e2c331fa4bf9eea3ad22c9e Mon Sep 17 00:00:00 2001 From: klownfish Date: Wed, 25 Sep 2024 01:01:19 +0200 Subject: [PATCH 05/12] resuse adc v4 for u5 --- embassy-stm32/src/adc/mod.rs | 3 +- embassy-stm32/src/adc/u5.rs | 350 ----------------------------------- embassy-stm32/src/adc/v4.rs | 19 +- 3 files changed, 19 insertions(+), 353 deletions(-) delete mode 100644 embassy-stm32/src/adc/u5.rs diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 80c942816..3cf2ca72e 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -12,9 +12,8 @@ #[cfg_attr(adc_l0, path = "v1.rs")] #[cfg_attr(adc_v2, path = "v2.rs")] #[cfg_attr(any(adc_v3, adc_g0, adc_h5, adc_u0), path = "v3.rs")] -#[cfg_attr(adc_v4, path = "v4.rs")] +#[cfg_attr(any(adc_v4, adc_u5), path = "v4.rs")] #[cfg_attr(adc_g4, path = "g4.rs")] -#[cfg_attr(adc_u5, path = "u5.rs")] mod _version; use core::marker::PhantomData; diff --git a/embassy-stm32/src/adc/u5.rs b/embassy-stm32/src/adc/u5.rs deleted file mode 100644 index 314cb02e2..000000000 --- a/embassy-stm32/src/adc/u5.rs +++ /dev/null @@ -1,350 +0,0 @@ -#[allow(unused)] -use pac::adc::vals::{Difsel, Exten, Pcsel}; -use pac::adccommon::vals::Presc; -use pac::PWR; - -use super::{ - blocking_delay_us, Adc, AdcChannel, Instance, Resolution, SampleTime, SealedAdcChannel -}; -use crate::time::Hertz; -use crate::{pac, rcc, Peripheral}; - -const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); - -const VREF_CHANNEL: u8 = 0; -const VBAT_CHANNEL: u8 = 18; -const TEMP_CHANNEL: u8 = 19; - -/// Default VREF voltage used for sample conversion to millivolts. -pub const VREF_DEFAULT_MV: u32 = 3300; -/// VREF voltage used for factory calibration of VREFINTCAL register. -pub const VREF_CALIB_MV: u32 = 3300; - - -// NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs -/// Internal voltage reference channel. -pub struct VrefInt; -impl AdcChannel for VrefInt {} -impl SealedAdcChannel for VrefInt { - fn channel(&self) -> u8 { - VREF_CHANNEL - } -} - -/// Internal temperature channel. -pub struct Temperature; -impl AdcChannel for Temperature {} -impl SealedAdcChannel for Temperature { - fn channel(&self) -> u8 { - TEMP_CHANNEL - } -} - -/// Internal battery voltage channel. -pub struct Vbat; -impl AdcChannel for Vbat {} -impl SealedAdcChannel for Vbat { - fn channel(&self) -> u8 { - VBAT_CHANNEL - } -} - -// NOTE (unused): The prescaler enum closely copies the hardware capabilities, -// but high prescaling doesn't make a lot of sense in the current implementation and is ommited. -#[allow(unused)] -enum Prescaler { - NotDivided, - DividedBy2, - DividedBy4, - DividedBy6, - DividedBy8, - DividedBy10, - DividedBy12, - DividedBy16, - DividedBy32, - DividedBy64, - DividedBy128, - DividedBy256, -} - -impl Prescaler { - fn from_ker_ck(frequency: Hertz) -> Self { - let raw_prescaler = frequency.0 / MAX_ADC_CLK_FREQ.0; - match raw_prescaler { - 0 => Self::NotDivided, - 1 => Self::DividedBy2, - 2..=3 => Self::DividedBy4, - 4..=5 => Self::DividedBy6, - 6..=7 => Self::DividedBy8, - 8..=9 => Self::DividedBy10, - 10..=11 => Self::DividedBy12, - _ => unimplemented!(), - } - } - - fn divisor(&self) -> u32 { - match self { - Prescaler::NotDivided => 1, - Prescaler::DividedBy2 => 2, - Prescaler::DividedBy4 => 4, - Prescaler::DividedBy6 => 6, - Prescaler::DividedBy8 => 8, - Prescaler::DividedBy10 => 10, - Prescaler::DividedBy12 => 12, - Prescaler::DividedBy16 => 16, - Prescaler::DividedBy32 => 32, - Prescaler::DividedBy64 => 64, - Prescaler::DividedBy128 => 128, - Prescaler::DividedBy256 => 256, - } - } - - fn presc(&self) -> Presc { - match self { - Prescaler::NotDivided => Presc::DIV1, - Prescaler::DividedBy2 => Presc::DIV2, - Prescaler::DividedBy4 => Presc::DIV4, - Prescaler::DividedBy6 => Presc::DIV6, - Prescaler::DividedBy8 => Presc::DIV8, - Prescaler::DividedBy10 => Presc::DIV10, - Prescaler::DividedBy12 => Presc::DIV12, - Prescaler::DividedBy16 => Presc::DIV16, - Prescaler::DividedBy32 => Presc::DIV32, - Prescaler::DividedBy64 => Presc::DIV64, - Prescaler::DividedBy128 => Presc::DIV128, - Prescaler::DividedBy256 => Presc::DIV256, - } - } -} - -/// Number of samples used for averaging. -pub enum Averaging { - Disabled, - Samples2, - Samples4, - Samples8, - Samples16, - Samples32, - Samples64, - Samples128, - Samples256, - Samples512, - Samples1024, -} - -impl<'d, T: Instance> Adc<'d, T> { - /// Create a new ADC driver. - pub fn new(adc: impl Peripheral

+ 'd) -> Self { - embassy_hal_internal::into_ref!(adc); - rcc::enable_and_reset::(); - let prescaler = Prescaler::from_ker_ck(T::frequency()); - - T::common_regs().ccr().modify(|w| w.set_presc(prescaler.presc())); - - let frequency = Hertz(T::frequency().0 / prescaler.divisor()); - info!("ADC frequency set to {} Hz", frequency.0); - - if frequency > MAX_ADC_CLK_FREQ { - panic!("Maximal allowed frequency for the ADC is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 ); - } - - let mut s = Self { - adc, - sample_time: SampleTime::from_bits(0), - }; - - s.power_up(); - s.configure_differential_inputs(); - - s.calibrate(); - blocking_delay_us(1); - - s.enable(); - s.configure(); - - s - } - - fn power_up(&mut self) { - T::regs().isr().modify(|reg| { - reg.set_ldordy(true); - }); - T::regs().cr().modify(|reg| { - reg.set_deeppwd(false); - reg.set_advregen(true); - }); - while !T::regs().isr().read().ldordy() { }; - - T::regs().isr().modify(|reg| { - reg.set_ldordy(true); - }); - } - - fn configure_differential_inputs(&mut self) { - T::regs().difsel().modify(|w| { - for n in 0..20 { - w.set_difsel(n, Difsel::SINGLEENDED); - } - }); - } - - fn calibrate(&mut self) { - T::regs().cr().modify(|w| { - w.set_adcallin(true); - w.set_aden(false) - }); - T::regs().calfact().modify(|w| { - w.set_capture_coef(false); - w.set_latch_coef(false) - }); - - T::regs().cr().modify(|w| w.set_adcal(true)); - while T::regs().cr().read().adcal() {} - } - - fn enable(&mut self) { - T::regs().isr().write(|w| w.set_adrdy(true)); - T::regs().cr().modify(|w| w.set_aden(true)); - while !T::regs().isr().read().adrdy() {} - T::regs().isr().write(|w| w.set_adrdy(true)); - } - - fn configure(&mut self) { - // single conversion mode, software trigger - T::regs().cfgr().modify(|w| { - w.set_cont(false); - w.set_exten(Exten::DISABLED); - }); - } - - /// Enable reading the voltage reference internal channel. - pub fn enable_vrefint(&self) -> VrefInt { - T::common_regs().ccr().modify(|reg| { - reg.set_vrefen(true); - }); - - VrefInt {} - } - - /// Enable reading the temperature internal channel. - pub fn enable_temperature(&self) -> Temperature { - T::common_regs().ccr().modify(|reg| { - reg.set_vsenseen(true); - }); - - Temperature {} - } - - /// Enable reading the vbat internal channel. - pub fn enable_vbat(&self) -> Vbat { - T::common_regs().ccr().modify(|reg| { - reg.set_vbaten(true); - }); - - Vbat {} - } - - /// Set the ADC sample time. - pub fn set_sample_time(&mut self, sample_time: SampleTime) { - self.sample_time = sample_time; - } - - /// Get the ADC sample time. - pub fn sample_time(&self) -> SampleTime { - self.sample_time - } - - /// Set the ADC resolution. - pub fn set_resolution(&mut self, resolution: Resolution) { - T::regs().cfgr().modify(|reg| reg.set_res(resolution.into())); - } - - /// Set hardware averaging. - pub fn set_averaging(&mut self, averaging: Averaging) { - let (enable, samples, right_shift) = match averaging { - Averaging::Disabled => (false, 0, 0), - Averaging::Samples2 => (true, 1, 1), - Averaging::Samples4 => (true, 3, 2), - Averaging::Samples8 => (true, 7, 3), - Averaging::Samples16 => (true, 15, 4), - Averaging::Samples32 => (true, 31, 5), - Averaging::Samples64 => (true, 63, 6), - Averaging::Samples128 => (true, 127, 7), - Averaging::Samples256 => (true, 255, 8), - Averaging::Samples512 => (true, 511, 9), - Averaging::Samples1024 => (true, 1023, 10), - }; - - T::regs().cfgr2().modify(|reg| { - reg.set_rovse(enable); - reg.set_osvr(samples); - reg.set_ovss(right_shift); - }) - } - - /// Perform a single conversion. - fn convert(&mut self) -> u16 { - T::regs().isr().modify(|reg| { - reg.set_eos(true); - reg.set_eoc(true); - }); - - // Start conversion - T::regs().cr().modify(|reg| { - reg.set_adstart(true); - }); - - while !T::regs().isr().read().eos() { - // spin - } - - T::regs().dr().read().0 as u16 - } - - /// Read an ADC channel. - pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { - self.read_channel(channel) - } - - fn configure_channel(channel: &mut impl AdcChannel, sample_time: SampleTime) { - channel.setup(); - - let channel = channel.channel(); - - Self::set_channel_sample_time(channel, sample_time); - - T::regs().cfgr2().modify(|w| w.set_lshift(0)); - T::regs() - .pcsel() - .modify(|w| w.set_pcsel(channel as _, Pcsel::PRESELECTED)); - } - - fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { - Self::configure_channel(channel, self.sample_time); - - T::regs().sqr1().modify(|reg| { - reg.set_sq(0, channel.channel()); - reg.set_l(0); - }); - - self.convert() - } - - fn set_channel_sample_time(ch: u8, sample_time: SampleTime) { - let sample_time = sample_time.into(); - if ch <= 9 { - T::regs().smpr(0).modify(|reg| reg.set_smp(ch as _, sample_time)); - } else { - T::regs().smpr(1).modify(|reg| reg.set_smp((ch - 10) as _, sample_time)); - } - } - - fn cancel_conversions() { - if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { - T::regs().cr().modify(|reg| { - reg.set_adstp(true); - }); - while T::regs().cr().read().adstart() {} - } - } -} \ No newline at end of file diff --git a/embassy-stm32/src/adc/v4.rs b/embassy-stm32/src/adc/v4.rs index 63b5b58ea..d73bdb226 100644 --- a/embassy-stm32/src/adc/v4.rs +++ b/embassy-stm32/src/adc/v4.rs @@ -1,5 +1,9 @@ #[allow(unused)] -use pac::adc::vals::{Adcaldif, Adstp, Boost, Difsel, Dmngt, Exten, Pcsel}; +use pac::adc::vals::{Adstp, Difsel, Exten, Pcsel, Dmngt}; + +#[cfg(not(stm32u5))] +use pac::adc::vals::{Adcaldif, Boost}; + use pac::adccommon::vals::Presc; use super::{ @@ -19,6 +23,9 @@ pub const VREF_CALIB_MV: u32 = 3300; const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60); #[cfg(stm32h7)] const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50); +#[cfg(stm32u5)] +const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); + #[cfg(stm32g4)] const VREF_CHANNEL: u8 = 18; @@ -31,8 +38,17 @@ const VREF_CHANNEL: u8 = 19; const TEMP_CHANNEL: u8 = 18; // TODO this should be 14 for H7a/b/35 +#[cfg(not(stm32u5))] const VBAT_CHANNEL: u8 = 17; + +#[cfg(stm32u5)] +const VREF_CHANNEL: u8 = 0; +#[cfg(stm32u5)] +const TEMP_CHANNEL: u8 = 19; +#[cfg(stm32u5)] +const VBAT_CHANNEL: u8 = 18; + // NOTE: Vrefint/Temperature/Vbat are not available on all ADCs, this currently cannot be modeled with stm32-data, so these are available from the software on all ADCs /// Internal voltage reference channel. pub struct VrefInt; @@ -209,6 +225,7 @@ impl<'d, T: Instance> Adc<'d, T> { fn calibrate(&mut self) { T::regs().cr().modify(|w| { + #[cfg(not(adc_u5))] w.set_adcaldif(Adcaldif::SINGLEENDED); w.set_adcallin(true); }); From 7b45577704c43465587f611da125d86cb3c85207 Mon Sep 17 00:00:00 2001 From: klownfish Date: Wed, 25 Sep 2024 16:55:27 +0200 Subject: [PATCH 06/12] fix warnings --- embassy-stm32/src/adc/u5_adc4.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs index 5dec0caa9..8d0c1abed 100644 --- a/embassy-stm32/src/adc/u5_adc4.rs +++ b/embassy-stm32/src/adc/u5_adc4.rs @@ -178,6 +178,7 @@ pub trait Instance: SealedInstance + crate::Peripheral

+ crate::rcc::R } pub struct Adc4<'d, T: Instance> { + #[allow(unused)] adc: crate::PeripheralRef<'d, T>, } @@ -372,13 +373,4 @@ impl<'d, T: Instance> Adc4<'d, T> { let ret = self.convert(); ret } - - fn cancel_conversions() { - if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { - T::regs().cr().modify(|reg| { - reg.set_adstp(true); - }); - while T::regs().cr().read().adstart() {} - } - } } \ No newline at end of file From 8eeff8502d56612ce6fea55d01990a21e665ac43 Mon Sep 17 00:00:00 2001 From: klownfish Date: Wed, 18 Dec 2024 01:46:26 +0100 Subject: [PATCH 07/12] better u5 adc example --- examples/stm32u5/src/bin/adc.rs | 65 ++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 22 deletions(-) diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs index f97facf9e..049b985cf 100644 --- a/examples/stm32u5/src/bin/adc.rs +++ b/examples/stm32u5/src/bin/adc.rs @@ -6,6 +6,7 @@ use defmt::{*}; use defmt_rtt as _; use embassy_stm32::adc; +use embassy_stm32::adc::AdcChannel; use embassy_stm32::adc::adc4; use panic_probe as _; @@ -33,37 +34,57 @@ async fn main(spawner: embassy_executor::Spawner) { } - let p = embassy_stm32::init(config); - info!("Hello World!"); + let mut p = embassy_stm32::init(config); let mut adc = adc::Adc::new(p.ADC1); - let mut adc_pin = p.PA3; + let mut adc_pin1 = p.PA3; // A0 on nucleo u5a5 + let mut adc_pin2 = p.PA2; // A1 on nucleo u5a5 adc.set_resolution(adc::Resolution::BITS14); adc.set_averaging(adc::Averaging::Samples1024); - adc.set_sample_time(adc::SampleTime::CYCLES1_5); - - let mut adc2 = adc::Adc::new(p.ADC2); - let mut adc_pin2 = p.PA5; - adc2.set_resolution(adc::Resolution::BITS14); - adc2.set_averaging(adc::Averaging::Samples1024); - adc2.set_sample_time(adc::SampleTime::CYCLES1_5); + adc.set_sample_time(adc::SampleTime::CYCLES160_5); + let max = adc::resolution_to_max_count(adc::Resolution::BITS14); let mut adc4 = adc4::Adc4::new(p.ADC4); - let mut adc_pin4 = p.PD11; + let mut adc4_pin1 = p.PD11; + let mut adc4_pin2 = p.PC0; adc4.set_resolution(adc4::Resolution::BITS12); adc4.set_averaging(adc4::Averaging::Samples256); adc4.set_sample_time(adc4::SampleTime::CYCLES1_5); + let max4 = adc4::resolution_to_max_count(adc4::Resolution::BITS12); - loop { - embassy_time::Timer::after_millis(100).await; - let raw :u16 = adc.blocking_read(&mut adc_pin); - let max = adc::resolution_to_max_count(adc::Resolution::BITS14); - let volt: f32 = 3.3 * raw as f32 / max as f32; - info!("Read ADC1 {}", volt); + let raw: u16 = adc.blocking_read(&mut adc_pin1); + let volt: f32 = 3.3 * raw as f32 / max as f32; + info!("Read 1 pin 1 {}", volt); + + let raw: u16 = adc.blocking_read(&mut adc_pin2); + let volt: f32 = 3.3 * raw as f32 / max as f32; + info!("Read 1 pin 2 {}", volt); + + let raw4: u16 = adc4.blocking_read(&mut adc4_pin1); + let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; + info!("Read 4 pin 1 {}", volt4); + + let raw4: u16 = adc4.blocking_read(&mut adc4_pin2); + let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; + info!("Read 4 pin 2 {}", volt4); + + let mut degraded1 = adc_pin1.degrade_adc(); + let mut degraded2 = adc_pin2.degrade_adc(); + let mut measurements = [0u16; 2]; + + adc.read( + &mut p.GPDMA1_CH0, + [ + (&mut degraded2, adc::SampleTime::CYCLES160_5), + (&mut degraded1, adc::SampleTime::CYCLES160_5), + ] + .into_iter(), + &mut measurements, + ).await; + let volt1: f32 = 3.3 * measurements[1] as f32 / max as f32; + let volt2: f32 = 3.3 * measurements[0] as f32 / max as f32; + + info!("Async read 1 pin 1 {}", volt1); + info!("Async read 1 pin 2 {}", volt2); - let raw4 :u16 = adc4.blocking_read(&mut adc_pin4); - let max4 = adc4::resolution_to_max_count(adc4::Resolution::BITS12); - let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; - info!("Read ADC4 {}", volt4); - } } \ No newline at end of file From 8678911028a591d72fd1d8418407b5885ed4c417 Mon Sep 17 00:00:00 2001 From: klownfish Date: Wed, 18 Dec 2024 01:46:53 +0100 Subject: [PATCH 08/12] fix adc for u5 --- embassy-stm32/src/adc/v4.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/embassy-stm32/src/adc/v4.rs b/embassy-stm32/src/adc/v4.rs index d73bdb226..96dae25bd 100644 --- a/embassy-stm32/src/adc/v4.rs +++ b/embassy-stm32/src/adc/v4.rs @@ -463,7 +463,7 @@ impl<'d, T: Instance> Adc<'d, T> { Self::set_channel_sample_time(channel, sample_time); - #[cfg(stm32h7)] + #[cfg(any(stm32h7, stm32u5))] { T::regs().cfgr2().modify(|w| w.set_lshift(0)); T::regs() From d1692494823c2be9423d74d446f555a879344a0c Mon Sep 17 00:00:00 2001 From: klownfish Date: Thu, 26 Dec 2024 22:26:01 +0100 Subject: [PATCH 09/12] update metapac version --- embassy-stm32/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/embassy-stm32/Cargo.toml b/embassy-stm32/Cargo.toml index 47e9e8bb9..1d96a6a61 100644 --- a/embassy-stm32/Cargo.toml +++ b/embassy-stm32/Cargo.toml @@ -73,7 +73,7 @@ rand_core = "0.6.3" sdio-host = "0.5.0" critical-section = "1.1" #stm32-metapac = { version = "15" } -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-ddb0e7abab14bf3e1399875767b8834442382988" } +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-392e41259ffc5ffbfd79169ee80451114fb367fe" } vcell = "0.1.3" nb = "1.0.0" @@ -102,7 +102,7 @@ proc-macro2 = "1.0.36" quote = "1.0.15" #stm32-metapac = { version = "15", default-features = false, features = ["metadata"]} -stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-ddb0e7abab14bf3e1399875767b8834442382988", default-features = false, features = ["metadata"] } +stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-392e41259ffc5ffbfd79169ee80451114fb367fe", default-features = false, features = ["metadata"] } [features] default = ["rt"] From 4f4740eeb25e0db607a7f700e29efd313dd1942d Mon Sep 17 00:00:00 2001 From: klownfish Date: Fri, 27 Dec 2024 00:24:47 +0100 Subject: [PATCH 10/12] add async read for u5 ADC4 --- embassy-stm32/src/adc/u5_adc4.rs | 122 ++++++++++++++++++++++++++----- examples/stm32u5/src/bin/adc.rs | 100 ++++++++++++++++++------- 2 files changed, 177 insertions(+), 45 deletions(-) diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs index 8d0c1abed..ddc1b58a2 100644 --- a/embassy-stm32/src/adc/u5_adc4.rs +++ b/embassy-stm32/src/adc/u5_adc4.rs @@ -4,13 +4,14 @@ pub use crate::pac::adc::vals::Adc4Presc as Presc; pub use crate::pac::adc::regs::Adc4Chselrmod0; #[allow(unused)] -use pac::adc::vals::{Adc4Exten, Adc4OversamplingRatio}; +use pac::adc::vals::{Adc4Exten, Adc4OversamplingRatio, Adc4Dmacfg}; use super::{ - blocking_delay_us, AdcChannel, SealedAdcChannel + blocking_delay_us, AdcChannel, SealedAdcChannel, AnyAdcChannel, RxDma4 }; use crate::time::Hertz; use crate::{pac, rcc, Peripheral}; +use crate::dma::Transfer; const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); @@ -182,6 +183,12 @@ pub struct Adc4<'d, T: Instance> { adc: crate::PeripheralRef<'d, T>, } +#[derive(Debug)] +pub enum Adc4Error { + InvalidSequence, + DMAError +} + impl<'d, T: Instance> Adc4<'d, T> { /// Create a new ADC driver. pub fn new(adc: impl Peripheral

+ 'd) -> Self { @@ -244,6 +251,7 @@ impl<'d, T: Instance> Adc4<'d, T> { // single conversion mode, software trigger T::regs().cfgr1().modify(|w| { w.set_cont(false); + w.set_discen(false); w.set_exten(Adc4Exten::DISABLED); }); @@ -336,8 +344,18 @@ impl<'d, T: Instance> Adc4<'d, T> { }) } - /// Perform a single conversion. - fn convert(&mut self) -> u16 { + /// Read an ADC channel. + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16{ + channel.setup(); + T::regs().cfgr1().modify(|reg| { + reg.set_chselrmod(false); + }); + + T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); + T::regs().chselrmod0().modify(|w| { + w.set_chsel(channel.channel() as usize, true); + }); + T::regs().isr().modify(|reg| { reg.set_eos(true); reg.set_eoc(true); @@ -355,22 +373,92 @@ impl<'d, T: Instance> Adc4<'d, T> { T::regs().dr().read().0 as u16 } - /// Read an ADC channel. - pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { - self.read_channel(channel) - } + /// Channels can not be repeated and must be in ascending order! + /// TODO: broken + pub async fn read( + &mut self, + rx_dma: &mut impl RxDma4, + sequence: impl ExactSizeIterator>, + readings: &mut [u16], + ) -> Result<(), Adc4Error> { + assert!(sequence.len() != 0, "Asynchronous read sequence cannot be empty"); + assert!( + sequence.len() == readings.len(), + "Sequence length must be equal to readings length" + ); - fn configure_channel(channel: &mut impl AdcChannel) { - channel.setup(); - T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); - T::regs().chselrmod0().modify(|w| { - w.set_chsel(channel.channel() as usize, true); + // Ensure no conversions are ongoing + Self::cancel_conversions(); + + T::regs().isr().modify(|reg| { + reg.set_ovr(true); + reg.set_eos(true); + reg.set_eoc(true); }); + + T::regs().cfgr1().modify(|reg| { + reg.set_dmaen(true); + reg.set_dmacfg(Adc4Dmacfg::ONESHOT); + reg.set_chselrmod(false); + }); + + + let mut prev_channel: i16 = -1; + T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); + for channel in sequence { + let channel_num = channel.channel; + if channel_num as i16 <= prev_channel { + return Err(Adc4Error::InvalidSequence); + }; + prev_channel = channel_num as i16; + + T::regs().chselrmod0().modify(|w| { + w.set_chsel(channel.channel as usize, true); + }); + }; + + let request = rx_dma.request(); + let transfer = unsafe { + Transfer::new_read( + rx_dma, + request, + T::regs().dr().as_ptr() as *mut u16, + readings, + Default::default(), + ) + }; + + // Start conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + + // Wait for conversion sequence to finish. + transfer.await; + + blocking_delay_us(10); + + // Ensure conversions are finished. + Self::cancel_conversions(); + + // Reset configuration. + T::regs().cfgr1().modify(|reg| { + reg.set_dmaen(false); + }); + + if T::regs().isr().read().ovr() { + Err(Adc4Error::DMAError) + } else { + Ok(()) + } } - fn read_channel(&mut self, channel: &mut impl AdcChannel) -> u16 { - Self::configure_channel(channel); - let ret = self.convert(); - ret + fn cancel_conversions() { + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(true); + }); + while T::regs().cr().read().adstart() {} + } } } \ No newline at end of file diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs index 049b985cf..4632f2cd1 100644 --- a/examples/stm32u5/src/bin/adc.rs +++ b/examples/stm32u5/src/bin/adc.rs @@ -36,55 +36,99 @@ async fn main(spawner: embassy_executor::Spawner) { let mut p = embassy_stm32::init(config); - let mut adc = adc::Adc::new(p.ADC1); - let mut adc_pin1 = p.PA3; // A0 on nucleo u5a5 - let mut adc_pin2 = p.PA2; // A1 on nucleo u5a5 - adc.set_resolution(adc::Resolution::BITS14); - adc.set_averaging(adc::Averaging::Samples1024); - adc.set_sample_time(adc::SampleTime::CYCLES160_5); - let max = adc::resolution_to_max_count(adc::Resolution::BITS14); + // **** ADC1 init **** + let mut adc1 = adc::Adc::new(p.ADC1); + let mut adc1_pin1 = p.PA3; // A0 on nucleo u5a5 + let mut adc1_pin2 = p.PA2; // A1 + adc1.set_resolution(adc::Resolution::BITS14); + adc1.set_averaging(adc::Averaging::Samples1024); + adc1.set_sample_time(adc::SampleTime::CYCLES160_5); + let max1 = adc::resolution_to_max_count(adc::Resolution::BITS14); + // **** ADC2 init **** + let mut adc2 = adc::Adc::new(p.ADC2); + let mut adc2_pin1 = p.PC3; // A2 + let mut adc2_pin2 = p.PB0; // A3 + adc2.set_resolution(adc::Resolution::BITS14); + adc2.set_averaging(adc::Averaging::Samples1024); + adc2.set_sample_time(adc::SampleTime::CYCLES160_5); + let max2 = adc::resolution_to_max_count(adc::Resolution::BITS14); + + // **** ADC4 init **** let mut adc4 = adc4::Adc4::new(p.ADC4); - let mut adc4_pin1 = p.PD11; - let mut adc4_pin2 = p.PC0; + let mut adc4_pin1 = p.PC1; // A4 + let mut adc4_pin2 = p.PC0; // A5 adc4.set_resolution(adc4::Resolution::BITS12); adc4.set_averaging(adc4::Averaging::Samples256); adc4.set_sample_time(adc4::SampleTime::CYCLES1_5); let max4 = adc4::resolution_to_max_count(adc4::Resolution::BITS12); - let raw: u16 = adc.blocking_read(&mut adc_pin1); - let volt: f32 = 3.3 * raw as f32 / max as f32; - info!("Read 1 pin 1 {}", volt); + // **** ADC1 blocking read **** + let raw: u16 = adc1.blocking_read(&mut adc1_pin1); + let volt: f32 = 3.3 * raw as f32 / max1 as f32; + info!("Read adc1 pin 1 {}", volt); - let raw: u16 = adc.blocking_read(&mut adc_pin2); - let volt: f32 = 3.3 * raw as f32 / max as f32; - info!("Read 1 pin 2 {}", volt); + let raw: u16 = adc1.blocking_read(&mut adc1_pin2); + let volt: f32 = 3.3 * raw as f32 / max1 as f32; + info!("Read adc1 pin 2 {}", volt); - let raw4: u16 = adc4.blocking_read(&mut adc4_pin1); - let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; - info!("Read 4 pin 1 {}", volt4); + // **** ADC2 blocking read **** + let raw: u16 = adc2.blocking_read(&mut adc2_pin1); + let volt: f32 = 3.3 * raw as f32 / max2 as f32; + info!("Read adc2 pin 1 {}", volt); - let raw4: u16 = adc4.blocking_read(&mut adc4_pin2); - let volt4: f32 = 3.3 * raw4 as f32 / max4 as f32; - info!("Read 4 pin 2 {}", volt4); + let raw: u16 = adc2.blocking_read(&mut adc2_pin2); + let volt: f32 = 3.3 * raw as f32 / max2 as f32; + info!("Read adc2 pin 2 {}", volt); - let mut degraded1 = adc_pin1.degrade_adc(); - let mut degraded2 = adc_pin2.degrade_adc(); + // **** ADC4 blocking read **** + let raw: u16 = adc4.blocking_read(&mut adc4_pin1); + let volt: f32 = 3.3 * raw as f32 / max4 as f32; + info!("Read adc4 pin 1 {}", volt); + + let raw: u16 = adc4.blocking_read(&mut adc4_pin2); + let volt: f32 = 3.3 * raw as f32 / max4 as f32; + info!("Read adc4 pin 2 {}", volt); + + // **** ADC1 async read **** + let mut degraded11 = adc1_pin1.degrade_adc(); + let mut degraded12 = adc1_pin2.degrade_adc(); let mut measurements = [0u16; 2]; - adc.read( + adc1.read( &mut p.GPDMA1_CH0, [ - (&mut degraded2, adc::SampleTime::CYCLES160_5), - (&mut degraded1, adc::SampleTime::CYCLES160_5), + (&mut degraded11, adc::SampleTime::CYCLES160_5), + (&mut degraded12, adc::SampleTime::CYCLES160_5), ] .into_iter(), &mut measurements, ).await; - let volt1: f32 = 3.3 * measurements[1] as f32 / max as f32; - let volt2: f32 = 3.3 * measurements[0] as f32 / max as f32; + let volt1: f32 = 3.3 * measurements[0] as f32 / max1 as f32; + let volt2: f32 = 3.3 * measurements[1] as f32 / max1 as f32; info!("Async read 1 pin 1 {}", volt1); info!("Async read 1 pin 2 {}", volt2); + // **** ADC2 does not support async read **** + + // **** ADC4 async read **** + let mut degraded41 = adc4_pin1.degrade_adc(); + let mut degraded42 = adc4_pin2.degrade_adc(); + let mut measurements = [0u16; 2]; + + // The channels must be in ascending order and can't repeat for ADC4 + adc4.read( + &mut p.GPDMA1_CH1, + [ + &mut degraded42, + &mut degraded41, + ] + .into_iter(), + &mut measurements, + ).await.unwrap(); + let volt2: f32 = 3.3 * measurements[0] as f32 / max4 as f32; + let volt1: f32 = 3.3 * measurements[1] as f32 / max4 as f32; + info!("Async read 4 pin 1 {}", volt1); + info!("Async read 4 pin 2 {}", volt2); } \ No newline at end of file From a5a90156ce2eeb09760075cecf0eea8f4d1a9e73 Mon Sep 17 00:00:00 2001 From: klownfish Date: Fri, 27 Dec 2024 02:54:38 +0100 Subject: [PATCH 11/12] cleanup --- embassy-stm32/src/adc/u5_adc4.rs | 74 +++++++++++++++++++++----------- embassy-stm32/src/lib.rs | 2 +- examples/stm32u5/src/bin/adc.rs | 19 -------- 3 files changed, 49 insertions(+), 46 deletions(-) diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs index ddc1b58a2..468d16640 100644 --- a/embassy-stm32/src/adc/u5_adc4.rs +++ b/embassy-stm32/src/adc/u5_adc4.rs @@ -221,16 +221,16 @@ impl<'d, T: Instance> Adc4<'d, T> { } fn power_up(&mut self) { - T::regs().isr().modify(|reg| { - reg.set_ldordy(true); + T::regs().isr().modify(|w| { + w.set_ldordy(true); }); - T::regs().cr().modify(|reg| { - reg.set_advregen(true); + T::regs().cr().modify(|w| { + w.set_advregen(true); }); while !T::regs().isr().read().ldordy() { }; - T::regs().isr().modify(|reg| { - reg.set_ldordy(true); + T::regs().isr().modify(|w| { + w.set_ldordy(true); }); } @@ -253,6 +253,7 @@ impl<'d, T: Instance> Adc4<'d, T> { w.set_cont(false); w.set_discen(false); w.set_exten(Adc4Exten::DISABLED); + w.set_chselrmod(false); }); // only use one channel at the moment @@ -265,8 +266,8 @@ impl<'d, T: Instance> Adc4<'d, T> { /// Enable reading the voltage reference internal channel. pub fn enable_vrefint(&self) -> VrefInt { - T::regs().ccr().modify(|reg| { - reg.set_vrefen(true); + T::regs().ccr().modify(|w| { + w.set_vrefen(true); }); VrefInt {} @@ -274,8 +275,8 @@ impl<'d, T: Instance> Adc4<'d, T> { /// Enable reading the temperature internal channel. pub fn enable_temperature(&self) -> Temperature { - T::regs().ccr().modify(|reg| { - reg.set_vsensesel(true); + T::regs().ccr().modify(|w| { + w.set_vsensesel(true); }); Temperature {} @@ -283,8 +284,8 @@ impl<'d, T: Instance> Adc4<'d, T> { /// Enable reading the vbat internal channel. pub fn enable_vbat(&self) -> Vbat { - T::regs().ccr().modify(|reg| { - reg.set_vbaten(true); + T::regs().ccr().modify(|w| { + w.set_vbaten(true); }); Vbat {} @@ -320,7 +321,7 @@ impl<'d, T: Instance> Adc4<'d, T> { /// Set the ADC resolution. pub fn set_resolution(&mut self, resolution: Resolution) { - T::regs().cfgr1().modify(|reg| reg.set_res(resolution.into())); + T::regs().cfgr1().modify(|w| w.set_res(resolution.into())); } /// Set hardware averaging. @@ -337,25 +338,24 @@ impl<'d, T: Instance> Adc4<'d, T> { Averaging::Samples256 => (true, Adc4OversamplingRatio::OVERSAMPLE256X, 8), }; - T::regs().cfgr2().modify(|reg| { - reg.set_ovsr(samples); - reg.set_ovss(right_shift); - reg.set_ovse(enable) + T::regs().cfgr2().modify(|w| { + w.set_ovsr(samples); + w.set_ovss(right_shift); + w.set_ovse(enable) }) } /// Read an ADC channel. pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16{ channel.setup(); - T::regs().cfgr1().modify(|reg| { - reg.set_chselrmod(false); - }); + // Select channel T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); T::regs().chselrmod0().modify(|w| { w.set_chsel(channel.channel() as usize, true); }); + // Reset interrupts T::regs().isr().modify(|reg| { reg.set_eos(true); reg.set_eoc(true); @@ -373,8 +373,33 @@ impl<'d, T: Instance> Adc4<'d, T> { T::regs().dr().read().0 as u16 } - /// Channels can not be repeated and must be in ascending order! - /// TODO: broken + /// Read one or multiple ADC channels using DMA. + /// + /// `sequence` iterator and `readings` must have the same length. + /// The channels in `sequence` must be in ascending order. + /// + /// Example + /// ```rust,ignore + /// use embassy_stm32::adc::adc4; + /// use embassy_stm32::adc::AdcChannel; + /// + /// let mut adc4 = adc4::Adc4::new(p.ADC4); + /// let mut adc4_pin1 = p.PC1; + /// let mut adc4_pin2 = p.PC0; + /// let mut degraded41 = adc4_pin1.degrade_adc(); + /// let mut degraded42 = adc4_pin2.degrade_adc(); + /// let mut measurements = [0u16; 2]; + /// // not that the channels must be in ascending order + /// adc4.read( + /// &mut p.GPDMA1_CH1, + /// [ + /// &mut degraded42, + /// &mut degraded41, + /// ] + /// .into_iter(), + /// &mut measurements, + /// ).await.unwrap(); + /// ``` pub async fn read( &mut self, rx_dma: &mut impl RxDma4, @@ -402,7 +427,7 @@ impl<'d, T: Instance> Adc4<'d, T> { reg.set_chselrmod(false); }); - + // Verify and activate sequence let mut prev_channel: i16 = -1; T::regs().chselrmod0().write_value(Adc4Chselrmod0(0_u32)); for channel in sequence { @@ -433,11 +458,8 @@ impl<'d, T: Instance> Adc4<'d, T> { reg.set_adstart(true); }); - // Wait for conversion sequence to finish. transfer.await; - blocking_delay_us(10); - // Ensure conversions are finished. Self::cancel_conversions(); diff --git a/embassy-stm32/src/lib.rs b/embassy-stm32/src/lib.rs index fb10f2a5f..d04199d05 100644 --- a/embassy-stm32/src/lib.rs +++ b/embassy-stm32/src/lib.rs @@ -238,7 +238,7 @@ pub struct Config { #[cfg(any(stm32l4, stm32l5, stm32u5))] pub enable_independent_io_supply: bool, - /// On the U5 series all analog peripherals are powere by a separate supply. + /// On the U5 series all analog peripherals are powered by a separate supply. #[cfg(stm32u5)] pub enable_independent_analog_supply: bool, diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs index 4632f2cd1..05e3faeb1 100644 --- a/examples/stm32u5/src/bin/adc.rs +++ b/examples/stm32u5/src/bin/adc.rs @@ -14,25 +14,6 @@ use panic_probe as _; #[embassy_executor::main] async fn main(spawner: embassy_executor::Spawner) { let mut config = embassy_stm32::Config::default(); - { - use embassy_stm32::rcc::*; - config.rcc.hsi = true; - - config.rcc.pll1 = Some(Pll { - source: PllSource::HSI, // 16 MHz - prediv: PllPreDiv::DIV1, // 16 MHz - mul: PllMul::MUL10, // 160 MHz - divp: Some(PllDiv::DIV1), // don't care - divq: Some(PllDiv::DIV1), // don't care - divr: Some(PllDiv::DIV1), // 160 MHz - }); - - config.rcc.sys = Sysclk::PLL1_R; - config.rcc.voltage_range = VoltageScale::RANGE1; - config.rcc.hsi48 = Some(Hsi48Config { sync_from_usb: true }); // needed for USB - config.rcc.mux.iclksel = mux::Iclksel::HSI48; // USB uses ICLK - - } let mut p = embassy_stm32::init(config); From 41c8bf867bc185507e1b9eadbf5645e57004cd4f Mon Sep 17 00:00:00 2001 From: klownfish Date: Tue, 31 Dec 2024 01:04:18 +0100 Subject: [PATCH 12/12] fix formatting --- embassy-stm32/src/adc/mod.rs | 2 +- embassy-stm32/src/adc/u5_adc4.rs | 35 +++++++++++++------------------- embassy-stm32/src/adc/v4.rs | 10 +++------ examples/stm32u5/src/bin/adc.rs | 30 +++++++++++---------------- 4 files changed, 30 insertions(+), 47 deletions(-) diff --git a/embassy-stm32/src/adc/mod.rs b/embassy-stm32/src/adc/mod.rs index 3cf2ca72e..36898b8f9 100644 --- a/embassy-stm32/src/adc/mod.rs +++ b/embassy-stm32/src/adc/mod.rs @@ -259,4 +259,4 @@ pub const fn resolution_to_max_count(res: Resolution) -> u32 { #[allow(unreachable_patterns)] _ => core::unreachable!(), } -} \ No newline at end of file +} diff --git a/embassy-stm32/src/adc/u5_adc4.rs b/embassy-stm32/src/adc/u5_adc4.rs index 468d16640..0635dad9b 100644 --- a/embassy-stm32/src/adc/u5_adc4.rs +++ b/embassy-stm32/src/adc/u5_adc4.rs @@ -1,17 +1,12 @@ -pub use crate::pac::adc::vals::Adc4Res as Resolution; -pub use crate::pac::adc::vals::Adc4SampleTime as SampleTime; -pub use crate::pac::adc::vals::Adc4Presc as Presc; -pub use crate::pac::adc::regs::Adc4Chselrmod0; - #[allow(unused)] -use pac::adc::vals::{Adc4Exten, Adc4OversamplingRatio, Adc4Dmacfg}; +use pac::adc::vals::{Adc4Dmacfg, Adc4Exten, Adc4OversamplingRatio}; -use super::{ - blocking_delay_us, AdcChannel, SealedAdcChannel, AnyAdcChannel, RxDma4 -}; +use super::{blocking_delay_us, AdcChannel, AnyAdcChannel, RxDma4, SealedAdcChannel}; +use crate::dma::Transfer; +pub use crate::pac::adc::regs::Adc4Chselrmod0; +pub use crate::pac::adc::vals::{Adc4Presc as Presc, Adc4Res as Resolution, Adc4SampleTime as SampleTime}; use crate::time::Hertz; use crate::{pac, rcc, Peripheral}; -use crate::dma::Transfer; const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); @@ -74,7 +69,7 @@ impl SealedAdcChannel for Vcore { pub enum DacChannel { OUT1, - OUT2 + OUT2, } /// Number of samples used for averaging. @@ -186,7 +181,7 @@ pub struct Adc4<'d, T: Instance> { #[derive(Debug)] pub enum Adc4Error { InvalidSequence, - DMAError + DMAError, } impl<'d, T: Instance> Adc4<'d, T> { @@ -205,9 +200,7 @@ impl<'d, T: Instance> Adc4<'d, T> { panic!("Maximal allowed frequency for ADC4 is {} MHz and it varies with different packages, refer to ST docs for more information.", MAX_ADC_CLK_FREQ.0 / 1_000_000 ); } - let mut s = Self { - adc, - }; + let mut s = Self { adc }; s.power_up(); @@ -227,7 +220,7 @@ impl<'d, T: Instance> Adc4<'d, T> { T::regs().cr().modify(|w| { w.set_advregen(true); }); - while !T::regs().isr().read().ldordy() { }; + while !T::regs().isr().read().ldordy() {} T::regs().isr().modify(|w| { w.set_ldordy(true); @@ -300,8 +293,8 @@ impl<'d, T: Instance> Adc4<'d, T> { pub fn enable_dac_channel(&self, dac: DacChannel) -> Dac { let mux; match dac { - DacChannel::OUT1 => {mux = false}, - DacChannel::OUT2 => {mux = true} + DacChannel::OUT1 => mux = false, + DacChannel::OUT2 => mux = true, } T::regs().or().modify(|w| w.set_chn21sel(mux)); Dac {} @@ -346,7 +339,7 @@ impl<'d, T: Instance> Adc4<'d, T> { } /// Read an ADC channel. - pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16{ + pub fn blocking_read(&mut self, channel: &mut impl AdcChannel) -> u16 { channel.setup(); // Select channel @@ -440,7 +433,7 @@ impl<'d, T: Instance> Adc4<'d, T> { T::regs().chselrmod0().modify(|w| { w.set_chsel(channel.channel as usize, true); }); - }; + } let request = rx_dma.request(); let transfer = unsafe { @@ -483,4 +476,4 @@ impl<'d, T: Instance> Adc4<'d, T> { while T::regs().cr().read().adstart() {} } } -} \ No newline at end of file +} diff --git a/embassy-stm32/src/adc/v4.rs b/embassy-stm32/src/adc/v4.rs index 96dae25bd..46f9c7ac7 100644 --- a/embassy-stm32/src/adc/v4.rs +++ b/embassy-stm32/src/adc/v4.rs @@ -1,9 +1,7 @@ -#[allow(unused)] -use pac::adc::vals::{Adstp, Difsel, Exten, Pcsel, Dmngt}; - #[cfg(not(stm32u5))] -use pac::adc::vals::{Adcaldif, Boost}; - +use pac::adc::vals::{Adcaldif, Boost}; +#[allow(unused)] +use pac::adc::vals::{Adstp, Difsel, Dmngt, Exten, Pcsel}; use pac::adccommon::vals::Presc; use super::{ @@ -26,7 +24,6 @@ const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(50); #[cfg(stm32u5)] const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(55); - #[cfg(stm32g4)] const VREF_CHANNEL: u8 = 18; #[cfg(stm32g4)] @@ -41,7 +38,6 @@ const TEMP_CHANNEL: u8 = 18; #[cfg(not(stm32u5))] const VBAT_CHANNEL: u8 = 17; - #[cfg(stm32u5)] const VREF_CHANNEL: u8 = 0; #[cfg(stm32u5)] diff --git a/examples/stm32u5/src/bin/adc.rs b/examples/stm32u5/src/bin/adc.rs index 05e3faeb1..6ba21cc63 100644 --- a/examples/stm32u5/src/bin/adc.rs +++ b/examples/stm32u5/src/bin/adc.rs @@ -1,19 +1,14 @@ #![no_std] #![no_main] - -use defmt::{*}; -use defmt_rtt as _; - +use defmt::*; use embassy_stm32::adc; -use embassy_stm32::adc::AdcChannel; -use embassy_stm32::adc::adc4; -use panic_probe as _; - +use embassy_stm32::adc::{adc4, AdcChannel}; +use {defmt_rtt as _, panic_probe as _}; #[embassy_executor::main] -async fn main(spawner: embassy_executor::Spawner) { - let mut config = embassy_stm32::Config::default(); +async fn main(_spawner: embassy_executor::Spawner) { + let config = embassy_stm32::Config::default(); let mut p = embassy_stm32::init(config); @@ -84,7 +79,8 @@ async fn main(spawner: embassy_executor::Spawner) { ] .into_iter(), &mut measurements, - ).await; + ) + .await; let volt1: f32 = 3.3 * measurements[0] as f32 / max1 as f32; let volt2: f32 = 3.3 * measurements[1] as f32 / max1 as f32; @@ -101,15 +97,13 @@ async fn main(spawner: embassy_executor::Spawner) { // The channels must be in ascending order and can't repeat for ADC4 adc4.read( &mut p.GPDMA1_CH1, - [ - &mut degraded42, - &mut degraded41, - ] - .into_iter(), + [&mut degraded42, &mut degraded41].into_iter(), &mut measurements, - ).await.unwrap(); + ) + .await + .unwrap(); let volt2: f32 = 3.3 * measurements[0] as f32 / max4 as f32; let volt1: f32 = 3.3 * measurements[1] as f32 / max4 as f32; info!("Async read 4 pin 1 {}", volt1); info!("Async read 4 pin 2 {}", volt2); -} \ No newline at end of file +}