From 20e9b6543c18611e91da2b15566ca720cd75c8f2 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 3 Nov 2020 09:36:03 +0100 Subject: [PATCH 01/20] Adding WIP updates to using DMA --- Cargo.lock | 11 +- Cargo.toml | 4 +- openocd.gdb | 3 + src/main.rs | 292 +++++++++++++++++++++++----------------------------- 4 files changed, 143 insertions(+), 167 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 998e749ae..915290b36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -185,6 +185,15 @@ dependencies = [ "cortex-m", ] +[[package]] +name = "embedded-dma" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c8c02e4347a0267ca60813c952017f4c5948c232474c6010a381a337f1bda4" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "embedded-hal" version = "0.2.4" @@ -558,12 +567,12 @@ dependencies = [ [[package]] name = "stm32h7xx-hal" version = "0.8.0" -source = "git+https://github.com/quartiq/stm32h7xx-hal?branch=rs/issue-158/managed-spi#cc36bbbaa1bf21e53732cfc0f3dd7175c3ed6d44" dependencies = [ "bare-metal 1.0.0", "cast", "cortex-m", "cortex-m-rt", + "embedded-dma", "embedded-hal", "nb 1.0.0", "paste 1.0.2", diff --git a/Cargo.toml b/Cargo.toml index 0f2df5c85..0cac547f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,7 +60,7 @@ features = ["stm32h743v"] [dependencies.stm32h7xx-hal] features = ["stm32h743v", "rt", "unproven", "ethernet", "quadspi"] git = "https://github.com/quartiq/stm32h7xx-hal" -branch = "rs/issue-158/managed-spi" +branch = "feature/stabilizer-dma" [features] semihosting = ["panic-semihosting", "cortex-m-log/semihosting"] @@ -70,7 +70,7 @@ nightly = ["cortex-m/inline-asm"] [profile.dev] codegen-units = 1 incremental = false -opt-level = 3 +opt-level = 1 [profile.release] opt-level = 3 diff --git a/openocd.gdb b/openocd.gdb index e903a33fd..c1ae67adb 100644 --- a/openocd.gdb +++ b/openocd.gdb @@ -26,3 +26,6 @@ set var $t0=*$cc continue end #set var $t0=*$cc + +source ../../PyCortexMDebug/cmdebug/svd_gdb.py +svd_load ~/Downloads/STM32H743x.svd diff --git a/src/main.rs b/src/main.rs index 58d879ec7..91058ba13 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,9 +35,16 @@ use stm32h7xx_hal::prelude::*; use embedded_hal::digital::v2::{InputPin, OutputPin}; use hal::{ - dma::{DmaChannel, DmaExt, DmaInternal}, + dma::{ + Transfer, + PeripheralToMemory, MemoryToPeripheral, + traits::{Stream, TargetAddress}, + dma::{ + DmaConfig, + DMAReq, + }, + }, ethernet::{self, PHY}, - rcc::rec::ResetEnable, }; use smoltcp as net; @@ -46,12 +53,17 @@ use heapless::{consts::*, String}; #[link_section = ".sram3.eth"] static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); +mod dac; +mod adc; mod afe; mod eeprom; mod iir; mod pounder; mod server; +use dac::{Dac0Output, Dac1Output}; +use adc::{Adc0Input, Adc1Input}; + #[cfg(not(feature = "semihosting"))] fn init_log() {} @@ -92,8 +104,6 @@ static mut NET_STORE: NetStorage = NetStorage { const SCALE: f32 = ((1 << 15) - 1) as f32; -const SPI_START: u32 = 0x00; - // static ETHERNET_PENDING: AtomicBool = AtomicBool::new(true); const TCP_RX_BUFFER_SIZE: usize = 8192; @@ -163,12 +173,12 @@ macro_rules! route_request { #[rtic::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)] const APP: () = { struct Resources { - adc0: hal::spi::Spi, - dac0: hal::spi::Spi, + adc0: Adc0Input, + dac0: Dac0Output, afe0: AFE0, - adc1: hal::spi::Spi, - dac1: hal::spi::Spi, + adc1: Adc1Input, + dac1: Dac1Output, afe1: AFE1, eeprom_i2c: hal::i2c::I2c, @@ -247,11 +257,10 @@ const APP: () = { afe::ProgrammableGainAmplifier::new(a0_pin, a1_pin) }; - ccdr.peripheral.DMA1.reset().enable(); - let mut dma_channels = dp.DMA1.split(); + let dma_streams = hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); // Configure the SPI interfaces to the ADCs and DACs. - let adc0_spi = { + let adc0 = { let spi_miso = gpiob .pb14 .into_alternate_af5() @@ -273,33 +282,7 @@ const APP: () = { .suspend_when_inactive() .cs_delay(220e-9); - dma_channels.0.set_peripheral_address( - &dp.SPI2.txdr as *const _ as u32, - false, - ); - dma_channels - .0 - .set_memory_address(&SPI_START as *const _ as u32, false); - dma_channels - .0 - .set_direction(hal::dma::Direction::MemoryToPeripherial); - dma_channels.0.set_transfer_length(1); - dma_channels.0.cr().modify(|_, w| { - w.circ() - .enabled() - .psize() - .bits16() - .msize() - .bits16() - .pfctrl() - .dma() - }); - dma_channels.0.dmamux().modify(|_, w| { - w.dmareq_id() - .variant(hal::stm32::dmamux1::ccr::DMAREQ_ID_A::TIM2_UP) - }); - - let mut spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi( + let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, 50.mhz(), @@ -307,16 +290,10 @@ const APP: () = { &ccdr.clocks, ); - // Kick-start the SPI transaction - we will add data to the TXFIFO to read from the ADC. - let spi_regs = unsafe { &*hal::stm32::SPI2::ptr() }; - spi_regs.cr1.modify(|_, w| w.cstart().started()); - - spi.listen(hal::spi::Event::Rxp); - - spi + Adc0Input::new(spi, dma_streams.0, dma_streams.1) }; - let adc1_spi = { + let adc1 = { let spi_miso = gpiob .pb4 .into_alternate_af6() @@ -338,33 +315,7 @@ const APP: () = { .suspend_when_inactive() .cs_delay(220e-9); - dma_channels.1.set_peripheral_address( - &dp.SPI3.txdr as *const _ as u32, - false, - ); - dma_channels - .1 - .set_memory_address(&SPI_START as *const _ as u32, false); - dma_channels - .1 - .set_direction(hal::dma::Direction::MemoryToPeripherial); - dma_channels.1.dmamux().modify(|_, w| { - w.dmareq_id() - .variant(hal::stm32::dmamux1::ccr::DMAREQ_ID_A::TIM2_UP) - }); - dma_channels.1.set_transfer_length(1); - dma_channels.1.cr().modify(|_, w| { - w.circ() - .enabled() - .psize() - .bits16() - .msize() - .bits16() - .pfctrl() - .dma() - }); - - let mut spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi( + let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, 50.mhz(), @@ -372,12 +323,7 @@ const APP: () = { &ccdr.clocks, ); - let spi_regs = unsafe { &*hal::stm32::SPI3::ptr() }; - spi_regs.cr1.modify(|_, w| w.cstart().started()); - - spi.listen(hal::spi::Event::Rxp); - - spi + Adc1Input::new(spi, dma_streams.2, dma_streams.3) }; let _dac_clr_n = gpioe.pe12.into_push_pull_output().set_high().unwrap(); @@ -386,68 +332,76 @@ const APP: () = { let _dac1_ldac_n = gpioe.pe15.into_push_pull_output().set_low().unwrap(); - let dac0_spi = { - let spi_miso = gpioe - .pe5 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let spi_sck = gpioe - .pe2 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let _spi_nss = gpioe - .pe4 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); + let dac0 = { + let dac0_spi = { + let spi_miso = gpioe + .pe5 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let spi_sck = gpioe + .pe2 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let _spi_nss = gpioe + .pe4 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); - let config = hal::spi::Config::new(hal::spi::Mode { - polarity: hal::spi::Polarity::IdleHigh, - phase: hal::spi::Phase::CaptureOnSecondTransition, - }) - .manage_cs() - .suspend_when_inactive() - .communication_mode(hal::spi::CommunicationMode::Transmitter) - .swap_mosi_miso(); + let config = hal::spi::Config::new(hal::spi::Mode { + polarity: hal::spi::Polarity::IdleHigh, + phase: hal::spi::Phase::CaptureOnSecondTransition, + }) + .manage_cs() + .suspend_when_inactive() + .communication_mode(hal::spi::CommunicationMode::Transmitter) + .swap_mosi_miso(); + + dp.SPI4.spi( + (spi_sck, spi_miso, hal::spi::NoMosi), + config, + 50.mhz(), + ccdr.peripheral.SPI4, + &ccdr.clocks, + ) + }; - dp.SPI4.spi( - (spi_sck, spi_miso, hal::spi::NoMosi), - config, - 50.mhz(), - ccdr.peripheral.SPI4, - &ccdr.clocks, - ) + Dac0Output::new(dac0_spi) }; - let dac1_spi = { - let spi_miso = gpiof - .pf8 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let spi_sck = gpiof - .pf7 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let _spi_nss = gpiof - .pf6 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); + let dac1 = { + let dac1_spi = { + let spi_miso = gpiof + .pf8 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let spi_sck = gpiof + .pf7 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let _spi_nss = gpiof + .pf6 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); - let config = hal::spi::Config::new(hal::spi::Mode { - polarity: hal::spi::Polarity::IdleHigh, - phase: hal::spi::Phase::CaptureOnSecondTransition, - }) - .manage_cs() - .suspend_when_inactive() - .communication_mode(hal::spi::CommunicationMode::Transmitter) - .swap_mosi_miso(); + let config = hal::spi::Config::new(hal::spi::Mode { + polarity: hal::spi::Polarity::IdleHigh, + phase: hal::spi::Phase::CaptureOnSecondTransition, + }) + .manage_cs() + .communication_mode(hal::spi::CommunicationMode::Transmitter) + .suspend_when_inactive() + .swap_mosi_miso(); + + dp.SPI5.spi( + (spi_sck, spi_miso, hal::spi::NoMosi), + config, + 50.mhz(), + ccdr.peripheral.SPI5, + &ccdr.clocks, + ) + }; - dp.SPI5.spi( - (spi_sck, spi_miso, hal::spi::NoMosi), - config, - 50.mhz(), - ccdr.peripheral.SPI5, - &ccdr.clocks, - ) + Dac1Output::new(dac1_spi) }; let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); @@ -728,24 +682,20 @@ const APP: () = { // Configure timer 2 to trigger conversions for the ADC let timer2 = - dp.TIM2.timer(500.khz(), ccdr.peripheral.TIM2, &ccdr.clocks); + dp.TIM2.timer(50.khz(), ccdr.peripheral.TIM2, &ccdr.clocks); { let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; t2_regs.dier.modify(|_, w| w.ude().set_bit()); } - // Start the SPI transfers. - dma_channels.0.start(); - dma_channels.1.start(); - init::LateResources { afe0: afe0, - adc0: adc0_spi, - dac0: dac0_spi, + adc0: adc0, + dac0: dac0, afe1: afe1, - adc1: adc1_spi, - dac1: dac1_spi, + adc1: adc1, + dac1: dac1, timer: timer2, pounder: pounder_devices, @@ -757,30 +707,34 @@ const APP: () = { } } - #[task(binds = SPI3, resources = [adc1, dac1, iir_state, iir_ch], priority = 2)] - fn spi3(c: spi3::Context) { - let output: u16 = { - let a: u16 = c.resources.adc1.read().unwrap(); - let x0 = f32::from(a as i16); - let y0 = - c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); - y0 as i16 as u16 ^ 0x8000 - }; + #[task(binds=DMA1_STR3, resources=[adc1, dac1, iir_state, iir_ch], priority=2)] + fn adc1(c: adc1::Context) { + let samples = c.resources.adc1.transfer_complete_handler(); - c.resources.dac1.send(output).unwrap(); + let mut last_result: u16 = 0; + for sample in samples { + let x0 = f32::from(*sample as i16); + let y0 = c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); + last_result = y0 as i16 as u16 ^ 0x8000; + //c.resources.dac0.push(last_result); + } + + c.resources.dac1.write(last_result); } - #[task(binds = SPI2, resources = [adc0, dac0, iir_state, iir_ch], priority = 2)] - fn spi2(c: spi2::Context) { - let output: u16 = { - let a: u16 = c.resources.adc0.read().unwrap(); - let x0 = f32::from(a as i16); - let y0 = - c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); - y0 as i16 as u16 ^ 0x8000 - }; + #[task(binds=DMA1_STR1, resources=[adc0, dac0, iir_state, iir_ch], priority=2)] + fn adc0(c: adc0::Context) { + let samples = c.resources.adc0.transfer_complete_handler(); + + let mut last_result: u16 = 0; + for sample in samples { + let x0 = f32::from(*sample as i16); + let y0 = c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); + last_result = y0 as i16 as u16 ^ 0x8000; + //c.resources.dac0.push(last_result); + } - c.resources.dac0.send(output).unwrap(); + c.resources.dac0.write(last_result); } #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])] @@ -973,6 +927,16 @@ const APP: () = { unsafe { ethernet::interrupt_handler() } } + #[task(binds = SPI2, priority = 1)] + fn spi2(_: spi2::Context) { + panic!("ADC0 input overrun"); + } + + #[task(binds = SPI3, priority = 1)] + fn spi3(_: spi3::Context) { + panic!("ADC0 input overrun"); + } + extern "C" { // hw interrupt handlers for RTIC to use for scheduling tasks // one per priority From adaca88a50e11cd98899d0269f18e9ca8867eb57 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 3 Nov 2020 09:41:14 +0100 Subject: [PATCH 02/20] Adding ADC/DAC modules --- src/adc.rs | 187 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/dac.rs | 64 ++++++++++++++++++ 2 files changed, 251 insertions(+) create mode 100644 src/adc.rs create mode 100644 src/dac.rs diff --git a/src/adc.rs b/src/adc.rs new file mode 100644 index 000000000..15d2f63e2 --- /dev/null +++ b/src/adc.rs @@ -0,0 +1,187 @@ +use super::{hal, DmaConfig, PeripheralToMemory, MemoryToPeripheral, TargetAddress, Transfer, DMAReq, +Stream}; + +const INPUT_BUFFER_SIZE: usize = 1; + +#[link_section = ".axisram.buffers"] +static mut SPI_START: [u16; 1] = [0x00]; + +#[link_section = ".axisram.buffers"] +static mut ADC0_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut ADC0_BUF1: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut ADC1_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut ADC1_BUF1: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; + +struct SPI2 {} + +impl SPI2 { + pub fn new() -> Self { + Self {} + } +} + +unsafe impl TargetAddress for SPI2 { + type MemSize = u16; + + const REQUEST_LINE: Option = Some(DMAReq::TIM2_UP as u8); + + fn address(&self) -> u32 { + let regs = unsafe { &*hal::stm32::SPI2::ptr() }; + ®s.txdr as *const _ as u32 + } +} + +struct SPI3 {} + +impl SPI3 { + pub fn new() -> Self { + Self {} + } +} + +unsafe impl TargetAddress for SPI3 { + type MemSize = u16; + + const REQUEST_LINE: Option = Some(DMAReq::TIM2_UP as u8); + + fn address(&self) -> u32 { + let regs = unsafe { &*hal::stm32::SPI3::ptr() }; + ®s.txdr as *const _ as u32 + } +} + +pub struct Adc0Input { + next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, + transfer: Transfer< + hal::dma::dma::Stream1, + hal::spi::Spi, + PeripheralToMemory, + &'static mut [u16; INPUT_BUFFER_SIZE]>, +} + +impl Adc0Input { + pub fn new( + spi: hal::spi::Spi, + trigger_stream: hal::dma::dma::Stream0, + data_stream: hal::dma::dma::Stream1, + ) -> Self { + let trigger_config = DmaConfig::default() + .memory_increment(false) + .peripheral_increment(false) + .circular_buffer(true); + + let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _ > = Transfer::init( + trigger_stream, + &SPI2::new(), + unsafe { &mut SPI_START }, + None, + trigger_config); + + let data_config = DmaConfig::default() + .memory_increment(true) + .transfer_complete_interrupt(true) + .peripheral_increment(false); + + let mut spi = spi.disable(); + spi.listen(hal::spi::Event::Error); + + let mut data_transfer: Transfer<_, _, PeripheralToMemory, _ > = Transfer::init( + data_stream, + &spi, + unsafe { &mut ADC0_BUF0 }, + None, + data_config); + + spi.enable_dma_rx(); + spi.enable_dma_tx(); + + let spi = spi.enable(); + spi.inner().cr1.modify(|_, w| w.cstart().started()); + + data_transfer.start(); + trigger_transfer.start(); + + Self { + next_buffer: unsafe { Some(&mut ADC0_BUF1) }, + transfer: data_transfer, + } + } + + pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { + let next_buffer = self.next_buffer.take().unwrap(); + let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + self.next_buffer.replace(prev_buffer); + self.next_buffer.as_ref().unwrap() + } +} + +pub struct Adc1Input { + next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, + transfer: Transfer< + hal::dma::dma::Stream3, + hal::spi::Spi, + PeripheralToMemory, + &'static mut [u16; INPUT_BUFFER_SIZE]>, +} + +impl Adc1Input { + pub fn new( + spi: hal::spi::Spi, + trigger_stream: hal::dma::dma::Stream2, + data_stream: hal::dma::dma::Stream3, + ) -> Self { + let trigger_config = DmaConfig::default() + .memory_increment(false) + .peripheral_increment(false) + .circular_buffer(true); + + let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _ > = Transfer::init( + trigger_stream, + &SPI3::new(), + unsafe { &mut SPI_START }, + None, + trigger_config); + + let data_config = DmaConfig::default() + .memory_increment(true) + .transfer_complete_interrupt(true) + .peripheral_increment(false); + + let mut spi = spi.disable(); + spi.listen(hal::spi::Event::Error); + + let mut data_transfer: Transfer<_, _, PeripheralToMemory, _ > = Transfer::init( + data_stream, + &spi, + unsafe { &mut ADC1_BUF0 }, + None, + data_config); + + spi.enable_dma_rx(); + spi.enable_dma_tx(); + + let spi = spi.enable(); + spi.inner().cr1.modify(|_, w| w.cstart().started()); + + data_transfer.start(); + trigger_transfer.start(); + + Self { + next_buffer: unsafe { Some(&mut ADC1_BUF1) }, + transfer: data_transfer, + } + } + + pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { + let next_buffer = self.next_buffer.take().unwrap(); + let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + self.next_buffer.replace(prev_buffer); + self.next_buffer.as_ref().unwrap() + } +} diff --git a/src/dac.rs b/src/dac.rs new file mode 100644 index 000000000..fb5f4abc6 --- /dev/null +++ b/src/dac.rs @@ -0,0 +1,64 @@ + +use super::hal; +use heapless::consts; + +pub struct Dac0Output { + outputs: heapless::spsc::Queue, + spi: hal::spi::Spi, +} + +impl Dac0Output { + pub fn new(spi: hal::spi::Spi) -> Self { + spi.inner().cr1.modify(|_, w| w.cstart().started()); + Self { spi, outputs: heapless::spsc::Queue::new() } + } + + pub fn push(&mut self, value: u16) { + self.outputs.enqueue(value).unwrap(); + } + + pub fn update(&mut self) { + match self.outputs.dequeue() { + Some(value) => self.write(value), + None => {}, + } + } + + pub fn write(&mut self, value: u16) { + unsafe { + core::ptr::write_volatile(&self.spi.inner().txdr as *const _ as *mut u16, value); + } + } +} + +pub struct Dac1Output { + outputs: heapless::spsc::Queue, + spi: hal::spi::Spi, +} + +impl Dac1Output { + pub fn new( + spi: hal::spi::Spi, + ) -> Self { + spi.inner().cr1.modify(|_, w| w.cstart().started()); + + Self { spi, outputs: heapless::spsc::Queue::new() } + } + + pub fn push(&mut self, value: u16) { + self.outputs.enqueue(value).unwrap(); + } + + pub fn update(&mut self) { + match self.outputs.dequeue() { + Some(value) => self.write(value), + None => {}, + } + } + + pub fn write(&mut self, value: u16) { + unsafe { + core::ptr::write_volatile(&self.spi.inner().txdr as *const _ as *mut u16, value); + } + } +} From 4e5459433e2f16947abd2ce812e5c8b2ba5d867f Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 3 Nov 2020 09:41:45 +0100 Subject: [PATCH 03/20] Formatting --- Cargo.lock | 1 + src/adc.rs | 74 +++++++++++++++++++++++++++++++---------------------- src/dac.rs | 29 +++++++++++++++------ src/main.rs | 21 ++++++++------- 4 files changed, 76 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 915290b36..ff768f0c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -567,6 +567,7 @@ dependencies = [ [[package]] name = "stm32h7xx-hal" version = "0.8.0" +source = "git+https://github.com/quartiq/stm32h7xx-hal?branch=feature/stabilizer-dma#5fbbfa9352f720994c210e5c21601f3acf9dc40c" dependencies = [ "bare-metal 1.0.0", "cast", diff --git a/src/adc.rs b/src/adc.rs index 15d2f63e2..dd006f199 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -1,5 +1,7 @@ -use super::{hal, DmaConfig, PeripheralToMemory, MemoryToPeripheral, TargetAddress, Transfer, DMAReq, -Stream}; +use super::{ + hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Stream, + TargetAddress, Transfer, +}; const INPUT_BUFFER_SIZE: usize = 1; @@ -62,7 +64,8 @@ pub struct Adc0Input { hal::dma::dma::Stream1, hal::spi::Spi, PeripheralToMemory, - &'static mut [u16; INPUT_BUFFER_SIZE]>, + &'static mut [u16; INPUT_BUFFER_SIZE], + >, } impl Adc0Input { @@ -76,12 +79,14 @@ impl Adc0Input { .peripheral_increment(false) .circular_buffer(true); - let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _ > = Transfer::init( - trigger_stream, - &SPI2::new(), - unsafe { &mut SPI_START }, - None, - trigger_config); + let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = + Transfer::init( + trigger_stream, + &SPI2::new(), + unsafe { &mut SPI_START }, + None, + trigger_config, + ); let data_config = DmaConfig::default() .memory_increment(true) @@ -91,12 +96,14 @@ impl Adc0Input { let mut spi = spi.disable(); spi.listen(hal::spi::Event::Error); - let mut data_transfer: Transfer<_, _, PeripheralToMemory, _ > = Transfer::init( - data_stream, - &spi, - unsafe { &mut ADC0_BUF0 }, - None, - data_config); + let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> = + Transfer::init( + data_stream, + &spi, + unsafe { &mut ADC0_BUF0 }, + None, + data_config, + ); spi.enable_dma_rx(); spi.enable_dma_tx(); @@ -115,7 +122,8 @@ impl Adc0Input { pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); - let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + let (prev_buffer, _) = + self.transfer.next_transfer(next_buffer).unwrap(); self.next_buffer.replace(prev_buffer); self.next_buffer.as_ref().unwrap() } @@ -127,7 +135,8 @@ pub struct Adc1Input { hal::dma::dma::Stream3, hal::spi::Spi, PeripheralToMemory, - &'static mut [u16; INPUT_BUFFER_SIZE]>, + &'static mut [u16; INPUT_BUFFER_SIZE], + >, } impl Adc1Input { @@ -141,12 +150,14 @@ impl Adc1Input { .peripheral_increment(false) .circular_buffer(true); - let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _ > = Transfer::init( - trigger_stream, - &SPI3::new(), - unsafe { &mut SPI_START }, - None, - trigger_config); + let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = + Transfer::init( + trigger_stream, + &SPI3::new(), + unsafe { &mut SPI_START }, + None, + trigger_config, + ); let data_config = DmaConfig::default() .memory_increment(true) @@ -156,12 +167,14 @@ impl Adc1Input { let mut spi = spi.disable(); spi.listen(hal::spi::Event::Error); - let mut data_transfer: Transfer<_, _, PeripheralToMemory, _ > = Transfer::init( - data_stream, - &spi, - unsafe { &mut ADC1_BUF0 }, - None, - data_config); + let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> = + Transfer::init( + data_stream, + &spi, + unsafe { &mut ADC1_BUF0 }, + None, + data_config, + ); spi.enable_dma_rx(); spi.enable_dma_tx(); @@ -180,7 +193,8 @@ impl Adc1Input { pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); - let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + let (prev_buffer, _) = + self.transfer.next_transfer(next_buffer).unwrap(); self.next_buffer.replace(prev_buffer); self.next_buffer.as_ref().unwrap() } diff --git a/src/dac.rs b/src/dac.rs index fb5f4abc6..575320da6 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -1,4 +1,3 @@ - use super::hal; use heapless::consts; @@ -8,9 +7,14 @@ pub struct Dac0Output { } impl Dac0Output { - pub fn new(spi: hal::spi::Spi) -> Self { + pub fn new( + spi: hal::spi::Spi, + ) -> Self { spi.inner().cr1.modify(|_, w| w.cstart().started()); - Self { spi, outputs: heapless::spsc::Queue::new() } + Self { + spi, + outputs: heapless::spsc::Queue::new(), + } } pub fn push(&mut self, value: u16) { @@ -20,13 +24,16 @@ impl Dac0Output { pub fn update(&mut self) { match self.outputs.dequeue() { Some(value) => self.write(value), - None => {}, + None => {} } } pub fn write(&mut self, value: u16) { unsafe { - core::ptr::write_volatile(&self.spi.inner().txdr as *const _ as *mut u16, value); + core::ptr::write_volatile( + &self.spi.inner().txdr as *const _ as *mut u16, + value, + ); } } } @@ -42,7 +49,10 @@ impl Dac1Output { ) -> Self { spi.inner().cr1.modify(|_, w| w.cstart().started()); - Self { spi, outputs: heapless::spsc::Queue::new() } + Self { + spi, + outputs: heapless::spsc::Queue::new(), + } } pub fn push(&mut self, value: u16) { @@ -52,13 +62,16 @@ impl Dac1Output { pub fn update(&mut self) { match self.outputs.dequeue() { Some(value) => self.write(value), - None => {}, + None => {} } } pub fn write(&mut self, value: u16) { unsafe { - core::ptr::write_volatile(&self.spi.inner().txdr as *const _ as *mut u16, value); + core::ptr::write_volatile( + &self.spi.inner().txdr as *const _ as *mut u16, + value, + ); } } } diff --git a/src/main.rs b/src/main.rs index 91058ba13..72d0db2e3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,13 +36,9 @@ use embedded_hal::digital::v2::{InputPin, OutputPin}; use hal::{ dma::{ - Transfer, - PeripheralToMemory, MemoryToPeripheral, + dma::{DMAReq, DmaConfig}, traits::{Stream, TargetAddress}, - dma::{ - DmaConfig, - DMAReq, - }, + MemoryToPeripheral, PeripheralToMemory, Transfer, }, ethernet::{self, PHY}, }; @@ -53,16 +49,16 @@ use heapless::{consts::*, String}; #[link_section = ".sram3.eth"] static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); -mod dac; mod adc; mod afe; +mod dac; mod eeprom; mod iir; mod pounder; mod server; -use dac::{Dac0Output, Dac1Output}; use adc::{Adc0Input, Adc1Input}; +use dac::{Dac0Output, Dac1Output}; #[cfg(not(feature = "semihosting"))] fn init_log() {} @@ -257,7 +253,8 @@ const APP: () = { afe::ProgrammableGainAmplifier::new(a0_pin, a1_pin) }; - let dma_streams = hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); + let dma_streams = + hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); // Configure the SPI interfaces to the ADCs and DACs. let adc0 = { @@ -714,7 +711,8 @@ const APP: () = { let mut last_result: u16 = 0; for sample in samples { let x0 = f32::from(*sample as i16); - let y0 = c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); + let y0 = + c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); last_result = y0 as i16 as u16 ^ 0x8000; //c.resources.dac0.push(last_result); } @@ -729,7 +727,8 @@ const APP: () = { let mut last_result: u16 = 0; for sample in samples { let x0 = f32::from(*sample as i16); - let y0 = c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); + let y0 = + c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); last_result = y0 as i16 as u16 ^ 0x8000; //c.resources.dac0.push(last_result); } From e95cad5bde8832c3fd2caf371f87e5d3c8d6f1e9 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 3 Nov 2020 10:52:37 +0100 Subject: [PATCH 04/20] Adding WIP updates --- src/adc.rs | 5 ++--- src/dac.rs | 23 +++++++++++++++++++++-- src/main.rs | 52 ++++++++++++++++++++++++++++++---------------------- 3 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index dd006f199..9c3aa010d 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -1,9 +1,8 @@ use super::{ - hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Stream, - TargetAddress, Transfer, + hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, TargetAddress, Transfer, }; -const INPUT_BUFFER_SIZE: usize = 1; +const INPUT_BUFFER_SIZE: usize = 25; #[link_section = ".axisram.buffers"] static mut SPI_START: [u16; 1] = [0x00]; diff --git a/src/dac.rs b/src/dac.rs index 575320da6..2c747ae18 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -4,27 +4,37 @@ use heapless::consts; pub struct Dac0Output { outputs: heapless::spsc::Queue, spi: hal::spi::Spi, + timer: hal::timer::Timer, } impl Dac0Output { pub fn new( spi: hal::spi::Spi, + mut timer: hal::timer::Timer, ) -> Self { spi.inner().cr1.modify(|_, w| w.cstart().started()); + timer.pause(); + timer.reset_counter(); + timer.clear_irq(); + timer.listen(hal::timer::Event::TimeOut); + Self { spi, outputs: heapless::spsc::Queue::new(), + timer, } } pub fn push(&mut self, value: u16) { self.outputs.enqueue(value).unwrap(); + self.timer.resume(); } pub fn update(&mut self) { + self.timer.clear_irq(); match self.outputs.dequeue() { Some(value) => self.write(value), - None => {} + None => self.timer.pause(), } } @@ -41,28 +51,37 @@ impl Dac0Output { pub struct Dac1Output { outputs: heapless::spsc::Queue, spi: hal::spi::Spi, + timer: hal::timer::Timer, } impl Dac1Output { pub fn new( spi: hal::spi::Spi, + mut timer: hal::timer::Timer, ) -> Self { spi.inner().cr1.modify(|_, w| w.cstart().started()); + timer.pause(); + timer.reset_counter(); + timer.clear_irq(); + timer.listen(hal::timer::Event::TimeOut); Self { spi, outputs: heapless::spsc::Queue::new(), + timer, } } pub fn push(&mut self, value: u16) { self.outputs.enqueue(value).unwrap(); + self.timer.resume(); } pub fn update(&mut self) { + self.timer.clear_irq(); match self.outputs.dequeue() { Some(value) => self.write(value), - None => {} + None => self.timer.pause(), } } diff --git a/src/main.rs b/src/main.rs index 72d0db2e3..a31451392 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,7 +37,7 @@ use embedded_hal::digital::v2::{InputPin, OutputPin}; use hal::{ dma::{ dma::{DMAReq, DmaConfig}, - traits::{Stream, TargetAddress}, + traits::TargetAddress, MemoryToPeripheral, PeripheralToMemory, Transfer, }, ethernet::{self, PHY}, @@ -46,6 +46,8 @@ use smoltcp as net; use heapless::{consts::*, String}; +const SAMPLE_FREQUENCY_KHZ: u32 = 800; + #[link_section = ".sram3.eth"] static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); @@ -362,7 +364,8 @@ const APP: () = { ) }; - Dac0Output::new(dac0_spi) + let timer = dp.TIM3.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM3, &ccdr.clocks); + Dac0Output::new(dac0_spi, timer) }; let dac1 = { @@ -398,7 +401,8 @@ const APP: () = { ) }; - Dac1Output::new(dac1_spi) + let timer = dp.TIM4.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM4, &ccdr.clocks); + Dac1Output::new(dac1_spi, timer) }; let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); @@ -679,7 +683,7 @@ const APP: () = { // Configure timer 2 to trigger conversions for the ADC let timer2 = - dp.TIM2.timer(50.khz(), ccdr.peripheral.TIM2, &ccdr.clocks); + dp.TIM2.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM2, &ccdr.clocks); { let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; t2_regs.dier.modify(|_, w| w.ude().set_bit()); @@ -704,36 +708,30 @@ const APP: () = { } } - #[task(binds=DMA1_STR3, resources=[adc1, dac1, iir_state, iir_ch], priority=2)] - fn adc1(c: adc1::Context) { - let samples = c.resources.adc1.transfer_complete_handler(); + #[task(binds=DMA1_STR1, resources=[adc0, dac0, iir_state, iir_ch], priority=2)] + fn adc0(mut c: adc0::Context) { + let samples = c.resources.adc0.transfer_complete_handler(); - let mut last_result: u16 = 0; for sample in samples { let x0 = f32::from(*sample as i16); let y0 = - c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); - last_result = y0 as i16 as u16 ^ 0x8000; - //c.resources.dac0.push(last_result); + c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); + let result = y0 as i16 as u16 ^ 0x8000; + c.resources.dac0.lock(|dac| dac.push(result)); } - - c.resources.dac1.write(last_result); } - #[task(binds=DMA1_STR1, resources=[adc0, dac0, iir_state, iir_ch], priority=2)] - fn adc0(c: adc0::Context) { - let samples = c.resources.adc0.transfer_complete_handler(); + #[task(binds=DMA1_STR3, resources=[adc1, dac1, iir_state, iir_ch], priority=2)] + fn adc1(mut c: adc1::Context) { + let samples = c.resources.adc1.transfer_complete_handler(); - let mut last_result: u16 = 0; for sample in samples { let x0 = f32::from(*sample as i16); let y0 = - c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); - last_result = y0 as i16 as u16 ^ 0x8000; - //c.resources.dac0.push(last_result); + c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); + let result = y0 as i16 as u16 ^ 0x8000; + c.resources.dac1.lock(|dac| dac.push(result)); } - - c.resources.dac0.write(last_result); } #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])] @@ -936,6 +934,16 @@ const APP: () = { panic!("ADC0 input overrun"); } + #[task(binds = TIM3, resources=[dac0], priority = 3)] + fn dac0(c: dac0::Context) { + c.resources.dac0.update(); + } + + #[task(binds = TIM4, resources=[dac1], priority = 3)] + fn dac1(c: dac1::Context) { + c.resources.dac1.update(); + } + extern "C" { // hw interrupt handlers for RTIC to use for scheduling tasks // one per priority From 5cc21cfde804b0713d9c34fb0d66fa8e4ee2916e Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 3 Nov 2020 16:09:00 +0100 Subject: [PATCH 05/20] Combining ADC + DAC ISRs --- src/adc.rs | 33 +++++++- src/dac.rs | 84 ++++++------------- src/iir.rs | 10 +++ src/main.rs | 228 +++++++++++++++++++++++++--------------------------- 4 files changed, 175 insertions(+), 180 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index 9c3aa010d..cb15c2783 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -1,8 +1,9 @@ use super::{ - hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, TargetAddress, Transfer, + hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, + Stream, TargetAddress, Transfer, }; -const INPUT_BUFFER_SIZE: usize = 25; +const INPUT_BUFFER_SIZE: usize = 1; #[link_section = ".axisram.buffers"] static mut SPI_START: [u16; 1] = [0x00]; @@ -57,6 +58,25 @@ unsafe impl TargetAddress for SPI3 { } } +pub struct AdcInputs { + adc0: Adc0Input, + adc1: Adc1Input, +} + +impl AdcInputs { + pub fn new(adc0: Adc0Input, adc1: Adc1Input) -> Self { + Self { adc0, adc1 } + } + + pub fn transfer_complete_handler( + &mut self, + ) -> (&[u16; INPUT_BUFFER_SIZE], &[u16; INPUT_BUFFER_SIZE]) { + let adc0_buffer = self.adc0.transfer_complete_handler(); + let adc1_buffer = self.adc1.transfer_complete_handler(); + (adc0_buffer, adc1_buffer) + } +} + pub struct Adc0Input { next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, transfer: Transfer< @@ -76,6 +96,7 @@ impl Adc0Input { let trigger_config = DmaConfig::default() .memory_increment(false) .peripheral_increment(false) + .priority(Priority::High) .circular_buffer(true); let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = @@ -89,7 +110,7 @@ impl Adc0Input { let data_config = DmaConfig::default() .memory_increment(true) - .transfer_complete_interrupt(true) + .priority(Priority::VeryHigh) .peripheral_increment(false); let mut spi = spi.disable(); @@ -121,6 +142,8 @@ impl Adc0Input { pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); + while hal::dma::dma::Stream1::::is_enabled() {} + self.transfer.clear_interrupts(); let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); self.next_buffer.replace(prev_buffer); @@ -147,6 +170,7 @@ impl Adc1Input { let trigger_config = DmaConfig::default() .memory_increment(false) .peripheral_increment(false) + .priority(Priority::High) .circular_buffer(true); let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = @@ -161,6 +185,7 @@ impl Adc1Input { let data_config = DmaConfig::default() .memory_increment(true) .transfer_complete_interrupt(true) + .priority(Priority::VeryHigh) .peripheral_increment(false); let mut spi = spi.disable(); @@ -192,6 +217,8 @@ impl Adc1Input { pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); + while hal::dma::dma::Stream3::::is_enabled() {} + self.transfer.clear_interrupts(); let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); self.next_buffer.replace(prev_buffer); diff --git a/src/dac.rs b/src/dac.rs index 2c747ae18..d2b36a31a 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -1,95 +1,61 @@ use super::hal; use heapless::consts; -pub struct Dac0Output { - outputs: heapless::spsc::Queue, - spi: hal::spi::Spi, +pub struct DacOutputs { + dac0_spi: hal::spi::Spi, + dac1_spi: hal::spi::Spi, + outputs: heapless::spsc::Queue<(u16, u16), consts::U32>, timer: hal::timer::Timer, } -impl Dac0Output { +impl DacOutputs { pub fn new( - spi: hal::spi::Spi, + dac0_spi: hal::spi::Spi, + dac1_spi: hal::spi::Spi, mut timer: hal::timer::Timer, ) -> Self { - spi.inner().cr1.modify(|_, w| w.cstart().started()); + dac0_spi.inner().cr1.modify(|_, w| w.cstart().started()); + dac1_spi.inner().cr1.modify(|_, w| w.cstart().started()); timer.pause(); timer.reset_counter(); timer.clear_irq(); timer.listen(hal::timer::Event::TimeOut); Self { - spi, + dac0_spi, + dac1_spi, outputs: heapless::spsc::Queue::new(), timer, } } - pub fn push(&mut self, value: u16) { - self.outputs.enqueue(value).unwrap(); + pub fn push(&mut self, dac0_value: u16, dac1_value: u16) { + self.outputs.enqueue((dac0_value, dac1_value)).unwrap(); self.timer.resume(); } pub fn update(&mut self) { self.timer.clear_irq(); match self.outputs.dequeue() { - Some(value) => self.write(value), - None => self.timer.pause(), - } + Some((dac0, dac1)) => self.write(dac0, dac1), + None => { + self.timer.pause(); + self.timer.reset_counter(); + self.timer.clear_irq(); + } + }; } - pub fn write(&mut self, value: u16) { + pub fn write(&mut self, dac0_value: u16, dac1_value: u16) { unsafe { core::ptr::write_volatile( - &self.spi.inner().txdr as *const _ as *mut u16, - value, + &self.dac0_spi.inner().txdr as *const _ as *mut u16, + dac0_value, ); - } - } -} -pub struct Dac1Output { - outputs: heapless::spsc::Queue, - spi: hal::spi::Spi, - timer: hal::timer::Timer, -} - -impl Dac1Output { - pub fn new( - spi: hal::spi::Spi, - mut timer: hal::timer::Timer, - ) -> Self { - spi.inner().cr1.modify(|_, w| w.cstart().started()); - timer.pause(); - timer.reset_counter(); - timer.clear_irq(); - timer.listen(hal::timer::Event::TimeOut); - - Self { - spi, - outputs: heapless::spsc::Queue::new(), - timer, - } - } - - pub fn push(&mut self, value: u16) { - self.outputs.enqueue(value).unwrap(); - self.timer.resume(); - } - - pub fn update(&mut self) { - self.timer.clear_irq(); - match self.outputs.dequeue() { - Some(value) => self.write(value), - None => self.timer.pause(), - } - } - - pub fn write(&mut self, value: u16) { - unsafe { core::ptr::write_volatile( - &self.spi.inner().txdr as *const _ as *mut u16, - value, + &self.dac1_spi.inner().txdr as *const _ as *mut u16, + dac1_value, ); } } diff --git a/src/iir.rs b/src/iir.rs index 0c34306ed..ff2d01156 100644 --- a/src/iir.rs +++ b/src/iir.rs @@ -105,4 +105,14 @@ impl IIR { xy[xy.len() / 2] = y0; y0 } + + pub fn update_from_adc_sample( + &mut self, + sample: u16, + state: &mut IIRState, + ) -> u16 { + let x0 = f32::from(sample as i16); + let y0 = self.update(state, x0); + y0 as i16 as u16 ^ 0x8000 + } } diff --git a/src/main.rs b/src/main.rs index a31451392..b176ca639 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,8 +36,9 @@ use embedded_hal::digital::v2::{InputPin, OutputPin}; use hal::{ dma::{ + config::Priority, dma::{DMAReq, DmaConfig}, - traits::TargetAddress, + traits::{Stream, TargetAddress}, MemoryToPeripheral, PeripheralToMemory, Transfer, }, ethernet::{self, PHY}, @@ -46,7 +47,7 @@ use smoltcp as net; use heapless::{consts::*, String}; -const SAMPLE_FREQUENCY_KHZ: u32 = 800; +const SAMPLE_FREQUENCY_KHZ: u32 = 500; #[link_section = ".sram3.eth"] static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); @@ -59,8 +60,8 @@ mod iir; mod pounder; mod server; -use adc::{Adc0Input, Adc1Input}; -use dac::{Dac0Output, Dac1Output}; +use adc::{Adc0Input, Adc1Input, AdcInputs}; +use dac::DacOutputs; #[cfg(not(feature = "semihosting"))] fn init_log() {} @@ -171,14 +172,12 @@ macro_rules! route_request { #[rtic::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)] const APP: () = { struct Resources { - adc0: Adc0Input, - dac0: Dac0Output, afe0: AFE0, - - adc1: Adc1Input, - dac1: Dac1Output, afe1: AFE1, + adcs: AdcInputs, + dacs: DacOutputs, + eeprom_i2c: hal::i2c::I2c, timer: hal::timer::Timer, @@ -259,79 +258,84 @@ const APP: () = { hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); // Configure the SPI interfaces to the ADCs and DACs. - let adc0 = { - let spi_miso = gpiob - .pb14 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let spi_sck = gpiob - .pb10 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); - let _spi_nss = gpiob - .pb9 - .into_alternate_af5() - .set_speed(hal::gpio::Speed::VeryHigh); + let adcs = { + let adc0 = { + let spi_miso = gpiob + .pb14 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let spi_sck = gpiob + .pb10 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); + let _spi_nss = gpiob + .pb9 + .into_alternate_af5() + .set_speed(hal::gpio::Speed::VeryHigh); - let config = hal::spi::Config::new(hal::spi::Mode { - polarity: hal::spi::Polarity::IdleHigh, - phase: hal::spi::Phase::CaptureOnSecondTransition, - }) - .manage_cs() - .suspend_when_inactive() - .cs_delay(220e-9); - - let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi( - (spi_sck, spi_miso, hal::spi::NoMosi), - config, - 50.mhz(), - ccdr.peripheral.SPI2, - &ccdr.clocks, - ); + let config = hal::spi::Config::new(hal::spi::Mode { + polarity: hal::spi::Polarity::IdleHigh, + phase: hal::spi::Phase::CaptureOnSecondTransition, + }) + .manage_cs() + .suspend_when_inactive() + .cs_delay(220e-9); - Adc0Input::new(spi, dma_streams.0, dma_streams.1) - }; + let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi( + (spi_sck, spi_miso, hal::spi::NoMosi), + config, + 50.mhz(), + ccdr.peripheral.SPI2, + &ccdr.clocks, + ); - let adc1 = { - let spi_miso = gpiob - .pb4 - .into_alternate_af6() - .set_speed(hal::gpio::Speed::VeryHigh); - let spi_sck = gpioc - .pc10 - .into_alternate_af6() - .set_speed(hal::gpio::Speed::VeryHigh); - let _spi_nss = gpioa - .pa15 - .into_alternate_af6() - .set_speed(hal::gpio::Speed::VeryHigh); + Adc0Input::new(spi, dma_streams.0, dma_streams.1) + }; - let config = hal::spi::Config::new(hal::spi::Mode { - polarity: hal::spi::Polarity::IdleHigh, - phase: hal::spi::Phase::CaptureOnSecondTransition, - }) - .manage_cs() - .suspend_when_inactive() - .cs_delay(220e-9); - - let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi( - (spi_sck, spi_miso, hal::spi::NoMosi), - config, - 50.mhz(), - ccdr.peripheral.SPI3, - &ccdr.clocks, - ); + let adc1 = { + let spi_miso = gpiob + .pb4 + .into_alternate_af6() + .set_speed(hal::gpio::Speed::VeryHigh); + let spi_sck = gpioc + .pc10 + .into_alternate_af6() + .set_speed(hal::gpio::Speed::VeryHigh); + let _spi_nss = gpioa + .pa15 + .into_alternate_af6() + .set_speed(hal::gpio::Speed::VeryHigh); + + let config = hal::spi::Config::new(hal::spi::Mode { + polarity: hal::spi::Polarity::IdleHigh, + phase: hal::spi::Phase::CaptureOnSecondTransition, + }) + .manage_cs() + .suspend_when_inactive() + .cs_delay(220e-9); + + let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi( + (spi_sck, spi_miso, hal::spi::NoMosi), + config, + 50.mhz(), + ccdr.peripheral.SPI3, + &ccdr.clocks, + ); + + Adc1Input::new(spi, dma_streams.2, dma_streams.3) + }; - Adc1Input::new(spi, dma_streams.2, dma_streams.3) + AdcInputs::new(adc0, adc1) }; - let _dac_clr_n = gpioe.pe12.into_push_pull_output().set_high().unwrap(); - let _dac0_ldac_n = - gpioe.pe11.into_push_pull_output().set_low().unwrap(); - let _dac1_ldac_n = - gpioe.pe15.into_push_pull_output().set_low().unwrap(); + let dacs = { + let _dac_clr_n = + gpioe.pe12.into_push_pull_output().set_high().unwrap(); + let _dac0_ldac_n = + gpioe.pe11.into_push_pull_output().set_low().unwrap(); + let _dac1_ldac_n = + gpioe.pe15.into_push_pull_output().set_low().unwrap(); - let dac0 = { let dac0_spi = { let spi_miso = gpioe .pe5 @@ -364,11 +368,6 @@ const APP: () = { ) }; - let timer = dp.TIM3.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM3, &ccdr.clocks); - Dac0Output::new(dac0_spi, timer) - }; - - let dac1 = { let dac1_spi = { let spi_miso = gpiof .pf8 @@ -401,8 +400,13 @@ const APP: () = { ) }; - let timer = dp.TIM4.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM4, &ccdr.clocks); - Dac1Output::new(dac1_spi, timer) + let timer = dp.TIM3.timer( + SAMPLE_FREQUENCY_KHZ.khz(), + ccdr.peripheral.TIM3, + &ccdr.clocks, + ); + + DacOutputs::new(dac0_spi, dac1_spi, timer) }; let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); @@ -682,8 +686,11 @@ const APP: () = { cp.DWT.enable_cycle_counter(); // Configure timer 2 to trigger conversions for the ADC - let timer2 = - dp.TIM2.timer(SAMPLE_FREQUENCY_KHZ.khz(), ccdr.peripheral.TIM2, &ccdr.clocks); + let timer2 = dp.TIM2.timer( + SAMPLE_FREQUENCY_KHZ.khz(), + ccdr.peripheral.TIM2, + &ccdr.clocks, + ); { let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; t2_regs.dier.modify(|_, w| w.ude().set_bit()); @@ -691,12 +698,10 @@ const APP: () = { init::LateResources { afe0: afe0, - adc0: adc0, - dac0: dac0, - afe1: afe1, - adc1: adc1, - dac1: dac1, + + adcs, + dacs, timer: timer2, pounder: pounder_devices, @@ -708,29 +713,26 @@ const APP: () = { } } - #[task(binds=DMA1_STR1, resources=[adc0, dac0, iir_state, iir_ch], priority=2)] - fn adc0(mut c: adc0::Context) { - let samples = c.resources.adc0.transfer_complete_handler(); - - for sample in samples { - let x0 = f32::from(*sample as i16); - let y0 = - c.resources.iir_ch[0].update(&mut c.resources.iir_state[0], x0); - let result = y0 as i16 as u16 ^ 0x8000; - c.resources.dac0.lock(|dac| dac.push(result)); - } + #[task(binds = TIM3, resources=[dacs], priority = 3)] + fn dac_update(c: dac_update::Context) { + c.resources.dacs.update(); } - #[task(binds=DMA1_STR3, resources=[adc1, dac1, iir_state, iir_ch], priority=2)] - fn adc1(mut c: adc1::Context) { - let samples = c.resources.adc1.transfer_complete_handler(); + #[task(binds=DMA1_STR3, resources=[adcs, dacs, iir_state, iir_ch], priority=2)] + fn adc_update(mut c: adc_update::Context) { + let (adc0_samples, adc1_samples) = + c.resources.adcs.transfer_complete_handler(); + + for (adc0, adc1) in adc0_samples.iter().zip(adc1_samples.iter()) { + let result_adc0 = c.resources.iir_ch[0] + .update_from_adc_sample(*adc0, &mut c.resources.iir_state[0]); + + let result_adc1 = c.resources.iir_ch[1] + .update_from_adc_sample(*adc1, &mut c.resources.iir_state[1]); - for sample in samples { - let x0 = f32::from(*sample as i16); - let y0 = - c.resources.iir_ch[1].update(&mut c.resources.iir_state[1], x0); - let result = y0 as i16 as u16 ^ 0x8000; - c.resources.dac1.lock(|dac| dac.push(result)); + c.resources + .dacs + .lock(|dacs| dacs.push(result_adc0, result_adc1)); } } @@ -934,16 +936,6 @@ const APP: () = { panic!("ADC0 input overrun"); } - #[task(binds = TIM3, resources=[dac0], priority = 3)] - fn dac0(c: dac0::Context) { - c.resources.dac0.update(); - } - - #[task(binds = TIM4, resources=[dac1], priority = 3)] - fn dac1(c: dac1::Context) { - c.resources.dac1.update(); - } - extern "C" { // hw interrupt handlers for RTIC to use for scheduling tasks // one per priority From aa36446f954466aea094212b471662bb645b7a6d Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 11:57:14 +0100 Subject: [PATCH 06/20] Adding updated docs for adc file --- Cargo.lock | 2 +- Cargo.toml | 4 +- src/adc.rs | 169 ++++++++++++++++++++++++++++++++++++++++++++-------- src/main.rs | 12 ++-- 4 files changed, 156 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9f1bb5db2..f247a6c4d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -501,7 +501,7 @@ dependencies = [ [[package]] name = "stm32h7xx-hal" version = "0.8.0" -source = "git+https://github.com/quartiq/stm32h7xx-hal?branch=feature/stabilizer-dma#5fbbfa9352f720994c210e5c21601f3acf9dc40c" +source = "git+https://github.com/quartiq/stm32h7xx-hal?branch=feature/dma-rtic-example#d8cb6fa5099282665f5e5068a9dcdc9ebaa63240" dependencies = [ "bare-metal 1.0.0", "cast", diff --git a/Cargo.toml b/Cargo.toml index 04bd4e5dc..049e61cf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,7 @@ path = "ad9959" [dependencies.stm32h7xx-hal] features = ["stm32h743v", "rt", "unproven", "ethernet", "quadspi"] git = "https://github.com/quartiq/stm32h7xx-hal" -branch = "feature/stabilizer-dma" +branch = "feature/dma-rtic-example" [features] semihosting = ["panic-semihosting", "cortex-m-log/semihosting"] @@ -65,7 +65,7 @@ nightly = ["cortex-m/inline-asm"] [profile.dev] codegen-units = 1 incremental = false -opt-level = 1 +opt-level = 3 [profile.release] opt-level = 3 diff --git a/src/adc.rs b/src/adc.rs index cb15c2783..039a7c32f 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -1,13 +1,36 @@ +///! Stabilizer ADC management interface +///! +///! The Stabilizer ADCs utilize a DMA channel to trigger sampling. The SPI streams are configured +///! for full-duplex operation, but only RX is connected to physical pins. A timer channel is +///! configured to generate a DMA write into the SPI TXFIFO, which initiates a SPI transfer and +///! results in an ADC sample read for both channels. +///! +///! In order to read multiple samples without interrupting the CPU, a separate DMA transfer is +///! configured to read from each of the ADC SPI RX FIFOs. Due to the design of the SPI peripheral, +///! these DMA transfers stall when no data is available in the FIFO. Thus, the DMA transfer only +///! completes after all samples have been read. When this occurs, a CPU interrupt is generated so +///! that software can process the acquired samples from both ADCs. Only one of the ADC DMA streams +///! is configured to generate an interrupt to handle both transfers, so it is necessary to ensure +///! both transfers are completed before reading the data. This is usually not significant for +///! busy-waiting because the transfers should complete at approximately the same time. use super::{ - hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, - Stream, TargetAddress, Transfer, + hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, TargetAddress, + Transfer, }; +// The desired ADC input buffer size. This is use configurable. const INPUT_BUFFER_SIZE: usize = 1; +// The following data is written by the timer ADC sample trigger into each of the SPI TXFIFOs. Note +// that because the SPI MOSI line is not connected, this data is dont-care. Data in AXI SRAM is not +// initialized on boot, so the contents are random. #[link_section = ".axisram.buffers"] static mut SPI_START: [u16; 1] = [0x00]; +// The following global buffers are used for the ADC sample DMA transfers. Two buffers are used for +// each transfer in a ping-pong buffer configuration (one is being acquired while the other is being +// processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on +// startup are undefined. #[link_section = ".axisram.buffers"] static mut ADC0_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; @@ -20,8 +43,9 @@ static mut ADC1_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; #[link_section = ".axisram.buffers"] static mut ADC1_BUF1: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; +/// SPI2 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI2 TX FIFO +/// whenever the tim2 update dma request occurs. struct SPI2 {} - impl SPI2 { pub fn new() -> Self { Self {} @@ -29,18 +53,23 @@ impl SPI2 { } unsafe impl TargetAddress for SPI2 { + /// SPI2 is configured to operate using 16-bit transfer words. type MemSize = u16; - const REQUEST_LINE: Option = Some(DMAReq::TIM2_UP as u8); + /// SPI2 DMA requests are generated whenever TIM2 CH1 comparison occurs. + const REQUEST_LINE: Option = Some(DMAReq::TIM2_CH1 as u8); + /// Whenever the DMA request occurs, it should write into SPI2's TX FIFO to start a DMA + /// transfer. fn address(&self) -> u32 { let regs = unsafe { &*hal::stm32::SPI2::ptr() }; ®s.txdr as *const _ as u32 } } +/// SPI3 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI3 TX FIFO +/// whenever the tim2 update dma request occurs. struct SPI3 {} - impl SPI3 { pub fn new() -> Self { Self {} @@ -48,26 +77,37 @@ impl SPI3 { } unsafe impl TargetAddress for SPI3 { + /// SPI3 is configured to operate using 16-bit transfer words. type MemSize = u16; - const REQUEST_LINE: Option = Some(DMAReq::TIM2_UP as u8); + /// SPI3 DMA requests are generated whenever TIM2 CH2 comparison occurs. + const REQUEST_LINE: Option = Some(DMAReq::TIM2_CH2 as u8); + /// Whenever the DMA request occurs, it should write into SPI3's TX FIFO to start a DMA + /// transfer. fn address(&self) -> u32 { let regs = unsafe { &*hal::stm32::SPI3::ptr() }; ®s.txdr as *const _ as u32 } } +/// Represents both ADC input channels. pub struct AdcInputs { adc0: Adc0Input, adc1: Adc1Input, } impl AdcInputs { + /// Construct the ADC inputs. pub fn new(adc0: Adc0Input, adc1: Adc1Input) -> Self { Self { adc0, adc1 } } + /// Interrupt handler to handle when the sample collection DMA transfer completes. + /// + /// # Returns + /// (adc0, adc1) where adcN is a reference to the collected ADC samples. Two array references + /// are returned - one for each ADC sample stream. pub fn transfer_complete_handler( &mut self, ) -> (&[u16; INPUT_BUFFER_SIZE], &[u16; INPUT_BUFFER_SIZE]) { @@ -77,6 +117,7 @@ impl AdcInputs { } } +/// Represents data associated with ADC0. pub struct Adc0Input { next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, transfer: Transfer< @@ -85,72 +126,113 @@ pub struct Adc0Input { PeripheralToMemory, &'static mut [u16; INPUT_BUFFER_SIZE], >, + _trigger_transfer: Transfer< + hal::dma::dma::Stream0, + SPI2, + MemoryToPeripheral, + &'static mut [u16; 1], + >, } impl Adc0Input { + /// Construct the ADC0 input channel. + /// + /// # Args + /// * `spi` - The SPI interface used to communicate with the ADC. + /// * `trigger_stream` - The DMA stream used to trigger each ADC transfer by writing a word into + /// the SPI TX FIFO. + /// * `data_stream` - The DMA stream used to read samples received over SPI into a data buffer. pub fn new( spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream0, data_stream: hal::dma::dma::Stream1, ) -> Self { + // The trigger stream constantly writes to the TX FIFO using a static word (dont-care + // contents). Thus, neither the memory or peripheral address ever change. This is run in + // circular mode to be completed at every DMA request. let trigger_config = DmaConfig::default() .memory_increment(false) .peripheral_increment(false) .priority(Priority::High) .circular_buffer(true); + // Construct the trigger stream to write from memory to the peripheral. let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( trigger_stream, - &SPI2::new(), + SPI2::new(), unsafe { &mut SPI_START }, None, trigger_config, ); + // The data stream constantly reads from the SPI RX FIFO into a RAM buffer. The peripheral + // stalls reads of the SPI RX FIFO until data is available, so the DMA transfer completes + // after the requested number of samples have been collected. Note that only ADC1's data + // stream is used to trigger a transfer completion interrupt. let data_config = DmaConfig::default() .memory_increment(true) .priority(Priority::VeryHigh) .peripheral_increment(false); + // A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This + // indicates that samples were dropped due to excessive processing time in the main + // application (e.g. a second DMA transfer completes before the first was done with + // processing). This is used as a flow control indicator to guarantee that no ADC samples + // are lost. let mut spi = spi.disable(); spi.listen(hal::spi::Event::Error); + // The data transfer is always a transfer of data from the peripheral to a RAM buffer. let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> = Transfer::init( data_stream, - &spi, + spi, unsafe { &mut ADC0_BUF0 }, None, data_config, ); - spi.enable_dma_rx(); - spi.enable_dma_tx(); + data_transfer.start(|spi| { + // Allow the SPI FIFOs to operate using only DMA data channels. + spi.enable_dma_rx(); + spi.enable_dma_tx(); - let spi = spi.enable(); - spi.inner().cr1.modify(|_, w| w.cstart().started()); + // Enable SPI and start it in infinite transaction mode. + spi.inner().cr1.modify(|_, w| w.spe().set_bit()); + spi.inner().cr1.modify(|_, w| w.cstart().started()); + }); - data_transfer.start(); - trigger_transfer.start(); + trigger_transfer.start(|_| {}); Self { next_buffer: unsafe { Some(&mut ADC0_BUF1) }, transfer: data_transfer, + _trigger_transfer: trigger_transfer, } } + /// Handle a transfer completion. + /// + /// # Returns + /// A reference to the underlying buffer that has been filled with ADC samples. pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); - while hal::dma::dma::Stream1::::is_enabled() {} + + // Wait for the transfer to fully complete before continuing. + while self.transfer.get_transfer_complete_flag() == false {} + + // Start the next transfer. self.transfer.clear_interrupts(); let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + self.next_buffer.replace(prev_buffer); self.next_buffer.as_ref().unwrap() } } +/// Represents the data input stream from ADC1 pub struct Adc1Input { next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, transfer: Transfer< @@ -159,68 +241,107 @@ pub struct Adc1Input { PeripheralToMemory, &'static mut [u16; INPUT_BUFFER_SIZE], >, + _trigger_transfer: Transfer< + hal::dma::dma::Stream2, + SPI3, + MemoryToPeripheral, + &'static mut [u16; 1], + >, } impl Adc1Input { + /// Construct a new ADC1 input data stream. + /// + /// # Args + /// * `spi` - The SPI interface connected to ADC1. + /// * `trigger_stream` - The DMA stream used to trigger ADC conversions on the SPI interface. + /// * `data_stream` - The DMA stream used to read ADC samples from the SPI RX FIFO. pub fn new( spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream2, data_stream: hal::dma::dma::Stream3, ) -> Self { + // The trigger stream constantly writes to the TX FIFO using a static word (dont-care + // contents). Thus, neither the memory or peripheral address ever change. This is run in + // circular mode to be completed at every DMA request. let trigger_config = DmaConfig::default() .memory_increment(false) .peripheral_increment(false) .priority(Priority::High) .circular_buffer(true); + // Construct the trigger stream to write from memory to the peripheral. let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( trigger_stream, - &SPI3::new(), + SPI3::new(), unsafe { &mut SPI_START }, None, trigger_config, ); + // The data stream constantly reads from the SPI RX FIFO into a RAM buffer. The peripheral + // stalls reads of the SPI RX FIFO until data is available, so the DMA transfer completes + // after the requested number of samples have been collected. Note that only ADC1's data + // stream is used to trigger a transfer completion interrupt. let data_config = DmaConfig::default() .memory_increment(true) .transfer_complete_interrupt(true) .priority(Priority::VeryHigh) .peripheral_increment(false); + // A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This + // indicates that samples were dropped due to excessive processing time in the main + // application (e.g. a second DMA transfer completes before the first was done with + // processing). This is used as a flow control indicator to guarantee that no ADC samples + // are lost. let mut spi = spi.disable(); spi.listen(hal::spi::Event::Error); + // The data transfer is always a transfer of data from the peripheral to a RAM buffer. let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> = Transfer::init( data_stream, - &spi, + spi, unsafe { &mut ADC1_BUF0 }, None, data_config, ); - spi.enable_dma_rx(); - spi.enable_dma_tx(); + data_transfer.start(|spi| { + // Allow the SPI FIFOs to operate using only DMA data channels. + spi.enable_dma_rx(); + spi.enable_dma_tx(); - let spi = spi.enable(); - spi.inner().cr1.modify(|_, w| w.cstart().started()); + // Enable SPI and start it in infinite transaction mode. + spi.inner().cr1.modify(|_, w| w.spe().set_bit()); + spi.inner().cr1.modify(|_, w| w.cstart().started()); + }); - data_transfer.start(); - trigger_transfer.start(); + trigger_transfer.start(|_| {}); Self { next_buffer: unsafe { Some(&mut ADC1_BUF1) }, transfer: data_transfer, + _trigger_transfer: trigger_transfer, } } + /// Handle a transfer completion. + /// + /// # Returns + /// A reference to the underlying buffer that has been filled with ADC samples. pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); - while hal::dma::dma::Stream3::::is_enabled() {} + + // Wait for the transfer to fully complete before continuing. + while self.transfer.get_transfer_complete_flag() == false {} + + // Start the next transfer. self.transfer.clear_interrupts(); let (prev_buffer, _) = self.transfer.next_transfer(next_buffer).unwrap(); + self.next_buffer.replace(prev_buffer); self.next_buffer.as_ref().unwrap() } diff --git a/src/main.rs b/src/main.rs index 3a0b00ef6..b7cf7dbc8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,4 @@ #![deny(warnings)] -// Deprecation warnings are temporarily allowed as the HAL DMA goes through updates. -#![allow(deprecated)] #![allow(clippy::missing_safety_doc)] #![no_std] #![no_main] @@ -41,7 +39,7 @@ use hal::{ dma::{ config::Priority, dma::{DMAReq, DmaConfig}, - traits::{Stream, TargetAddress}, + traits::TargetAddress, MemoryToPeripheral, PeripheralToMemory, Transfer, }, ethernet::{self, PHY}, @@ -706,8 +704,14 @@ const APP: () = { &ccdr.clocks, ); { + // Listen to the CH1 and CH2 comparison events. These channels should have a value of + // zero loaded into them, so the event should occur whenever the timer overflows. Note + // that we use channels instead of timer updates because each SPI DMA transfer needs a + // unique request line. let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; - t2_regs.dier.modify(|_, w| w.ude().set_bit()); + t2_regs + .dier + .modify(|_, w| w.cc1de().set_bit().cc2de().set_bit()); } init::LateResources { From 8f399ec12b6b5bc9cd8bae3ae51f0bd3c02227fb Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 11:57:57 +0100 Subject: [PATCH 07/20] Reverting openocd change --- openocd.gdb | 3 --- 1 file changed, 3 deletions(-) diff --git a/openocd.gdb b/openocd.gdb index c1ae67adb..e903a33fd 100644 --- a/openocd.gdb +++ b/openocd.gdb @@ -26,6 +26,3 @@ set var $t0=*$cc continue end #set var $t0=*$cc - -source ../../PyCortexMDebug/cmdebug/svd_gdb.py -svd_load ~/Downloads/STM32H743x.svd From 3088a002c015e56eb2e4535e6f8cf1927b9523e7 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 12:09:27 +0100 Subject: [PATCH 08/20] Adding documentation --- src/adc.rs | 4 ++-- src/dac.rs | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++--- src/main.rs | 10 +++++++++ 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index 039a7c32f..e3310f4d4 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -14,8 +14,8 @@ ///! both transfers are completed before reading the data. This is usually not significant for ///! busy-waiting because the transfers should complete at approximately the same time. use super::{ - hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, TargetAddress, - Transfer, + hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, + TargetAddress, Transfer, }; // The desired ADC input buffer size. This is use configurable. diff --git a/src/dac.rs b/src/dac.rs index d2b36a31a..882938543 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -1,21 +1,44 @@ +///! Stabilizer DAC output control +///! +///! Stabilizer output DACs do not currently rely on DMA requests for generating output. +///! Instead, the DACs utilize an internal queue for storing output codes. A timer then periodically +///! generates an interrupt which triggers an update of the DACs via a write over SPI. use super::hal; use heapless::consts; +/// Controller structure for managing the DAC outputs. pub struct DacOutputs { dac0_spi: hal::spi::Spi, dac1_spi: hal::spi::Spi, - outputs: heapless::spsc::Queue<(u16, u16), consts::U32>, timer: hal::timer::Timer, + + // The queue is provided a default length of 32 updates, but this queue can be updated by the + // end user to be larger if necessary. + outputs: heapless::spsc::Queue<(u16, u16), consts::U32>, } impl DacOutputs { + /// Construct a new set of DAC output controls + /// + /// # Args + /// * `dac0_spi` - The SPI interface to the DAC0 output. + /// * `dac1_spi` - The SPI interface to the DAC1 output. + /// * `timer` - The timer used to generate periodic events for updating the DACs. pub fn new( - dac0_spi: hal::spi::Spi, - dac1_spi: hal::spi::Spi, + mut dac0_spi: hal::spi::Spi, + mut dac1_spi: hal::spi::Spi, mut timer: hal::timer::Timer, ) -> Self { + // Start the DAC SPI interfaces in infinite transaction mode. CS is configured in + // auto-suspend mode. dac0_spi.inner().cr1.modify(|_, w| w.cstart().started()); dac1_spi.inner().cr1.modify(|_, w| w.cstart().started()); + + dac0_spi.listen(hal::spi::Event::Error); + dac1_spi.listen(hal::spi::Event::Error); + + // Stop the timer and begin listening for timeouts. Timeouts will be used as a means to + // generate new DAC outputs. timer.pause(); timer.reset_counter(); timer.clear_irq(); @@ -29,11 +52,28 @@ impl DacOutputs { } } + /// Push a set of new DAC output codes to the internal queue. + /// + /// # Note + /// The earlier DAC output codes will be generated within 1 update cycle of the codes. This is a + /// fixed latency currently. + /// + /// This function will panic if too many codes are written. + /// + /// # Args + /// * `dac0_value` - The value to enqueue for a DAC0 update. + /// * `dac1_value` - The value to enqueue for a DAC1 update. pub fn push(&mut self, dac0_value: u16, dac1_value: u16) { self.outputs.enqueue((dac0_value, dac1_value)).unwrap(); self.timer.resume(); } + /// Update the DAC codes with the next set of values in the internal queue. + /// + /// # Note + /// This is intended to be called from the TIM3 update ISR. + /// + /// If the last value in the queue is used, the timer is stopped. pub fn update(&mut self) { self.timer.clear_irq(); match self.outputs.dequeue() { @@ -46,7 +86,19 @@ impl DacOutputs { }; } + /// Write immediate values to the DAC outputs. + /// + /// # Note + /// The DACs will be updated as soon as the SPI transfer completes, which will be nominally + /// 320nS after this function call. + /// + /// # Args + /// * `dac0_value` - The output code to write to DAC0. + /// * `dac1_value` - The output code to write to DAC1. pub fn write(&mut self, dac0_value: u16, dac1_value: u16) { + // In order to optimize throughput and minimize latency, the DAC codes are written directly + // into the SPI TX FIFO. No error checking is conducted. Errors are handled via interrupts + // instead. unsafe { core::ptr::write_volatile( &self.dac0_spi.inner().txdr as *const _ as *mut u16, diff --git a/src/main.rs b/src/main.rs index b7cf7dbc8..b5fff6408 100644 --- a/src/main.rs +++ b/src/main.rs @@ -954,6 +954,16 @@ const APP: () = { panic!("ADC0 input overrun"); } + #[task(binds = SPI4, priority = 1)] + fn spi4(_: spi4::Context) { + panic!("DAC0 output error"); + } + + #[task(binds = SPI5, priority = 1)] + fn spi5(_: spi5::Context) { + panic!("DAC1 output error"); + } + extern "C" { // hw interrupt handlers for RTIC to use for scheduling tasks // one per priority From da9ca818563511c33586ff3c71a4431e06bf798b Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 12:12:19 +0100 Subject: [PATCH 09/20] Reverting changeset --- src/iir.rs | 10 ---------- src/main.rs | 16 ++++++++++++---- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/iir.rs b/src/iir.rs index ff2d01156..0c34306ed 100644 --- a/src/iir.rs +++ b/src/iir.rs @@ -105,14 +105,4 @@ impl IIR { xy[xy.len() / 2] = y0; y0 } - - pub fn update_from_adc_sample( - &mut self, - sample: u16, - state: &mut IIRState, - ) -> u16 { - let x0 = f32::from(sample as i16); - let y0 = self.update(state, x0); - y0 as i16 as u16 ^ 0x8000 - } } diff --git a/src/main.rs b/src/main.rs index b5fff6408..1805370c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -742,11 +742,19 @@ const APP: () = { c.resources.adcs.transfer_complete_handler(); for (adc0, adc1) in adc0_samples.iter().zip(adc1_samples.iter()) { - let result_adc0 = c.resources.iir_ch[0] - .update_from_adc_sample(*adc0, &mut c.resources.iir_state[0]); + let result_adc0 = { + let x0 = f32::from(*adc0 as i16); + let y0 = c.resources.iir_ch[0] + .update(&mut c.resources.iir_state[0], x0); + y0 as i16 as u16 ^ 0x8000 + }; - let result_adc1 = c.resources.iir_ch[1] - .update_from_adc_sample(*adc1, &mut c.resources.iir_state[1]); + let result_adc1 = { + let x1 = f32::from(*adc1 as i16); + let y1 = c.resources.iir_ch[1] + .update(&mut c.resources.iir_state[1], x1); + y1 as i16 as u16 ^ 0x8000 + }; c.resources .dacs From 3b953e36aa3ec77ee00de4c70830f196301971b5 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 18:42:34 +0100 Subject: [PATCH 10/20] Adding compile-time management of TIM2 channels --- src/adc.rs | 18 ++++++++++++++++-- src/main.rs | 46 +++++++++++++++++++++++++--------------------- 2 files changed, 41 insertions(+), 23 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index e3310f4d4..d63ebe952 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -14,8 +14,8 @@ ///! both transfers are completed before reading the data. This is usually not significant for ///! busy-waiting because the transfers should complete at approximately the same time. use super::{ - hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, - TargetAddress, Transfer, + hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral, + PeripheralToMemory, Priority, TargetAddress, Transfer, }; // The desired ADC input buffer size. This is use configurable. @@ -142,11 +142,18 @@ impl Adc0Input { /// * `trigger_stream` - The DMA stream used to trigger each ADC transfer by writing a word into /// the SPI TX FIFO. /// * `data_stream` - The DMA stream used to read samples received over SPI into a data buffer. + /// * `_trigger_channel` - The ADC sampling timer output compare channel for read triggers. pub fn new( spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream0, data_stream: hal::dma::dma::Stream1, + trigger_channel: sampling_timer::Timer2Channel1, ) -> Self { + // Generate DMA events when an output compare of the timer hitting zero (timer roll over) + // occurs. + trigger_channel.listen_dma(); + trigger_channel.to_output_compare(0); + // The trigger stream constantly writes to the TX FIFO using a static word (dont-care // contents). Thus, neither the memory or peripheral address ever change. This is run in // circular mode to be completed at every DMA request. @@ -256,11 +263,18 @@ impl Adc1Input { /// * `spi` - The SPI interface connected to ADC1. /// * `trigger_stream` - The DMA stream used to trigger ADC conversions on the SPI interface. /// * `data_stream` - The DMA stream used to read ADC samples from the SPI RX FIFO. + /// * `trigger_channel` - The ADC sampling timer output compare channel for read triggers. pub fn new( spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream2, data_stream: hal::dma::dma::Stream3, + trigger_channel: sampling_timer::Timer2Channel2, ) -> Self { + // Generate DMA events when an output compare of the timer hitting zero (timer roll over) + // occurs. + trigger_channel.listen_dma(); + trigger_channel.to_output_compare(0); + // The trigger stream constantly writes to the TX FIFO using a static word (dont-care // contents). Thus, neither the memory or peripheral address ever change. This is run in // circular mode to be completed at every DMA request. diff --git a/src/main.rs b/src/main.rs index 1805370c2..59b19fcf5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -62,6 +62,7 @@ mod dac; mod eeprom; mod iir; mod pounder; +mod sampling_timer; mod server; use adc::{Adc0Input, Adc1Input, AdcInputs}; @@ -187,8 +188,6 @@ const APP: () = { eeprom_i2c: hal::i2c::I2c, - timer: hal::timer::Timer, - // Note: It appears that rustfmt generates a format that GDB cannot recognize, which // results in GDB breakpoints being set improperly. #[rustfmt::skip] @@ -264,6 +263,16 @@ const APP: () = { let dma_streams = hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); + // Configure timer 2 to trigger conversions for the ADC + let timer2 = dp.TIM2.timer( + SAMPLE_FREQUENCY_KHZ.khz(), + ccdr.peripheral.TIM2, + &ccdr.clocks, + ); + + let mut sampling_timer = sampling_timer::SamplingTimer::new(timer2); + let sampling_timer_channels = sampling_timer.channels(); + // Configure the SPI interfaces to the ADCs and DACs. let adcs = { let adc0 = { @@ -296,7 +305,12 @@ const APP: () = { &ccdr.clocks, ); - Adc0Input::new(spi, dma_streams.0, dma_streams.1) + Adc0Input::new( + spi, + dma_streams.0, + dma_streams.1, + sampling_timer_channels.ch1, + ) }; let adc1 = { @@ -329,7 +343,12 @@ const APP: () = { &ccdr.clocks, ); - Adc1Input::new(spi, dma_streams.2, dma_streams.3) + Adc1Input::new( + spi, + dma_streams.2, + dma_streams.3, + sampling_timer_channels.ch2, + ) }; AdcInputs::new(adc0, adc1) @@ -697,22 +716,8 @@ const APP: () = { // Utilize the cycle counter for RTIC scheduling. cp.DWT.enable_cycle_counter(); - // Configure timer 2 to trigger conversions for the ADC - let timer2 = dp.TIM2.timer( - SAMPLE_FREQUENCY_KHZ.khz(), - ccdr.peripheral.TIM2, - &ccdr.clocks, - ); - { - // Listen to the CH1 and CH2 comparison events. These channels should have a value of - // zero loaded into them, so the event should occur whenever the timer overflows. Note - // that we use channels instead of timer updates because each SPI DMA transfer needs a - // unique request line. - let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; - t2_regs - .dier - .modify(|_, w| w.cc1de().set_bit().cc2de().set_bit()); - } + // Start sampling ADCs. + sampling_timer.start(); init::LateResources { afe0: afe0, @@ -721,7 +726,6 @@ const APP: () = { adcs, dacs, - timer: timer2, pounder: pounder_devices, eeprom_i2c, From 56bcf1e0aad89a6f9bc4c240ce2cb94ea113c51f Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 11 Nov 2020 18:44:28 +0100 Subject: [PATCH 11/20] Adding sampling_timer file --- src/sampling_timer.rs | 107 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/sampling_timer.rs diff --git a/src/sampling_timer.rs b/src/sampling_timer.rs new file mode 100644 index 000000000..b412b7529 --- /dev/null +++ b/src/sampling_timer.rs @@ -0,0 +1,107 @@ +///! The sampling timer is used for managing ADC sampling and external reference timestamping. +use super::hal; + +pub use hal::stm32::tim2::ccmr2_input::CC4S_A; + +/// The timer used for managing ADC sampling. +pub struct SamplingTimer { + timer: hal::timer::Timer, + channels: Option, +} + +impl SamplingTimer { + /// Construct the sampling timer. + pub fn new(mut timer: hal::timer::Timer) -> Self { + timer.pause(); + + Self { + timer, + channels: Some(TimerChannels::new()), + } + } + + /// Get the timer capture/compare channels. + pub fn channels(&mut self) -> TimerChannels { + self.channels.take().unwrap() + } + + /// Start the sampling timer. + pub fn start(&mut self) { + self.timer.reset_counter(); + self.timer.resume(); + } +} + +/// The capture/compare channels for the sampling timer. +/// +/// # Note +/// This should not be instantiated directly. +pub struct TimerChannels { + pub ch1: Timer2Channel1, + pub ch2: Timer2Channel2, + pub ch3: Timer2Channel3, + pub ch4: Timer2Channel4, +} + +impl TimerChannels { + fn new() -> Self { + Self { + ch1: Timer2Channel1 {}, + ch2: Timer2Channel2 {}, + ch3: Timer2Channel3 {}, + ch4: Timer2Channel4 {}, + } + } +} + +/// Representation of CH1 of TIM2. +pub struct Timer2Channel1 {} + +impl Timer2Channel1 { + /// Allow CH1 to generate DMA requests. + pub fn listen_dma(&self) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + regs.dier.modify(|_, w| w.cc1de().set_bit()); + } + + /// Operate CH1 as an output-compare. + /// + /// # Args + /// * `value` - The value to compare the sampling timer's counter against. + pub fn to_output_compare(&self, value: u32) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + assert!(value <= regs.arr.read().bits()); + regs.ccr1.write(|w| w.ccr().bits(value)); + regs.ccmr1_output() + .modify(|_, w| unsafe { w.cc1s().bits(0) }); + } +} + +/// Representation of CH2 of TIM2. +pub struct Timer2Channel2 {} + +impl Timer2Channel2 { + /// Allow CH2 to generate DMA requests. + pub fn listen_dma(&self) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + regs.dier.modify(|_, w| w.cc2de().set_bit()); + } + + /// Operate CH2 as an output-compare. + /// + /// # Args + /// * `value` - The value to compare the sampling timer's counter against. + pub fn to_output_compare(&self, value: u32) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + assert!(value <= regs.arr.read().bits()); + regs.ccr2.write(|w| w.ccr().bits(value)); + regs.ccmr1_output() + .modify(|_, w| unsafe { w.cc2s().bits(0) }); + } +} + +/// Representation of CH3 of TIM2. +pub struct Timer2Channel3 {} + +/// Representation of CH4 of TIM2. +pub struct Timer2Channel4 {} From 91809cf255eff81b86c5c5e530e8a0c9d1ab13fb Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Fri, 13 Nov 2020 10:47:44 +0100 Subject: [PATCH 12/20] Adding DMA support for DAC writes --- Cargo.lock | 2 +- Cargo.toml | 4 +- src/adc.rs | 27 ++-- src/dac.rs | 335 +++++++++++++++++++++++++++++++----------- src/main.rs | 46 +++--- src/sampling_timer.rs | 40 +++++ 6 files changed, 331 insertions(+), 123 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f247a6c4d..3c96c4f15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -501,7 +501,7 @@ dependencies = [ [[package]] name = "stm32h7xx-hal" version = "0.8.0" -source = "git+https://github.com/quartiq/stm32h7xx-hal?branch=feature/dma-rtic-example#d8cb6fa5099282665f5e5068a9dcdc9ebaa63240" +source = "git+https://github.com/stm32-rs/stm32h7xx-hal?branch=dma#0bfeeca4ce120c1b7c6d140a7da73a4372b874d8" dependencies = [ "bare-metal 1.0.0", "cast", diff --git a/Cargo.toml b/Cargo.toml index 049e61cf0..429fe85a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,8 +54,8 @@ path = "ad9959" [dependencies.stm32h7xx-hal] features = ["stm32h743v", "rt", "unproven", "ethernet", "quadspi"] -git = "https://github.com/quartiq/stm32h7xx-hal" -branch = "feature/dma-rtic-example" +git = "https://github.com/stm32-rs/stm32h7xx-hal" +branch = "dma" [features] semihosting = ["panic-semihosting", "cortex-m-log/semihosting"] diff --git a/src/adc.rs b/src/adc.rs index d63ebe952..55ed2a894 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -15,12 +15,9 @@ ///! busy-waiting because the transfers should complete at approximately the same time. use super::{ hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral, - PeripheralToMemory, Priority, TargetAddress, Transfer, + PeripheralToMemory, Priority, TargetAddress, Transfer, SAMPLE_BUFFER_SIZE, }; -// The desired ADC input buffer size. This is use configurable. -const INPUT_BUFFER_SIZE: usize = 1; - // The following data is written by the timer ADC sample trigger into each of the SPI TXFIFOs. Note // that because the SPI MOSI line is not connected, this data is dont-care. Data in AXI SRAM is not // initialized on boot, so the contents are random. @@ -32,16 +29,16 @@ static mut SPI_START: [u16; 1] = [0x00]; // processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on // startup are undefined. #[link_section = ".axisram.buffers"] -static mut ADC0_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; +static mut ADC0_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; #[link_section = ".axisram.buffers"] -static mut ADC0_BUF1: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; +static mut ADC0_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; #[link_section = ".axisram.buffers"] -static mut ADC1_BUF0: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; +static mut ADC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; #[link_section = ".axisram.buffers"] -static mut ADC1_BUF1: [u16; INPUT_BUFFER_SIZE] = [0; INPUT_BUFFER_SIZE]; +static mut ADC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; /// SPI2 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI2 TX FIFO /// whenever the tim2 update dma request occurs. @@ -110,7 +107,7 @@ impl AdcInputs { /// are returned - one for each ADC sample stream. pub fn transfer_complete_handler( &mut self, - ) -> (&[u16; INPUT_BUFFER_SIZE], &[u16; INPUT_BUFFER_SIZE]) { + ) -> (&[u16; SAMPLE_BUFFER_SIZE], &[u16; SAMPLE_BUFFER_SIZE]) { let adc0_buffer = self.adc0.transfer_complete_handler(); let adc1_buffer = self.adc1.transfer_complete_handler(); (adc0_buffer, adc1_buffer) @@ -119,12 +116,12 @@ impl AdcInputs { /// Represents data associated with ADC0. pub struct Adc0Input { - next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, + next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, transfer: Transfer< hal::dma::dma::Stream1, hal::spi::Spi, PeripheralToMemory, - &'static mut [u16; INPUT_BUFFER_SIZE], + &'static mut [u16; SAMPLE_BUFFER_SIZE], >, _trigger_transfer: Transfer< hal::dma::dma::Stream0, @@ -223,7 +220,7 @@ impl Adc0Input { /// /// # Returns /// A reference to the underlying buffer that has been filled with ADC samples. - pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { + pub fn transfer_complete_handler(&mut self) -> &[u16; SAMPLE_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); // Wait for the transfer to fully complete before continuing. @@ -241,12 +238,12 @@ impl Adc0Input { /// Represents the data input stream from ADC1 pub struct Adc1Input { - next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, + next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, transfer: Transfer< hal::dma::dma::Stream3, hal::spi::Spi, PeripheralToMemory, - &'static mut [u16; INPUT_BUFFER_SIZE], + &'static mut [u16; SAMPLE_BUFFER_SIZE], >, _trigger_transfer: Transfer< hal::dma::dma::Stream2, @@ -345,7 +342,7 @@ impl Adc1Input { /// /// # Returns /// A reference to the underlying buffer that has been filled with ADC samples. - pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { + pub fn transfer_complete_handler(&mut self) -> &[u16; SAMPLE_BUFFER_SIZE] { let next_buffer = self.next_buffer.take().unwrap(); // Wait for the transfer to fully complete before continuing. diff --git a/src/dac.rs b/src/dac.rs index 882938543..8057a5ace 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -1,114 +1,279 @@ -///! Stabilizer DAC output control +///! Stabilizer DAC management interface ///! -///! Stabilizer output DACs do not currently rely on DMA requests for generating output. -///! Instead, the DACs utilize an internal queue for storing output codes. A timer then periodically -///! generates an interrupt which triggers an update of the DACs via a write over SPI. -use super::hal; -use heapless::consts; +///! The Stabilizer DAC utilize a DMA channel to generate output updates. A timer channel is +///! configured to generate a DMA write into the SPI TXFIFO, which initiates a SPI transfer and +///! results in DAC update for both channels. +use super::{ + hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral, TargetAddress, + Transfer, SAMPLE_BUFFER_SIZE, +}; -/// Controller structure for managing the DAC outputs. -pub struct DacOutputs { - dac0_spi: hal::spi::Spi, - dac1_spi: hal::spi::Spi, - timer: hal::timer::Timer, +// The following global buffers are used for the DAC code DMA transfers. Two buffers are used for +// each transfer in a ping-pong buffer configuration (one is being prepared while the other is being +// processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on +// startup are undefined. +#[link_section = ".axisram.buffers"] +static mut DAC0_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut DAC0_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut DAC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + +#[link_section = ".axisram.buffers"] +static mut DAC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + +/// SPI4 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI4 TX FIFO +struct SPI4 {} +impl SPI4 { + pub fn new() -> Self { + Self {} + } +} + +unsafe impl TargetAddress for SPI4 { + /// SPI2 is configured to operate using 16-bit transfer words. + type MemSize = u16; + + /// SPI4 DMA requests are generated whenever TIM2 CH3 comparison occurs. + const REQUEST_LINE: Option = Some(DMAReq::TIM2_CH3 as u8); + + /// Whenever the DMA request occurs, it should write into SPI4's TX FIFO. + fn address(&self) -> u32 { + let regs = unsafe { &*hal::stm32::SPI4::ptr() }; + ®s.txdr as *const _ as u32 + } +} + +/// SPI5 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI5 TX FIFO +struct SPI5 {} +impl SPI5 { + pub fn new() -> Self { + Self {} + } +} - // The queue is provided a default length of 32 updates, but this queue can be updated by the - // end user to be larger if necessary. - outputs: heapless::spsc::Queue<(u16, u16), consts::U32>, +unsafe impl TargetAddress for SPI5 { + /// SPI5 is configured to operate using 16-bit transfer words. + type MemSize = u16; + + /// SPI5 DMA requests are generated whenever TIM2 CH4 comparison occurs. + const REQUEST_LINE: Option = Some(DMAReq::TIM2_CH4 as u8); + + /// Whenever the DMA request occurs, it should write into SPI5's TX FIFO + fn address(&self) -> u32 { + let regs = unsafe { &*hal::stm32::SPI5::ptr() }; + ®s.txdr as *const _ as u32 + } +} + +/// Represents both DAC output channels. +pub struct DacOutputs { + dac0: Dac0Output, + dac1: Dac1Output, } impl DacOutputs { - /// Construct a new set of DAC output controls + /// Construct the DAC outputs. + pub fn new(dac0: Dac0Output, dac1: Dac1Output) -> Self { + Self { dac0, dac1 } + } + + /// Enqueue the next DAC output codes for transmission. + /// + /// # Args + /// * `dac0_codes` - The output codes for DAC0 to enqueue. + /// * `dac1_codes` - The output codes for DAC1 to enqueue. + pub fn next_data( + &mut self, + dac0_codes: &[u16; SAMPLE_BUFFER_SIZE], + dac1_codes: &[u16; SAMPLE_BUFFER_SIZE], + ) { + self.dac0.next_data(dac0_codes); + self.dac1.next_data(dac1_codes); + } +} + +/// Represents data associated with DAC0. +pub struct Dac0Output { + next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, + _spi: hal::spi::Spi, + transfer: Transfer< + hal::dma::dma::Stream4, + SPI4, + MemoryToPeripheral, + &'static mut [u16; SAMPLE_BUFFER_SIZE], + >, + first_transfer: bool, +} + +impl Dac0Output { + /// Construct the DAC0 output channel. /// /// # Args - /// * `dac0_spi` - The SPI interface to the DAC0 output. - /// * `dac1_spi` - The SPI interface to the DAC1 output. - /// * `timer` - The timer used to generate periodic events for updating the DACs. + /// * `spi` - The SPI interface used to communicate with the ADC. + /// * `stream` - The DMA stream used to write DAC codes over SPI. + /// * `trigger_channel` - The sampling timer output compare channel for update triggers. pub fn new( - mut dac0_spi: hal::spi::Spi, - mut dac1_spi: hal::spi::Spi, - mut timer: hal::timer::Timer, + spi: hal::spi::Spi, + stream: hal::dma::dma::Stream4, + trigger_channel: sampling_timer::Timer2Channel3, ) -> Self { - // Start the DAC SPI interfaces in infinite transaction mode. CS is configured in - // auto-suspend mode. - dac0_spi.inner().cr1.modify(|_, w| w.cstart().started()); - dac1_spi.inner().cr1.modify(|_, w| w.cstart().started()); + // Generate DMA events when an output compare of the timer hitting zero (timer roll over) + // occurs. + trigger_channel.listen_dma(); + trigger_channel.to_output_compare(0); - dac0_spi.listen(hal::spi::Event::Error); - dac1_spi.listen(hal::spi::Event::Error); + // The stream constantly writes to the TX FIFO to write new update codes. + let trigger_config = DmaConfig::default() + .memory_increment(true) + .peripheral_increment(false); - // Stop the timer and begin listening for timeouts. Timeouts will be used as a means to - // generate new DAC outputs. - timer.pause(); - timer.reset_counter(); - timer.clear_irq(); - timer.listen(hal::timer::Event::TimeOut); + // Construct the trigger stream to write from memory to the peripheral. + let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( + stream, + SPI4::new(), + unsafe { &mut DAC0_BUF0 }, + None, + trigger_config, + ); + + // Listen for any potential SPI error signals, which may indicate that we are not generating + // update codes. + let mut spi = spi.disable(); + spi.listen(hal::spi::Event::Error); + + // Allow the SPI FIFOs to operate using only DMA data channels. + spi.enable_dma_tx(); + + // Enable SPI and start it in infinite transaction mode. + spi.inner().cr1.modify(|_, w| w.spe().set_bit()); + spi.inner().cr1.modify(|_, w| w.cstart().started()); Self { - dac0_spi, - dac1_spi, - outputs: heapless::spsc::Queue::new(), - timer, + transfer, + next_buffer: unsafe { Some(&mut DAC0_BUF1) }, + _spi: spi, + first_transfer: true, } } - /// Push a set of new DAC output codes to the internal queue. - /// - /// # Note - /// The earlier DAC output codes will be generated within 1 update cycle of the codes. This is a - /// fixed latency currently. - /// - /// This function will panic if too many codes are written. + /// Schedule the next set of DAC update codes. /// /// # Args - /// * `dac0_value` - The value to enqueue for a DAC0 update. - /// * `dac1_value` - The value to enqueue for a DAC1 update. - pub fn push(&mut self, dac0_value: u16, dac1_value: u16) { - self.outputs.enqueue((dac0_value, dac1_value)).unwrap(); - self.timer.resume(); + /// * `data` - The next samples to enqueue for transmission. + pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) { + let next_buffer = self.next_buffer.take().unwrap(); + + // Copy data into the next buffer + next_buffer.copy_from_slice(data); + + // If the last transfer was not complete, we didn't write all our previous DAC codes. + // Wait for all the DAC codes to get written as well. + if self.first_transfer { + self.first_transfer = false + } else { + while self.transfer.get_transfer_complete_flag() == false {} + } + + // Start the next transfer. + self.transfer.clear_interrupts(); + let (prev_buffer, _) = + self.transfer.next_transfer(next_buffer).unwrap(); + + self.next_buffer.replace(prev_buffer); } +} - /// Update the DAC codes with the next set of values in the internal queue. - /// - /// # Note - /// This is intended to be called from the TIM3 update ISR. +/// Represents the data output stream from DAC1. +pub struct Dac1Output { + next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, + _spi: hal::spi::Spi, + transfer: Transfer< + hal::dma::dma::Stream5, + SPI5, + MemoryToPeripheral, + &'static mut [u16; SAMPLE_BUFFER_SIZE], + >, + first_transfer: bool, +} + +impl Dac1Output { + /// Construct a new DAC1 output data stream. /// - /// If the last value in the queue is used, the timer is stopped. - pub fn update(&mut self) { - self.timer.clear_irq(); - match self.outputs.dequeue() { - Some((dac0, dac1)) => self.write(dac0, dac1), - None => { - self.timer.pause(); - self.timer.reset_counter(); - self.timer.clear_irq(); - } - }; + /// # Args + /// * `spi` - The SPI interface connected to DAC1. + /// * `stream` - The DMA stream used to write DAC codes the SPI TX FIFO. + /// * `trigger_channel` - The timer channel used to generate DMA requests for DAC updates. + pub fn new( + spi: hal::spi::Spi, + stream: hal::dma::dma::Stream5, + trigger_channel: sampling_timer::Timer2Channel4, + ) -> Self { + // Generate DMA events when an output compare of the timer hitting zero (timer roll over) + // occurs. + trigger_channel.listen_dma(); + trigger_channel.to_output_compare(0); + + // The trigger stream constantly writes to the TX FIFO to generate DAC updates. + let trigger_config = DmaConfig::default() + .memory_increment(true) + .peripheral_increment(false) + .circular_buffer(true); + + // Construct the stream to write from memory to the peripheral. + let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( + stream, + SPI5::new(), + unsafe { &mut DAC1_BUF0 }, + None, + trigger_config, + ); + + // Listen for any SPI errors, as this may indicate that we are not generating updates on the + // DAC. + let mut spi = spi.disable(); + spi.listen(hal::spi::Event::Error); + + // Allow the SPI FIFOs to operate using only DMA data channels. + spi.enable_dma_tx(); + + // Enable SPI and start it in infinite transaction mode. + spi.inner().cr1.modify(|_, w| w.spe().set_bit()); + spi.inner().cr1.modify(|_, w| w.cstart().started()); + + Self { + next_buffer: unsafe { Some(&mut DAC1_BUF1) }, + transfer, + _spi: spi, + first_transfer: true, + } } - /// Write immediate values to the DAC outputs. - /// - /// # Note - /// The DACs will be updated as soon as the SPI transfer completes, which will be nominally - /// 320nS after this function call. + /// Enqueue the next buffer for transmission to the DAC. /// /// # Args - /// * `dac0_value` - The output code to write to DAC0. - /// * `dac1_value` - The output code to write to DAC1. - pub fn write(&mut self, dac0_value: u16, dac1_value: u16) { - // In order to optimize throughput and minimize latency, the DAC codes are written directly - // into the SPI TX FIFO. No error checking is conducted. Errors are handled via interrupts - // instead. - unsafe { - core::ptr::write_volatile( - &self.dac0_spi.inner().txdr as *const _ as *mut u16, - dac0_value, - ); - - core::ptr::write_volatile( - &self.dac1_spi.inner().txdr as *const _ as *mut u16, - dac1_value, - ); + /// * `data` - The next data to write to the DAC. + pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) { + let next_buffer = self.next_buffer.take().unwrap(); + + // Copy data into the next buffer + next_buffer.copy_from_slice(data); + + // If the last transfer was not complete, we didn't write all our previous DAC codes. + // Wait for all the DAC codes to get written as well. + if self.first_transfer { + self.first_transfer = false + } else { + while self.transfer.get_transfer_complete_flag() == false {} } + + // Start the next transfer. + self.transfer.clear_interrupts(); + let (prev_buffer, _) = + self.transfer.next_transfer(next_buffer).unwrap(); + + self.next_buffer.replace(prev_buffer); } } diff --git a/src/main.rs b/src/main.rs index 59b19fcf5..6060d4fa0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,8 +51,12 @@ use smoltcp::wire::Ipv4Address; use heapless::{consts::*, String}; +// The desired sampling frequency of the ADCs. const SAMPLE_FREQUENCY_KHZ: u32 = 500; +// The desired ADC sample processing buffer size. +const SAMPLE_BUFFER_SIZE: usize = 1; + #[link_section = ".sram3.eth"] static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); @@ -66,7 +70,7 @@ mod sampling_timer; mod server; use adc::{Adc0Input, Adc1Input, AdcInputs}; -use dac::DacOutputs; +use dac::{Dac0Output, Dac1Output, DacOutputs}; #[cfg(not(feature = "semihosting"))] fn init_log() {} @@ -426,13 +430,17 @@ const APP: () = { ) }; - let timer = dp.TIM3.timer( - SAMPLE_FREQUENCY_KHZ.khz(), - ccdr.peripheral.TIM3, - &ccdr.clocks, + let dac0 = Dac0Output::new( + dac0_spi, + dma_streams.4, + sampling_timer_channels.ch3, ); - - DacOutputs::new(dac0_spi, dac1_spi, timer) + let dac1 = Dac1Output::new( + dac1_spi, + dma_streams.5, + sampling_timer_channels.ch4, + ); + DacOutputs::new(dac0, dac1) }; let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); @@ -735,35 +743,33 @@ const APP: () = { } } - #[task(binds = TIM3, resources=[dacs], priority = 3)] - fn dac_update(c: dac_update::Context) { - c.resources.dacs.update(); - } - #[task(binds=DMA1_STR3, resources=[adcs, dacs, iir_state, iir_ch], priority=2)] - fn adc_update(mut c: adc_update::Context) { + fn adc_update(c: adc_update::Context) { let (adc0_samples, adc1_samples) = c.resources.adcs.transfer_complete_handler(); - for (adc0, adc1) in adc0_samples.iter().zip(adc1_samples.iter()) { - let result_adc0 = { + let mut dac0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + let mut dac1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + + for (i, (adc0, adc1)) in + adc0_samples.iter().zip(adc1_samples.iter()).enumerate() + { + dac0[i] = { let x0 = f32::from(*adc0 as i16); let y0 = c.resources.iir_ch[0] .update(&mut c.resources.iir_state[0], x0); y0 as i16 as u16 ^ 0x8000 }; - let result_adc1 = { + dac1[i] = { let x1 = f32::from(*adc1 as i16); let y1 = c.resources.iir_ch[1] .update(&mut c.resources.iir_state[1], x1); y1 as i16 as u16 ^ 0x8000 }; - - c.resources - .dacs - .lock(|dacs| dacs.push(result_adc0, result_adc1)); } + + c.resources.dacs.next_data(&dac0, &dac1); } #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])] diff --git a/src/sampling_timer.rs b/src/sampling_timer.rs index b412b7529..7b3b55705 100644 --- a/src/sampling_timer.rs +++ b/src/sampling_timer.rs @@ -103,5 +103,45 @@ impl Timer2Channel2 { /// Representation of CH3 of TIM2. pub struct Timer2Channel3 {} +impl Timer2Channel3 { + /// Allow CH4 to generate DMA requests. + pub fn listen_dma(&self) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + regs.dier.modify(|_, w| w.cc3de().set_bit()); + } + + /// Operate CH2 as an output-compare. + /// + /// # Args + /// * `value` - The value to compare the sampling timer's counter against. + pub fn to_output_compare(&self, value: u32) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + assert!(value <= regs.arr.read().bits()); + regs.ccr3.write(|w| w.ccr().bits(value)); + regs.ccmr2_output() + .modify(|_, w| unsafe { w.cc3s().bits(0) }); + } +} + /// Representation of CH4 of TIM2. pub struct Timer2Channel4 {} + +impl Timer2Channel4 { + /// Allow CH4 to generate DMA requests. + pub fn listen_dma(&self) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + regs.dier.modify(|_, w| w.cc4de().set_bit()); + } + + /// Operate CH2 as an output-compare. + /// + /// # Args + /// * `value` - The value to compare the sampling timer's counter against. + pub fn to_output_compare(&self, value: u32) { + let regs = unsafe { &*hal::stm32::TIM2::ptr() }; + assert!(value <= regs.arr.read().bits()); + regs.ccr4.write(|w| w.ccr().bits(value)); + regs.ccmr2_output() + .modify(|_, w| unsafe { w.cc4s().bits(0) }); + } +} From 11e6688a14adccb955f014749503a6a832b4b643 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Mon, 23 Nov 2020 14:30:29 +0100 Subject: [PATCH 13/20] Refactoring timer channels to macros, adding safety notes --- Cargo.lock | 1 + Cargo.toml | 1 + src/adc.rs | 45 +++++++--- src/dac.rs | 38 ++++++--- src/sampling_timer.rs | 190 ++++++++++++++++++------------------------ 5 files changed, 146 insertions(+), 129 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3c96c4f15..47e2086b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -474,6 +474,7 @@ dependencies = [ "nb 1.0.0", "panic-halt", "panic-semihosting", + "paste", "serde", "serde-json-core", "smoltcp", diff --git a/Cargo.toml b/Cargo.toml index 429fe85a6..44f2d025e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ embedded-hal = "0.2.4" nb = "1.0.0" asm-delay = "0.9.0" enum-iterator = "0.6.0" +paste = "1" [dependencies.mcp23017] git = "https://github.com/mrd0ll4r/mcp23017.git" diff --git a/src/adc.rs b/src/adc.rs index 55ed2a894..9b2c53b12 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -42,13 +42,18 @@ static mut ADC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; /// SPI2 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI2 TX FIFO /// whenever the tim2 update dma request occurs. -struct SPI2 {} +struct SPI2 { + _channel: sampling_timer::tim2::Channel1, +} impl SPI2 { - pub fn new() -> Self { - Self {} + pub fn new(_channel: sampling_timer::tim2::Channel1) -> Self { + Self { _channel } } } +// Note(unsafe): This structure is only safe to instantiate once. The DMA request is hard-coded and +// may only be used if ownership of the timer2 channel 1 compare channel is assured, which is +// ensured by maintaining ownership of the channel. unsafe impl TargetAddress for SPI2 { /// SPI2 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -59,6 +64,8 @@ unsafe impl TargetAddress for SPI2 { /// Whenever the DMA request occurs, it should write into SPI2's TX FIFO to start a DMA /// transfer. fn address(&self) -> u32 { + // Note(unsafe): It is assumed that SPI2 is owned by another DMA transfer and this DMA is + // only used for the transmit-half of DMA. let regs = unsafe { &*hal::stm32::SPI2::ptr() }; ®s.txdr as *const _ as u32 } @@ -66,13 +73,18 @@ unsafe impl TargetAddress for SPI2 { /// SPI3 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI3 TX FIFO /// whenever the tim2 update dma request occurs. -struct SPI3 {} +struct SPI3 { + _channel: sampling_timer::tim2::Channel2, +} impl SPI3 { - pub fn new() -> Self { - Self {} + pub fn new(_channel: sampling_timer::tim2::Channel2) -> Self { + Self { _channel } } } +// Note(unsafe): This structure is only safe to instantiate once. The DMA request is hard-coded and +// may only be used if ownership of the timer2 channel 2 compare channel is assured, which is +// ensured by maintaining ownership of the channel. unsafe impl TargetAddress for SPI3 { /// SPI3 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -83,6 +95,8 @@ unsafe impl TargetAddress for SPI3 { /// Whenever the DMA request occurs, it should write into SPI3's TX FIFO to start a DMA /// transfer. fn address(&self) -> u32 { + // Note(unsafe): It is assumed that SPI3 is owned by another DMA transfer and this DMA is + // only used for the transmit-half of DMA. let regs = unsafe { &*hal::stm32::SPI3::ptr() }; ®s.txdr as *const _ as u32 } @@ -144,7 +158,7 @@ impl Adc0Input { spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream0, data_stream: hal::dma::dma::Stream1, - trigger_channel: sampling_timer::Timer2Channel1, + trigger_channel: sampling_timer::tim2::Channel1, ) -> Self { // Generate DMA events when an output compare of the timer hitting zero (timer roll over) // occurs. @@ -164,7 +178,10 @@ impl Adc0Input { let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( trigger_stream, - SPI2::new(), + SPI2::new(trigger_channel), + // Note(unsafe): Because this is a Memory->Peripheral transfer, this data is never + // actually modified. It technically only needs to be immutably borrowed, but the + // current HAL API only supports mutable borrows. unsafe { &mut SPI_START }, None, trigger_config, @@ -192,6 +209,8 @@ impl Adc0Input { Transfer::init( data_stream, spi, + // Note(unsafe): The ADC0_BUF0 is "owned" by this peripheral. It shall not be used + // anywhere else in the module. unsafe { &mut ADC0_BUF0 }, None, data_config, @@ -210,6 +229,8 @@ impl Adc0Input { trigger_transfer.start(|_| {}); Self { + // Note(unsafe): The ADC0_BUF1 is "owned" by this peripheral. It shall not be used + // anywhere else in the module. next_buffer: unsafe { Some(&mut ADC0_BUF1) }, transfer: data_transfer, _trigger_transfer: trigger_transfer, @@ -265,7 +286,7 @@ impl Adc1Input { spi: hal::spi::Spi, trigger_stream: hal::dma::dma::Stream2, data_stream: hal::dma::dma::Stream3, - trigger_channel: sampling_timer::Timer2Channel2, + trigger_channel: sampling_timer::tim2::Channel2, ) -> Self { // Generate DMA events when an output compare of the timer hitting zero (timer roll over) // occurs. @@ -285,7 +306,7 @@ impl Adc1Input { let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( trigger_stream, - SPI3::new(), + SPI3::new(trigger_channel), unsafe { &mut SPI_START }, None, trigger_config, @@ -314,6 +335,8 @@ impl Adc1Input { Transfer::init( data_stream, spi, + // Note(unsafe): The ADC1_BUF0 is "owned" by this peripheral. It shall not be used + // anywhere else in the module. unsafe { &mut ADC1_BUF0 }, None, data_config, @@ -332,6 +355,8 @@ impl Adc1Input { trigger_transfer.start(|_| {}); Self { + // Note(unsafe): The ADC1_BUF1 is "owned" by this peripheral. It shall not be used + // anywhere else in the module. next_buffer: unsafe { Some(&mut ADC1_BUF1) }, transfer: data_transfer, _trigger_transfer: trigger_transfer, diff --git a/src/dac.rs b/src/dac.rs index 8057a5ace..d7032dbb2 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -25,13 +25,18 @@ static mut DAC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; static mut DAC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; /// SPI4 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI4 TX FIFO -struct SPI4 {} +struct SPI4 { + _channel: sampling_timer::tim2::Channel3, +} impl SPI4 { - pub fn new() -> Self { - Self {} + pub fn new(_channel: sampling_timer::tim2::Channel3) -> Self { + Self { _channel } } } +// Note(unsafe): This is safe because the DMA request line is logically owned by this module. +// Additionally, it is only safe if the SPI TX functionality is never used, which is managed by the +// Dac0Output. unsafe impl TargetAddress for SPI4 { /// SPI2 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -41,19 +46,25 @@ unsafe impl TargetAddress for SPI4 { /// Whenever the DMA request occurs, it should write into SPI4's TX FIFO. fn address(&self) -> u32 { + // Note(unsafe): This is only safe as long as no other users write to the SPI TX FIFO. let regs = unsafe { &*hal::stm32::SPI4::ptr() }; ®s.txdr as *const _ as u32 } } /// SPI5 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI5 TX FIFO -struct SPI5 {} +struct SPI5 { + _channel: sampling_timer::tim2::Channel4, +} impl SPI5 { - pub fn new() -> Self { - Self {} + pub fn new(_channel: sampling_timer::tim2::Channel4) -> Self { + Self { _channel } } } +// Note(unsafe): This is safe because the DMA request line is logically owned by this module. +// Additionally, it is only safe if the SPI TX functionality is never used, which is managed by the +// Dac1Output. unsafe impl TargetAddress for SPI5 { /// SPI5 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -63,6 +74,7 @@ unsafe impl TargetAddress for SPI5 { /// Whenever the DMA request occurs, it should write into SPI5's TX FIFO fn address(&self) -> u32 { + // Note(unsafe): This is only safe as long as no other users write to the SPI TX FIFO. let regs = unsafe { &*hal::stm32::SPI5::ptr() }; ®s.txdr as *const _ as u32 } @@ -98,6 +110,7 @@ impl DacOutputs { /// Represents data associated with DAC0. pub struct Dac0Output { next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, + // Note: SPI TX functionality may not be used from this structure to ensure safety with DMA. _spi: hal::spi::Spi, transfer: Transfer< hal::dma::dma::Stream4, @@ -118,7 +131,7 @@ impl Dac0Output { pub fn new( spi: hal::spi::Spi, stream: hal::dma::dma::Stream4, - trigger_channel: sampling_timer::Timer2Channel3, + trigger_channel: sampling_timer::tim2::Channel3, ) -> Self { // Generate DMA events when an output compare of the timer hitting zero (timer roll over) // occurs. @@ -133,7 +146,8 @@ impl Dac0Output { // Construct the trigger stream to write from memory to the peripheral. let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( stream, - SPI4::new(), + SPI4::new(trigger_channel), + // Note(unsafe): This buffer is only used once and provided for the DMA transfer. unsafe { &mut DAC0_BUF0 }, None, trigger_config, @@ -153,6 +167,7 @@ impl Dac0Output { Self { transfer, + // Note(unsafe): This buffer is only used once and provided for the next DMA transfer. next_buffer: unsafe { Some(&mut DAC0_BUF1) }, _spi: spi, first_transfer: true, @@ -189,6 +204,7 @@ impl Dac0Output { /// Represents the data output stream from DAC1. pub struct Dac1Output { next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, + // Note: SPI TX functionality may not be used from this structure to ensure safety with DMA. _spi: hal::spi::Spi, transfer: Transfer< hal::dma::dma::Stream5, @@ -209,7 +225,7 @@ impl Dac1Output { pub fn new( spi: hal::spi::Spi, stream: hal::dma::dma::Stream5, - trigger_channel: sampling_timer::Timer2Channel4, + trigger_channel: sampling_timer::tim2::Channel4, ) -> Self { // Generate DMA events when an output compare of the timer hitting zero (timer roll over) // occurs. @@ -225,7 +241,8 @@ impl Dac1Output { // Construct the stream to write from memory to the peripheral. let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( stream, - SPI5::new(), + SPI5::new(trigger_channel), + // Note(unsafe): This buffer is only used once and provided to the transfer. unsafe { &mut DAC1_BUF0 }, None, trigger_config, @@ -244,6 +261,7 @@ impl Dac1Output { spi.inner().cr1.modify(|_, w| w.cstart().started()); Self { + // Note(unsafe): This buffer is only used once and provided for the next DMA transfer. next_buffer: unsafe { Some(&mut DAC1_BUF1) }, transfer, _spi: spi, diff --git a/src/sampling_timer.rs b/src/sampling_timer.rs index 7b3b55705..47558862e 100644 --- a/src/sampling_timer.rs +++ b/src/sampling_timer.rs @@ -1,12 +1,10 @@ ///! The sampling timer is used for managing ADC sampling and external reference timestamping. use super::hal; -pub use hal::stm32::tim2::ccmr2_input::CC4S_A; - /// The timer used for managing ADC sampling. pub struct SamplingTimer { timer: hal::timer::Timer, - channels: Option, + channels: Option, } impl SamplingTimer { @@ -16,12 +14,17 @@ impl SamplingTimer { Self { timer, - channels: Some(TimerChannels::new()), + // Note(unsafe): Once these channels are taken, we guarantee that we do not modify any + // of the underlying timer channel registers, as ownership of the channels is now + // provided through the associated channel structures. We additionally guarantee this + // can only be called once because there is only one Timer2 and this resource takes + // ownership of it once instantiated. + channels: unsafe { Some(tim2::Channels::new()) }, } } /// Get the timer capture/compare channels. - pub fn channels(&mut self) -> TimerChannels { + pub fn channels(&mut self) -> tim2::Channels { self.channels.take().unwrap() } @@ -32,116 +35,85 @@ impl SamplingTimer { } } -/// The capture/compare channels for the sampling timer. -/// -/// # Note -/// This should not be instantiated directly. -pub struct TimerChannels { - pub ch1: Timer2Channel1, - pub ch2: Timer2Channel2, - pub ch3: Timer2Channel3, - pub ch4: Timer2Channel4, -} - -impl TimerChannels { - fn new() -> Self { - Self { - ch1: Timer2Channel1 {}, - ch2: Timer2Channel2 {}, - ch3: Timer2Channel3 {}, - ch4: Timer2Channel4 {}, +macro_rules! timer_channel { + ($name:ident, $TY:ty, ($ccxde:expr, $ccrx:expr, $ccmrx_output:expr, $ccxs:expr)) => { + pub struct $name {} + + paste::paste! { + impl $name { + /// Construct a new timer channel. + /// + /// Note(unsafe): This function must only be called once. Once constructed, the + /// constructee guarantees to never modify the timer channel. + unsafe fn new() -> Self { + Self {} + } + + /// Allow CH4 to generate DMA requests. + pub fn listen_dma(&self) { + let regs = unsafe { &*<$TY>::ptr() }; + regs.dier.modify(|_, w| w.[< $ccxde >]().set_bit()); + } + + /// Operate CH2 as an output-compare. + /// + /// # Args + /// * `value` - The value to compare the sampling timer's counter against. + pub fn to_output_compare(&self, value: u32) { + let regs = unsafe { &*<$TY>::ptr() }; + assert!(value <= regs.arr.read().bits()); + regs.[< $ccrx >].write(|w| w.ccr().bits(value)); + regs.[< $ccmrx_output >]() + .modify(|_, w| unsafe { w.[< $ccxs >]().bits(0) }); + } + } } - } -} - -/// Representation of CH1 of TIM2. -pub struct Timer2Channel1 {} - -impl Timer2Channel1 { - /// Allow CH1 to generate DMA requests. - pub fn listen_dma(&self) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - regs.dier.modify(|_, w| w.cc1de().set_bit()); - } - - /// Operate CH1 as an output-compare. - /// - /// # Args - /// * `value` - The value to compare the sampling timer's counter against. - pub fn to_output_compare(&self, value: u32) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - assert!(value <= regs.arr.read().bits()); - regs.ccr1.write(|w| w.ccr().bits(value)); - regs.ccmr1_output() - .modify(|_, w| unsafe { w.cc1s().bits(0) }); - } + }; } -/// Representation of CH2 of TIM2. -pub struct Timer2Channel2 {} +pub mod tim2 { + use stm32h7xx_hal as hal; -impl Timer2Channel2 { - /// Allow CH2 to generate DMA requests. - pub fn listen_dma(&self) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - regs.dier.modify(|_, w| w.cc2de().set_bit()); + /// The channels representing the timer. + pub struct Channels { + pub ch1: Channel1, + pub ch2: Channel2, + pub ch3: Channel3, + pub ch4: Channel4, } - /// Operate CH2 as an output-compare. - /// - /// # Args - /// * `value` - The value to compare the sampling timer's counter against. - pub fn to_output_compare(&self, value: u32) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - assert!(value <= regs.arr.read().bits()); - regs.ccr2.write(|w| w.ccr().bits(value)); - regs.ccmr1_output() - .modify(|_, w| unsafe { w.cc2s().bits(0) }); - } -} - -/// Representation of CH3 of TIM2. -pub struct Timer2Channel3 {} - -impl Timer2Channel3 { - /// Allow CH4 to generate DMA requests. - pub fn listen_dma(&self) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - regs.dier.modify(|_, w| w.cc3de().set_bit()); - } - - /// Operate CH2 as an output-compare. - /// - /// # Args - /// * `value` - The value to compare the sampling timer's counter against. - pub fn to_output_compare(&self, value: u32) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - assert!(value <= regs.arr.read().bits()); - regs.ccr3.write(|w| w.ccr().bits(value)); - regs.ccmr2_output() - .modify(|_, w| unsafe { w.cc3s().bits(0) }); - } -} - -/// Representation of CH4 of TIM2. -pub struct Timer2Channel4 {} - -impl Timer2Channel4 { - /// Allow CH4 to generate DMA requests. - pub fn listen_dma(&self) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - regs.dier.modify(|_, w| w.cc4de().set_bit()); + impl Channels { + /// Construct a new set of channels. + /// + /// Note(unsafe): This is only safe to call once. + pub unsafe fn new() -> Self { + Self { + ch1: Channel1::new(), + ch2: Channel2::new(), + ch3: Channel3::new(), + ch4: Channel4::new(), + } + } } - /// Operate CH2 as an output-compare. - /// - /// # Args - /// * `value` - The value to compare the sampling timer's counter against. - pub fn to_output_compare(&self, value: u32) { - let regs = unsafe { &*hal::stm32::TIM2::ptr() }; - assert!(value <= regs.arr.read().bits()); - regs.ccr4.write(|w| w.ccr().bits(value)); - regs.ccmr2_output() - .modify(|_, w| unsafe { w.cc4s().bits(0) }); - } + timer_channel!( + Channel1, + hal::stm32::TIM2, + (cc1de, ccr1, ccmr1_output, cc1s) + ); + timer_channel!( + Channel2, + hal::stm32::TIM2, + (cc2de, ccr2, ccmr1_output, cc1s) + ); + timer_channel!( + Channel3, + hal::stm32::TIM2, + (cc3de, ccr3, ccmr2_output, cc3s) + ); + timer_channel!( + Channel4, + hal::stm32::TIM2, + (cc4de, ccr4, ccmr2_output, cc4s) + ); } From b7c6b6d203559123a0decbdb9eaff680d71c50a4 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 24 Nov 2020 16:46:14 +0100 Subject: [PATCH 14/20] Marking AXISRAM as NOLOAD --- memory.x | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memory.x b/memory.x index df4246853..c1569cedd 100644 --- a/memory.x +++ b/memory.x @@ -17,7 +17,7 @@ SECTIONS { *(.itcm .itcm.*); . = ALIGN(8); } > ITCM - .axisram : ALIGN(8) { + .axisram (NOLOAD) : ALIGN(8) { *(.axisram .axisram.*); . = ALIGN(8); } > AXISRAM From 720e0291f5582ef678ebfc968f5a87e641cebadd Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 24 Nov 2020 16:57:36 +0100 Subject: [PATCH 15/20] Removing copy to DAC buffers, adding in-place borrow of output buffers --- src/dac.rs | 52 +++++++++++++++++++++++++++++++++------------------- src/main.rs | 5 ++--- 2 files changed, 35 insertions(+), 22 deletions(-) diff --git a/src/dac.rs b/src/dac.rs index d7032dbb2..c567bf2e0 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -92,18 +92,28 @@ impl DacOutputs { Self { dac0, dac1 } } - /// Enqueue the next DAC output codes for transmission. + /// Borrow the next DAC output buffers to populate the DAC output codes in-place. /// - /// # Args - /// * `dac0_codes` - The output codes for DAC0 to enqueue. - /// * `dac1_codes` - The output codes for DAC1 to enqueue. - pub fn next_data( + /// # Returns + /// (dac0, dac1) where each value is a mutable reference to the output code array for DAC0 and + /// DAC1 respectively. + pub fn prepare_data( &mut self, - dac0_codes: &[u16; SAMPLE_BUFFER_SIZE], - dac1_codes: &[u16; SAMPLE_BUFFER_SIZE], + ) -> ( + &mut [u16; SAMPLE_BUFFER_SIZE], + &mut [u16; SAMPLE_BUFFER_SIZE], ) { - self.dac0.next_data(dac0_codes); - self.dac1.next_data(dac1_codes); + (self.dac0.prepare_buffer(), self.dac1.prepare_buffer()) + } + + /// Enqueue the next DAC output codes for transmission. + /// + /// # Note + /// It is assumed that data was populated using `prepare_data()` before this function is + /// called. + pub fn commit_data(&mut self) { + self.dac0.commit_buffer(); + self.dac1.commit_buffer(); } } @@ -174,16 +184,18 @@ impl Dac0Output { } } - /// Schedule the next set of DAC update codes. + /// Mutably borrow the next output buffer to populate it with DAC codes. + pub fn prepare_buffer(&mut self) -> &mut [u16; SAMPLE_BUFFER_SIZE] { + self.next_buffer.as_mut().unwrap() + } + + /// Enqueue the next buffer for transmission to the DAC. /// /// # Args - /// * `data` - The next samples to enqueue for transmission. - pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) { + /// * `data` - The next data to write to the DAC. + pub fn commit_buffer(&mut self) { let next_buffer = self.next_buffer.take().unwrap(); - // Copy data into the next buffer - next_buffer.copy_from_slice(data); - // If the last transfer was not complete, we didn't write all our previous DAC codes. // Wait for all the DAC codes to get written as well. if self.first_transfer { @@ -269,16 +281,18 @@ impl Dac1Output { } } + /// Mutably borrow the next output buffer to populate it with DAC codes. + pub fn prepare_buffer(&mut self) -> &mut [u16; SAMPLE_BUFFER_SIZE] { + self.next_buffer.as_mut().unwrap() + } + /// Enqueue the next buffer for transmission to the DAC. /// /// # Args /// * `data` - The next data to write to the DAC. - pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) { + pub fn commit_buffer(&mut self) { let next_buffer = self.next_buffer.take().unwrap(); - // Copy data into the next buffer - next_buffer.copy_from_slice(data); - // If the last transfer was not complete, we didn't write all our previous DAC codes. // Wait for all the DAC codes to get written as well. if self.first_transfer { diff --git a/src/main.rs b/src/main.rs index 89908f5e6..e3ddbcfc8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -748,8 +748,7 @@ const APP: () = { let (adc0_samples, adc1_samples) = c.resources.adcs.transfer_complete_handler(); - let mut dac0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; - let mut dac1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; + let (dac0, dac1) = c.resources.dacs.prepare_data(); for (i, (adc0, adc1)) in adc0_samples.iter().zip(adc1_samples.iter()).enumerate() @@ -769,7 +768,7 @@ const APP: () = { }; } - c.resources.dacs.next_data(&dac0, &dac1); + c.resources.dacs.commit_data(); } #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])] From bf8b950fe6f2a9e4688db1cc3dc7e4b15d5511c7 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 24 Nov 2020 17:09:36 +0100 Subject: [PATCH 16/20] Moving constants to a new file --- src/design_parameters.rs | 6 ++++++ src/main.rs | 13 +++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 src/design_parameters.rs diff --git a/src/design_parameters.rs b/src/design_parameters.rs new file mode 100644 index 000000000..98355687b --- /dev/null +++ b/src/design_parameters.rs @@ -0,0 +1,6 @@ +/// The ADC setup time is the number of seconds after the CSn line goes low before the serial clock +/// may begin. This is used for performing the internal ADC conversion. +pub const ADC_SETUP_TIME: f32 = 220e-9; + +/// The maximum DAC/ADC serial clock line frequency. This is a hardware limit. +pub const ADC_DAC_SCK_MHZ_MAX: u32 = 50; diff --git a/src/main.rs b/src/main.rs index e3ddbcfc8..ea6ed1c5d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -63,6 +63,7 @@ static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); mod adc; mod afe; mod dac; +mod design_parameters; mod eeprom; mod pounder; mod sampling_timer; @@ -299,12 +300,12 @@ const APP: () = { }) .manage_cs() .suspend_when_inactive() - .cs_delay(220e-9); + .cs_delay(design_parameters::ADC_SETUP_TIME); let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, - 50.mhz(), + design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(), ccdr.peripheral.SPI2, &ccdr.clocks, ); @@ -337,12 +338,12 @@ const APP: () = { }) .manage_cs() .suspend_when_inactive() - .cs_delay(220e-9); + .cs_delay(design_parameters::ADC_SETUP_TIME); let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, - 50.mhz(), + design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(), ccdr.peripheral.SPI3, &ccdr.clocks, ); @@ -392,7 +393,7 @@ const APP: () = { dp.SPI4.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, - 50.mhz(), + design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(), ccdr.peripheral.SPI4, &ccdr.clocks, ) @@ -424,7 +425,7 @@ const APP: () = { dp.SPI5.spi( (spi_sck, spi_miso, hal::spi::NoMosi), config, - 50.mhz(), + design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(), ccdr.peripheral.SPI5, &ccdr.clocks, ) From d236ea94c476aa74edcfee1985134d098daa954c Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Tue, 24 Nov 2020 17:21:14 +0100 Subject: [PATCH 17/20] Updating DAC SPI structures to own HAL SPI structure for safety guarantees --- src/adc.rs | 2 ++ src/dac.rs | 81 +++++++++++++++++++++++++++--------------------------- 2 files changed, 43 insertions(+), 40 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index 9b2c53b12..552d21032 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -307,6 +307,8 @@ impl Adc1Input { Transfer::init( trigger_stream, SPI3::new(trigger_channel), + // Note(unsafe). This transaction is read-only and SPI_START is a dont-care value, + // so it is always safe to share. unsafe { &mut SPI_START }, None, trigger_config, diff --git a/src/dac.rs b/src/dac.rs index c567bf2e0..89a31bf91 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -24,19 +24,24 @@ static mut DAC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; #[link_section = ".axisram.buffers"] static mut DAC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; -/// SPI4 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI4 TX FIFO +/// SPI4 is used as a type for indicating a DMA transfer into the SPI4 TX FIFO struct SPI4 { + spi: hal::spi::Spi, _channel: sampling_timer::tim2::Channel3, } + impl SPI4 { - pub fn new(_channel: sampling_timer::tim2::Channel3) -> Self { - Self { _channel } + pub fn new( + _channel: sampling_timer::tim2::Channel3, + spi: hal::spi::Spi, + ) -> Self { + Self { _channel, spi } } } // Note(unsafe): This is safe because the DMA request line is logically owned by this module. -// Additionally, it is only safe if the SPI TX functionality is never used, which is managed by the -// Dac0Output. +// Additionally, the SPI is owned by this structure and is known to be configured for u16 word +// sizes. unsafe impl TargetAddress for SPI4 { /// SPI2 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -46,25 +51,28 @@ unsafe impl TargetAddress for SPI4 { /// Whenever the DMA request occurs, it should write into SPI4's TX FIFO. fn address(&self) -> u32 { - // Note(unsafe): This is only safe as long as no other users write to the SPI TX FIFO. - let regs = unsafe { &*hal::stm32::SPI4::ptr() }; - ®s.txdr as *const _ as u32 + &self.spi.inner().txdr as *const _ as u32 } } /// SPI5 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI5 TX FIFO struct SPI5 { _channel: sampling_timer::tim2::Channel4, + spi: hal::spi::Spi, } + impl SPI5 { - pub fn new(_channel: sampling_timer::tim2::Channel4) -> Self { - Self { _channel } + pub fn new( + _channel: sampling_timer::tim2::Channel4, + spi: hal::spi::Spi, + ) -> Self { + Self { _channel, spi } } } // Note(unsafe): This is safe because the DMA request line is logically owned by this module. -// Additionally, it is only safe if the SPI TX functionality is never used, which is managed by the -// Dac1Output. +// Additionally, the SPI is owned by this structure and is known to be configured for u16 word +// sizes. unsafe impl TargetAddress for SPI5 { /// SPI5 is configured to operate using 16-bit transfer words. type MemSize = u16; @@ -74,9 +82,7 @@ unsafe impl TargetAddress for SPI5 { /// Whenever the DMA request occurs, it should write into SPI5's TX FIFO fn address(&self) -> u32 { - // Note(unsafe): This is only safe as long as no other users write to the SPI TX FIFO. - let regs = unsafe { &*hal::stm32::SPI5::ptr() }; - ®s.txdr as *const _ as u32 + &self.spi.inner().txdr as *const _ as u32 } } @@ -121,7 +127,6 @@ impl DacOutputs { pub struct Dac0Output { next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, // Note: SPI TX functionality may not be used from this structure to ensure safety with DMA. - _spi: hal::spi::Spi, transfer: Transfer< hal::dma::dma::Stream4, SPI4, @@ -153,16 +158,6 @@ impl Dac0Output { .memory_increment(true) .peripheral_increment(false); - // Construct the trigger stream to write from memory to the peripheral. - let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( - stream, - SPI4::new(trigger_channel), - // Note(unsafe): This buffer is only used once and provided for the DMA transfer. - unsafe { &mut DAC0_BUF0 }, - None, - trigger_config, - ); - // Listen for any potential SPI error signals, which may indicate that we are not generating // update codes. let mut spi = spi.disable(); @@ -175,11 +170,20 @@ impl Dac0Output { spi.inner().cr1.modify(|_, w| w.spe().set_bit()); spi.inner().cr1.modify(|_, w| w.cstart().started()); + // Construct the trigger stream to write from memory to the peripheral. + let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( + stream, + SPI4::new(trigger_channel, spi), + // Note(unsafe): This buffer is only used once and provided for the DMA transfer. + unsafe { &mut DAC0_BUF0 }, + None, + trigger_config, + ); + Self { transfer, // Note(unsafe): This buffer is only used once and provided for the next DMA transfer. next_buffer: unsafe { Some(&mut DAC0_BUF1) }, - _spi: spi, first_transfer: true, } } @@ -216,8 +220,6 @@ impl Dac0Output { /// Represents the data output stream from DAC1. pub struct Dac1Output { next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, - // Note: SPI TX functionality may not be used from this structure to ensure safety with DMA. - _spi: hal::spi::Spi, transfer: Transfer< hal::dma::dma::Stream5, SPI5, @@ -250,16 +252,6 @@ impl Dac1Output { .peripheral_increment(false) .circular_buffer(true); - // Construct the stream to write from memory to the peripheral. - let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( - stream, - SPI5::new(trigger_channel), - // Note(unsafe): This buffer is only used once and provided to the transfer. - unsafe { &mut DAC1_BUF0 }, - None, - trigger_config, - ); - // Listen for any SPI errors, as this may indicate that we are not generating updates on the // DAC. let mut spi = spi.disable(); @@ -272,11 +264,20 @@ impl Dac1Output { spi.inner().cr1.modify(|_, w| w.spe().set_bit()); spi.inner().cr1.modify(|_, w| w.cstart().started()); + // Construct the stream to write from memory to the peripheral. + let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( + stream, + SPI5::new(trigger_channel, spi), + // Note(unsafe): This buffer is only used once and provided to the transfer. + unsafe { &mut DAC1_BUF0 }, + None, + trigger_config, + ); + Self { // Note(unsafe): This buffer is only used once and provided for the next DMA transfer. next_buffer: unsafe { Some(&mut DAC1_BUF1) }, transfer, - _spi: spi, first_transfer: true, } } From 7d13627a0cb8f5e5acdeb7f918da9d482886303b Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 25 Nov 2020 16:29:45 +0100 Subject: [PATCH 18/20] Removing default parameter settings --- src/adc.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index 552d21032..6f7243cef 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -169,8 +169,6 @@ impl Adc0Input { // contents). Thus, neither the memory or peripheral address ever change. This is run in // circular mode to be completed at every DMA request. let trigger_config = DmaConfig::default() - .memory_increment(false) - .peripheral_increment(false) .priority(Priority::High) .circular_buffer(true); @@ -193,8 +191,7 @@ impl Adc0Input { // stream is used to trigger a transfer completion interrupt. let data_config = DmaConfig::default() .memory_increment(true) - .priority(Priority::VeryHigh) - .peripheral_increment(false); + .priority(Priority::VeryHigh); // A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This // indicates that samples were dropped due to excessive processing time in the main @@ -297,8 +294,6 @@ impl Adc1Input { // contents). Thus, neither the memory or peripheral address ever change. This is run in // circular mode to be completed at every DMA request. let trigger_config = DmaConfig::default() - .memory_increment(false) - .peripheral_increment(false) .priority(Priority::High) .circular_buffer(true); @@ -321,8 +316,7 @@ impl Adc1Input { let data_config = DmaConfig::default() .memory_increment(true) .transfer_complete_interrupt(true) - .priority(Priority::VeryHigh) - .peripheral_increment(false); + .priority(Priority::VeryHigh); // A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This // indicates that samples were dropped due to excessive processing time in the main From 88da225e4bcc2ee42a8080ca0d97d62ccd1493e2 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 25 Nov 2020 16:43:49 +0100 Subject: [PATCH 19/20] Adding comments about execution hanging to transfer complete waits --- src/adc.rs | 4 ++++ src/main.rs | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/adc.rs b/src/adc.rs index 6f7243cef..9d344dc45 100644 --- a/src/adc.rs +++ b/src/adc.rs @@ -242,6 +242,8 @@ impl Adc0Input { let next_buffer = self.next_buffer.take().unwrap(); // Wait for the transfer to fully complete before continuing. + // Note: If a device hangs up, check that this conditional is passing correctly, as there is + // no time-out checks here in the interest of execution speed. while self.transfer.get_transfer_complete_flag() == false {} // Start the next transfer. @@ -367,6 +369,8 @@ impl Adc1Input { let next_buffer = self.next_buffer.take().unwrap(); // Wait for the transfer to fully complete before continuing. + // Note: If a device hangs up, check that this conditional is passing correctly, as there is + // no time-out checks here in the interest of execution speed. while self.transfer.get_transfer_complete_flag() == false {} // Start the next transfer. diff --git a/src/main.rs b/src/main.rs index ea6ed1c5d..ece4340ed 100644 --- a/src/main.rs +++ b/src/main.rs @@ -962,22 +962,22 @@ const APP: () = { unsafe { ethernet::interrupt_handler() } } - #[task(binds = SPI2, priority = 1)] + #[task(binds = SPI2, priority = 3)] fn spi2(_: spi2::Context) { panic!("ADC0 input overrun"); } - #[task(binds = SPI3, priority = 1)] + #[task(binds = SPI3, priority = 3)] fn spi3(_: spi3::Context) { panic!("ADC0 input overrun"); } - #[task(binds = SPI4, priority = 1)] + #[task(binds = SPI4, priority = 3)] fn spi4(_: spi4::Context) { panic!("DAC0 output error"); } - #[task(binds = SPI5, priority = 1)] + #[task(binds = SPI5, priority = 3)] fn spi5(_: spi5::Context) { panic!("DAC1 output error"); } From a07be010b633b93f1297a4ee2262006d8436d580 Mon Sep 17 00:00:00 2001 From: Ryan Summers Date: Wed, 25 Nov 2020 16:46:42 +0100 Subject: [PATCH 20/20] Adding comment about checking for flag pass completion --- src/dac.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/dac.rs b/src/dac.rs index 89a31bf91..d6325c272 100644 --- a/src/dac.rs +++ b/src/dac.rs @@ -205,6 +205,8 @@ impl Dac0Output { if self.first_transfer { self.first_transfer = false } else { + // Note: If a device hangs up, check that this conditional is passing correctly, as + // there is no time-out checks here in the interest of execution speed. while self.transfer.get_transfer_complete_flag() == false {} } @@ -299,6 +301,8 @@ impl Dac1Output { if self.first_transfer { self.first_transfer = false } else { + // Note: If a device hangs up, check that this conditional is passing correctly, as + // there is no time-out checks here in the interest of execution speed. while self.transfer.get_transfer_complete_flag() == false {} }