From 8184bb809b65281cfcf0035e40c7c215d6b9aeda Mon Sep 17 00:00:00 2001 From: Jakob Date: Tue, 4 Nov 2025 19:55:09 +0100 Subject: Implement into_ring_buffered for g4. Add methods for configuring injected sampling for g4. --- embassy-stm32/src/adc/g4.rs | 235 ++++++++++++++++++++- embassy-stm32/src/adc/ringbuffered.rs | 15 +- embassy-stm32/src/timer/complementary_pwm.rs | 12 +- embassy-stm32/src/timer/low_level.rs | 10 + examples/stm32g4/.cargo/config.toml | 2 +- examples/stm32g4/Cargo.toml | 13 +- examples/stm32g4/src/bin/adc_dma.rs | 4 +- .../stm32g4/src/bin/adc_injected_and_regular.rs | 144 +++++++++++++ 8 files changed, 411 insertions(+), 24 deletions(-) create mode 100644 examples/stm32g4/src/bin/adc_injected_and_regular.rs diff --git a/embassy-stm32/src/adc/g4.rs b/embassy-stm32/src/adc/g4.rs index 5098aadd8..d8aaaba55 100644 --- a/embassy-stm32/src/adc/g4.rs +++ b/embassy-stm32/src/adc/g4.rs @@ -3,9 +3,10 @@ use pac::adc::vals::{Adcaldif, Difsel, Exten}; #[allow(unused)] #[cfg(stm32g4)] -use pac::adc::vals::{Adcaldif, Difsel, Exten, Rovsm, Trovs}; -use pac::adccommon::vals::Presc; -use stm32_metapac::adc::vals::{Adstp, Dmacfg, Dmaen}; +pub use pac::adc::vals::{Adcaldif, Difsel, Exten, Rovsm, Trovs}; +pub use pac::adccommon::vals::Presc; +pub use stm32_metapac::adc::vals::{Adstp, Dmacfg, Dmaen}; +pub use stm32_metapac::adccommon::vals::Dual; use super::{Adc, AdcChannel, AnyAdcChannel, Instance, Resolution, RxDma, SampleTime, blocking_delay_us}; use crate::adc::SealedAdcChannel; @@ -13,11 +14,16 @@ use crate::dma::Transfer; use crate::time::Hertz; use crate::{Peri, pac, rcc}; +mod ringbuffered; +pub use ringbuffered::RingBufferedAdc; + /// 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 NR_INJECTED_RANKS: usize = 4; + /// Max single ADC operation clock frequency #[cfg(stm32g4)] const MAX_ADC_CLK_FREQ: Hertz = Hertz::mhz(60); @@ -357,7 +363,31 @@ impl<'d, T: Instance> Adc<'d, T> { self.read_channel(channel) } - /// Read one or multiple ADC channels using DMA. + pub(super) fn start() { + // Start adc conversion + T::regs().cr().modify(|reg| { + reg.set_adstart(true); + }); + } + + pub(super) fn stop() { + // Stop adc conversion + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_adstp(Adstp::STOP); + }); + while T::regs().cr().read().adstart() {} + } + } + + pub(super) fn teardown_adc() { + //disable dma control + T::regs().cfgr().modify(|reg| { + reg.set_dmaen(Dmaen::DISABLE); + }); + } + + /// Read one or multiple ADC regular channels using DMA. /// /// `sequence` iterator and `readings` must have the same length. /// @@ -382,6 +412,8 @@ impl<'d, T: Instance> Adc<'d, T> { /// .await; /// defmt::info!("measurements: {}", measurements); /// ``` + /// + /// Note: This is not very efficient as the ADC needs to be reconfigured for each read. pub async fn read( &mut self, rx_dma: Peri<'_, impl RxDma>, @@ -397,8 +429,6 @@ impl<'d, T: Instance> Adc<'d, T> { sequence.len() <= 16, "Asynchronous read sequence cannot be more than 16 in length" ); - - // Ensure no conversions are ongoing and ADC is enabled. Self::cancel_conversions(); self.enable(); @@ -406,11 +436,9 @@ impl<'d, T: Instance> Adc<'d, T> { T::regs().sqr1().modify(|w| { w.set_l(sequence.len() as u8 - 1); }); - // Configure channels and ranks for (_i, (channel, sample_time)) in sequence.enumerate() { Self::configure_channel(channel, sample_time); - match _i { 0..=3 => { T::regs().sqr1().modify(|w| { @@ -477,6 +505,189 @@ impl<'d, T: Instance> Adc<'d, T> { }); } + /// Set external trigger for regular conversion sequence + /// Possible trigger values are seen in Table 166 in RM0440 Rev 9 + pub fn set_regular_conversion_trigger(&mut self, trigger: u8, edge: Exten) { + T::regs().cfgr().modify(|r| { + r.set_extsel(trigger); + r.set_exten(edge); + }); + // Regular conversions uses DMA so no need to generate interrupt + T::regs().ier().modify(|r| r.set_eosie(false)); + } + + // Dual ADC mode selection + pub fn configure_dual_mode(&mut self, val: Dual) { + T::common_regs().ccr().modify(|reg| { + reg.set_dual(val); + }) + } + + /// Configure a sequence of injected channels + pub fn configure_injected_sequence<'a>( + &mut self, + sequence: impl ExactSizeIterator, SampleTime)>, + ) { + assert!(sequence.len() != 0, "Read sequence cannot be empty"); + assert!( + sequence.len() <= NR_INJECTED_RANKS, + "Read sequence cannot be more than 4 in length" + ); + + // Ensure no conversions are ongoing and ADC is enabled. + Self::cancel_conversions(); + self.enable(); + + // Set sequence length + T::regs().jsqr().modify(|w| { + w.set_jl(sequence.len() as u8 - 1); + }); + + // Configure channels and ranks + for (n, (channel, sample_time)) in sequence.enumerate() { + Self::configure_channel(channel, sample_time); + + match n { + 0..=3 => { + T::regs().jsqr().modify(|w| { + w.set_jsq(n, channel.channel()); + }); + } + 4..=8 => { + T::regs().jsqr().modify(|w| { + w.set_jsq(n - 4, channel.channel()); + }); + } + 9..=13 => { + T::regs().jsqr().modify(|w| { + w.set_jsq(n - 9, channel.channel()); + }); + } + 14..=15 => { + T::regs().jsqr().modify(|w| { + w.set_jsq(n - 14, channel.channel()); + }); + } + _ => unreachable!(), + } + } + + T::regs().cfgr().modify(|reg| { + reg.set_jdiscen(false); // Will convert all channels for each trigger + }); + } + + /// Configures the ADC to use a DMA ring buffer for continuous data acquisition. + /// + /// The `dma_buf` should be large enough to prevent DMA buffer overrun. + /// The length of the `dma_buf` should be a multiple of the ADC channel count. + /// For example, if 3 channels are measured, its length can be 3 * 40 = 120 measurements. + /// + /// `read` method is used to read out measurements from the DMA ring buffer, and its buffer should be exactly half of the `dma_buf` length. + /// It is critical to call `read` frequently to prevent DMA buffer overrun. + /// + /// [`read`]: #method.read + pub fn into_ring_buffered<'a>( + &mut self, + dma: Peri<'a, impl RxDma>, + dma_buf: &'a mut [u16], + sequence: impl ExactSizeIterator, SampleTime)>, + ) -> RingBufferedAdc<'a, T> { + assert!(!dma_buf.is_empty() && dma_buf.len() <= 0xFFFF); + assert!(sequence.len() != 0, "Asynchronous read sequence cannot be empty"); + assert!( + sequence.len() <= 16, + "Asynchronous read sequence cannot be more than 16 in length" + ); + // reset conversions and enable the adc + Self::cancel_conversions(); + self.enable(); + + //adc side setup + + // Set sequence length + T::regs().sqr1().modify(|w| { + w.set_l(sequence.len() as u8 - 1); + }); + + // Configure channels and ranks + for (_i, (channel, sample_time)) in sequence.enumerate() { + Self::configure_channel(channel, sample_time); + + match _i { + 0..=3 => { + T::regs().sqr1().modify(|w| { + w.set_sq(_i, channel.channel()); + }); + } + 4..=8 => { + T::regs().sqr2().modify(|w| { + w.set_sq(_i - 4, channel.channel()); + }); + } + 9..=13 => { + T::regs().sqr3().modify(|w| { + w.set_sq(_i - 9, channel.channel()); + }); + } + 14..=15 => { + T::regs().sqr4().modify(|w| { + w.set_sq(_i - 14, channel.channel()); + }); + } + _ => unreachable!(), + } + } + + // Clear overrun flag before starting transfer. + T::regs().isr().modify(|reg| { + reg.set_ovr(true); + }); + + T::regs().cfgr().modify(|reg| { + reg.set_discen(false); // Convert all channels for each trigger + reg.set_cont(false); // New trigger is neede for each sample to be read + reg.set_dmacfg(Dmacfg::CIRCULAR); + reg.set_dmaen(Dmaen::ENABLE); + }); + + RingBufferedAdc::new(dma, dma_buf) + } + + /// Start injected ADC conversion + pub fn start_injected_conversion(&mut self) { + T::regs().cr().modify(|reg| { + reg.set_jadstart(true); + }); + } + + /// Set external trigger for injected conversion sequence + /// Possible trigger values are seen in Table 167 in RM0440 Rev 9 + pub fn set_injected_conversion_trigger(&mut self, trigger: u8, edge: Exten) { + T::regs().jsqr().modify(|r| { + r.set_jextsel(trigger); + r.set_jexten(edge); + }); + } + + /// Enable end of injected sequence interrupt + pub fn enable_injected_eos_interrupt(&mut self, enable: bool) { + T::regs().ier().modify(|r| r.set_jeosie(enable)); + } + + /// Read sampled data from all injected ADC injected ranks + /// Clear the JEOS flag to allow a new injected sequence + pub fn clear_injected_eos(&mut self) -> [u16; NR_INJECTED_RANKS] { + let mut data = [0u16; NR_INJECTED_RANKS]; + for i in 0..NR_INJECTED_RANKS { + data[i] = T::regs().jdr(i).read().jdata(); + } + + // Clear JEOS by writing 1 + T::regs().isr().modify(|r| r.set_jeos(true)); + data + } + fn configure_channel(channel: &mut impl AdcChannel, sample_time: SampleTime) { // Configure channel Self::set_channel_sample_time(channel.channel(), sample_time); @@ -510,12 +721,20 @@ impl<'d, T: Instance> Adc<'d, T> { } fn cancel_conversions() { + // Cancel regular conversions if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { T::regs().cr().modify(|reg| { reg.set_adstp(Adstp::STOP); }); while T::regs().cr().read().adstart() {} } + // Cancel injected conversions + if T::regs().cr().read().adstart() && !T::regs().cr().read().addis() { + T::regs().cr().modify(|reg| { + reg.set_jadstp(Adstp::STOP); + }); + while T::regs().cr().read().jadstart() {} + } } } diff --git a/embassy-stm32/src/adc/ringbuffered.rs b/embassy-stm32/src/adc/ringbuffered.rs index 1f384efb5..971c8195c 100644 --- a/embassy-stm32/src/adc/ringbuffered.rs +++ b/embassy-stm32/src/adc/ringbuffered.rs @@ -63,14 +63,17 @@ impl<'d, T: Instance> RingBufferedAdc<'d, T> { /// Reads measurements from the DMA ring buffer. /// /// This method fills the provided `measurements` array with ADC readings from the DMA buffer. - /// The length of the `measurements` array should be exactly half of the DMA buffer length. Because interrupts are only generated if half or full DMA transfer completes. + /// The length of the `measurements` array should be exactly half of the DMA buffer length. + /// Because interrupts are only generated if half or full DMA transfer completes. /// - /// Each call to `read` will populate the `measurements` array in the same order as the channels defined with `sequence`. - /// There will be many sequences worth of measurements in this array because it only returns if at least half of the DMA buffer is filled. - /// For example if 2 channels are sampled `measurements` contain: `[sq0 sq1 sq0 sq1 sq0 sq1 ..]`. + /// Each call to `read` will populate the `measurements` array in the same order as the channels + /// defined with `sequence`. There will be many sequences worth of measurements in this array + /// because it only returns if at least half of the DMA buffer is filled. For example if 2 + /// channels are sampled `measurements` contain: `[sq0 sq1 sq0 sq1 sq0 sq1 ..]`. /// - /// Note that the ADC Datarate can be very fast, it is suggested to use DMA mode inside tightly running tasks - /// Otherwise, you'll see constant Overrun errors occuring, this means that you're sampling too quickly for the task to handle, and you may need to increase the buffer size. + /// Note that the ADC Datarate can be very fast, it is suggested to use DMA mode inside tightly + /// running tasks. Otherwise, you'll see constant Overrun errors occurring, this means that + /// you're sampling too quickly for the task to handle, and you may need to increase the buffer size. /// Example: /// ```rust,ignore /// const DMA_BUF_LEN: usize = 120; diff --git a/embassy-stm32/src/timer/complementary_pwm.rs b/embassy-stm32/src/timer/complementary_pwm.rs index 75a83629c..9a56a41fb 100644 --- a/embassy-stm32/src/timer/complementary_pwm.rs +++ b/embassy-stm32/src/timer/complementary_pwm.rs @@ -2,7 +2,7 @@ use core::marker::PhantomData; -pub use stm32_metapac::timer::vals::{Ckd, Ossi, Ossr}; +pub use stm32_metapac::timer::vals::{Ckd, Mms2, Ossi, Ossr}; use super::low_level::{CountingMode, OutputPolarity, Timer}; use super::simple_pwm::PwmPin; @@ -136,6 +136,16 @@ impl<'d, T: AdvancedInstance4Channel> ComplementaryPwm<'d, T> { self.inner.get_moe() } + /// Set Master Slave Mode 2 + pub fn set_mms2(&mut self, mms2: Mms2) { + self.inner.set_mms2_selection(mms2); + } + + /// Set Repetition Counter + pub fn set_repetition_counter(&mut self, val: u16) { + self.inner.set_repetition_counter(val); + } + /// Enable the given channel. pub fn enable(&mut self, channel: Channel) { self.inner.enable_channel(channel, true); diff --git a/embassy-stm32/src/timer/low_level.rs b/embassy-stm32/src/timer/low_level.rs index 82645887e..0122fe4f7 100644 --- a/embassy-stm32/src/timer/low_level.rs +++ b/embassy-stm32/src/timer/low_level.rs @@ -814,6 +814,16 @@ impl<'d, T: AdvancedInstance4Channel> Timer<'d, T> { self.regs_advanced().cr2().modify(|w| w.set_oisn(channel.index(), val)); } + /// Set master mode selection 2 + pub fn set_mms2_selection(&self, mms2: vals::Mms2) { + self.regs_advanced().cr2().modify(|w| w.set_mms2(mms2)); + } + + /// Set repetition counter + pub fn set_repetition_counter(&self, val: u16) { + self.regs_advanced().rcr().modify(|w| w.set_rep(val)); + } + /// Trigger software break 1 or 2 /// Setting this bit generates a break event. This bit is automatically cleared by the hardware. pub fn trigger_software_break(&self, n: usize) { diff --git a/examples/stm32g4/.cargo/config.toml b/examples/stm32g4/.cargo/config.toml index d28ad069e..de3e5718e 100644 --- a/examples/stm32g4/.cargo/config.toml +++ b/examples/stm32g4/.cargo/config.toml @@ -6,4 +6,4 @@ runner = "probe-rs run --chip STM32G484VETx" target = "thumbv7em-none-eabi" [env] -DEFMT_LOG = "trace" +DEFMT_LOG = "trace" \ No newline at end of file diff --git a/examples/stm32g4/Cargo.toml b/examples/stm32g4/Cargo.toml index 6fd282d6d..8bbeb594c 100644 --- a/examples/stm32g4/Cargo.toml +++ b/examples/stm32g4/Cargo.toml @@ -7,12 +7,12 @@ publish = false [dependencies] # Change stm32g491re to your chip name, if necessary. -embassy-stm32 = { version = "0.4.0", path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32g491re", "memory-x", "unstable-pac", "exti"] } -embassy-sync = { version = "0.7.2", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.9.0", path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt"] } -embassy-time = { version = "0.5.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } -embassy-usb = { version = "0.5.1", path = "../../embassy-usb", features = ["defmt"] } -embassy-futures = { version = "0.1.2", path = "../../embassy-futures" } +embassy-stm32 = { path = "../../embassy-stm32", features = [ "defmt", "time-driver-any", "stm32g491re", "memory-x", "unstable-pac", "exti"] } +embassy-sync = { path = "../../embassy-sync", features = ["defmt"] } +embassy-executor = { path = "../../embassy-executor", features = ["arch-cortex-m", "executor-thread", "defmt"] } +embassy-time = { path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] } +embassy-usb = { path = "../../embassy-usb", features = ["defmt"] } +embassy-futures = { path = "../../embassy-futures" } usbd-hid = "0.8.1" defmt = "1.0.1" @@ -25,6 +25,7 @@ embedded-can = { version = "0.4" } panic-probe = { version = "1.0.0", features = ["print-defmt"] } heapless = { version = "0.8", default-features = false } static_cell = "2.0.0" +critical-section = "1.1" [profile.release] debug = 2 diff --git a/examples/stm32g4/src/bin/adc_dma.rs b/examples/stm32g4/src/bin/adc_dma.rs index a82067049..ef8b0c3c2 100644 --- a/examples/stm32g4/src/bin/adc_dma.rs +++ b/examples/stm32g4/src/bin/adc_dma.rs @@ -12,7 +12,7 @@ static mut DMA_BUF: [u16; 2] = [0; 2]; #[embassy_executor::main] async fn main(_spawner: Spawner) { - let mut read_buffer = unsafe { &mut DMA_BUF[..] }; + let read_buffer = unsafe { &mut DMA_BUF[..] }; let mut config = Config::default(); { @@ -47,7 +47,7 @@ async fn main(_spawner: Spawner) { (&mut pa0, SampleTime::CYCLES247_5), ] .into_iter(), - &mut read_buffer, + read_buffer, ) .await; diff --git a/examples/stm32g4/src/bin/adc_injected_and_regular.rs b/examples/stm32g4/src/bin/adc_injected_and_regular.rs new file mode 100644 index 000000000..5db1a4fa0 --- /dev/null +++ b/examples/stm32g4/src/bin/adc_injected_and_regular.rs @@ -0,0 +1,144 @@ +//! adc injected and regular conversions +//! +//! This example both regular and injected ADC conversions at the same time +//! p:pa0 n:pa2 + +#![no_std] +#![no_main] + +use core::cell::RefCell; + +use defmt::info; +use embassy_stm32::adc::{Adc, AdcChannel as _, Exten, RxDma, SampleTime}; +use embassy_stm32::interrupt::typelevel::{ADC1_2, Interrupt}; +use embassy_stm32::peripherals::ADC1; +use embassy_stm32::time::Hertz; +use embassy_stm32::timer::complementary_pwm::{ComplementaryPwm, Mms2}; +use embassy_stm32::timer::low_level::CountingMode; +use embassy_stm32::{Config, interrupt}; +use embassy_sync::blocking_mutex::CriticalSectionMutex; +use {critical_section, defmt_rtt as _, panic_probe as _}; + +static ADC1_HANDLE: CriticalSectionMutex>>> = + CriticalSectionMutex::new(RefCell::new(None)); + +/// This example showcases how to use both regular ADC conversions with DMA and injected ADC +/// conversions with ADC interrupt simultaneously. Both conversion types can be configured with +/// different triggers and thanks to DMA it is possible to use the measurements in different task +/// without needing to access the ADC peripheral. +/// +/// If you don't need both regular and injected conversions the example code can easily be reworked +/// to only include one of the ADC conversion types. +#[embassy_executor::main] +async fn main(_spawner: embassy_executor::Spawner) { + // See Table 166 and 167 in RM0440 Rev 9 for ADC1/2 External triggers + // Note: Regular and Injected channels use different tables!! + const ADC1_INJECTED_TRIGGER_TIM1_TRGO2: u8 = 8; + const ADC1_REGULAR_TRIGGER_TIM1_TRGO2: u8 = 10; + + // --- RCC config --- + let mut config = Config::default(); + { + use embassy_stm32::rcc::*; + config.rcc.pll = Some(Pll { + source: PllSource::HSI, + prediv: PllPreDiv::DIV4, + mul: PllMul::MUL85, + divp: None, + divq: None, + divr: Some(PllRDiv::DIV2), + }); + config.rcc.mux.adc12sel = mux::Adcsel::SYS; + config.rcc.sys = Sysclk::PLL1_R; + } + let p = embassy_stm32::init(config); + + // In this example we use tim1_trgo2 event to trigger the ADC conversions + let tim1 = p.TIM1; + let pwm_freq = 1; + let mut pwm = ComplementaryPwm::new( + tim1, + None, + None, + None, + None, + None, + None, + None, + None, + Hertz::hz(pwm_freq), + CountingMode::EdgeAlignedUp, + ); + pwm.set_master_output_enable(false); + // Mms2 is used to configure which timer event that is connected to tim1_trgo2. + // In this case we use the update event of the timer. + pwm.set_mms2(Mms2::UPDATE); + + // Configure regular conversions with DMA + let mut adc1 = Adc::new(p.ADC1); + + let mut vrefint_channel = adc1.enable_vrefint().degrade_adc(); + let mut pa0 = p.PC1.degrade_adc(); + let regular_sequence = [ + (&mut vrefint_channel, SampleTime::CYCLES247_5), + (&mut pa0, SampleTime::CYCLES247_5), + ] + .into_iter(); + + // Configure DMA for retrieving regular ADC measurements + let dma1_ch1 = p.DMA1_CH1; + // Using buffer of double size means the half-full interrupts will generate at the expected rate + let mut readings = [0u16; 4]; + let mut ring_buffered_adc = adc1.into_ring_buffered(dma1_ch1, &mut readings, regular_sequence); + + // Configurations of Injected ADC measurements + let mut pa2 = p.PA2.degrade_adc(); + let injected_seq = [(&mut pa2, SampleTime::CYCLES247_5)].into_iter(); + adc1.configure_injected_sequence(injected_seq); + + adc1.set_regular_conversion_trigger(ADC1_REGULAR_TRIGGER_TIM1_TRGO2, Exten::RISING_EDGE); + adc1.set_injected_conversion_trigger(ADC1_INJECTED_TRIGGER_TIM1_TRGO2, Exten::RISING_EDGE); + + // ADC must be started after all configurations are completed + adc1.start_injected_conversion(); + + // Enable interrupt at end of injected ADC conversion + adc1.enable_injected_eos_interrupt(true); + + // Store ADC globally to allow access from ADC interrupt + critical_section::with(|cs| { + ADC1_HANDLE.borrow(cs).replace(Some(adc1)); + }); + // Enable interrupt for ADC1_2 + unsafe { ADC1_2::enable() }; + + // Main loop for reading regular ADC measurements periodically + let mut data = [0u16; 2]; + loop { + { + match ring_buffered_adc.read(&mut data).await { + Ok(n) => { + defmt::info!("Regular ADC reading, VrefInt: {}, PA0: {}", data[0], data[1]); + defmt::info!("Remaining samples: {}", n,); + } + Err(e) => { + defmt::error!("DMA error: {:?}", e); + ring_buffered_adc.clear(); + } + } + } + } +} + +/// Use ADC1_2 interrupt to retrieve injected ADC measurements +/// Interrupt must be unsafe as hardware can invoke it any-time. Critical sections ensure safety +/// within the interrupt. +#[interrupt] +unsafe fn ADC1_2() { + critical_section::with(|cs| { + if let Some(adc) = ADC1_HANDLE.borrow(cs).borrow_mut().as_mut() { + let injected_data = adc.clear_injected_eos(); + info!("Injected reading of PA2: {}", injected_data[0]); + } + }); +} -- cgit