Adding DMA support for DAC writes

This commit is contained in:
Ryan Summers 2020-11-13 10:47:44 +01:00
parent 56bcf1e0aa
commit 91809cf255
6 changed files with 348 additions and 140 deletions

2
Cargo.lock generated
View File

@ -501,7 +501,7 @@ dependencies = [
[[package]] [[package]]
name = "stm32h7xx-hal" name = "stm32h7xx-hal"
version = "0.8.0" 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 = [ dependencies = [
"bare-metal 1.0.0", "bare-metal 1.0.0",
"cast", "cast",

View File

@ -54,8 +54,8 @@ path = "ad9959"
[dependencies.stm32h7xx-hal] [dependencies.stm32h7xx-hal]
features = ["stm32h743v", "rt", "unproven", "ethernet", "quadspi"] features = ["stm32h743v", "rt", "unproven", "ethernet", "quadspi"]
git = "https://github.com/quartiq/stm32h7xx-hal" git = "https://github.com/stm32-rs/stm32h7xx-hal"
branch = "feature/dma-rtic-example" branch = "dma"
[features] [features]
semihosting = ["panic-semihosting", "cortex-m-log/semihosting"] semihosting = ["panic-semihosting", "cortex-m-log/semihosting"]

View File

@ -15,12 +15,9 @@
///! busy-waiting because the transfers should complete at approximately the same time. ///! busy-waiting because the transfers should complete at approximately the same time.
use super::{ use super::{
hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral, 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 // 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 // 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. // 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 // processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on
// startup are undefined. // startup are undefined.
#[link_section = ".axisram.buffers"] #[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"] #[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"] #[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"] #[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 /// 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. /// whenever the tim2 update dma request occurs.
@ -110,7 +107,7 @@ impl AdcInputs {
/// are returned - one for each ADC sample stream. /// are returned - one for each ADC sample stream.
pub fn transfer_complete_handler( pub fn transfer_complete_handler(
&mut self, &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 adc0_buffer = self.adc0.transfer_complete_handler();
let adc1_buffer = self.adc1.transfer_complete_handler(); let adc1_buffer = self.adc1.transfer_complete_handler();
(adc0_buffer, adc1_buffer) (adc0_buffer, adc1_buffer)
@ -119,12 +116,12 @@ impl AdcInputs {
/// Represents data associated with ADC0. /// Represents data associated with ADC0.
pub struct Adc0Input { pub struct Adc0Input {
next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
transfer: Transfer< transfer: Transfer<
hal::dma::dma::Stream1<hal::stm32::DMA1>, hal::dma::dma::Stream1<hal::stm32::DMA1>,
hal::spi::Spi<hal::stm32::SPI2, hal::spi::Disabled, u16>, hal::spi::Spi<hal::stm32::SPI2, hal::spi::Disabled, u16>,
PeripheralToMemory, PeripheralToMemory,
&'static mut [u16; INPUT_BUFFER_SIZE], &'static mut [u16; SAMPLE_BUFFER_SIZE],
>, >,
_trigger_transfer: Transfer< _trigger_transfer: Transfer<
hal::dma::dma::Stream0<hal::stm32::DMA1>, hal::dma::dma::Stream0<hal::stm32::DMA1>,
@ -223,7 +220,7 @@ impl Adc0Input {
/// ///
/// # Returns /// # Returns
/// A reference to the underlying buffer that has been filled with ADC samples. /// 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(); let next_buffer = self.next_buffer.take().unwrap();
// Wait for the transfer to fully complete before continuing. // Wait for the transfer to fully complete before continuing.
@ -241,12 +238,12 @@ impl Adc0Input {
/// Represents the data input stream from ADC1 /// Represents the data input stream from ADC1
pub struct Adc1Input { pub struct Adc1Input {
next_buffer: Option<&'static mut [u16; INPUT_BUFFER_SIZE]>, next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
transfer: Transfer< transfer: Transfer<
hal::dma::dma::Stream3<hal::stm32::DMA1>, hal::dma::dma::Stream3<hal::stm32::DMA1>,
hal::spi::Spi<hal::stm32::SPI3, hal::spi::Disabled, u16>, hal::spi::Spi<hal::stm32::SPI3, hal::spi::Disabled, u16>,
PeripheralToMemory, PeripheralToMemory,
&'static mut [u16; INPUT_BUFFER_SIZE], &'static mut [u16; SAMPLE_BUFFER_SIZE],
>, >,
_trigger_transfer: Transfer< _trigger_transfer: Transfer<
hal::dma::dma::Stream2<hal::stm32::DMA1>, hal::dma::dma::Stream2<hal::stm32::DMA1>,
@ -345,7 +342,7 @@ impl Adc1Input {
/// ///
/// # Returns /// # Returns
/// A reference to the underlying buffer that has been filled with ADC samples. /// 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(); let next_buffer = self.next_buffer.take().unwrap();
// Wait for the transfer to fully complete before continuing. // Wait for the transfer to fully complete before continuing.

View File

@ -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. ///! The Stabilizer DAC utilize a DMA channel to generate output updates. A timer channel is
///! Instead, the DACs utilize an internal queue for storing output codes. A timer then periodically ///! configured to generate a DMA write into the SPI TXFIFO, which initiates a SPI transfer and
///! generates an interrupt which triggers an update of the DACs via a write over SPI. ///! results in DAC update for both channels.
use super::hal; use super::{
use heapless::consts; hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral, TargetAddress,
Transfer, SAMPLE_BUFFER_SIZE,
};
/// Controller structure for managing the DAC outputs. // 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<MemoryToPeripheral> 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<u8> = 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() };
&regs.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 {}
}
}
unsafe impl TargetAddress<MemoryToPeripheral> 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<u8> = 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() };
&regs.txdr as *const _ as u32
}
}
/// Represents both DAC output channels.
pub struct DacOutputs { pub struct DacOutputs {
dac0_spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>, dac0: Dac0Output,
dac1_spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Enabled, u16>, dac1: Dac1Output,
timer: hal::timer::Timer<hal::stm32::TIM3>,
// 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 { 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 /// # Args
/// * `dac0_spi` - The SPI interface to the DAC0 output. /// * `dac0_codes` - The output codes for DAC0 to enqueue.
/// * `dac1_spi` - The SPI interface to the DAC1 output. /// * `dac1_codes` - The output codes for DAC1 to enqueue.
/// * `timer` - The timer used to generate periodic events for updating the DACs. 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<hal::stm32::SPI4, hal::spi::Disabled, u16>,
transfer: Transfer<
hal::dma::dma::Stream4<hal::stm32::DMA1>,
SPI4,
MemoryToPeripheral,
&'static mut [u16; SAMPLE_BUFFER_SIZE],
>,
first_transfer: bool,
}
impl Dac0Output {
/// Construct the DAC0 output channel.
///
/// # Args
/// * `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( pub fn new(
mut dac0_spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>, spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>,
mut dac1_spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Enabled, u16>, stream: hal::dma::dma::Stream4<hal::stm32::DMA1>,
mut timer: hal::timer::Timer<hal::stm32::TIM3>, trigger_channel: sampling_timer::Timer2Channel3,
) -> Self { ) -> Self {
// Start the DAC SPI interfaces in infinite transaction mode. CS is configured in // Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// auto-suspend mode. // occurs.
dac0_spi.inner().cr1.modify(|_, w| w.cstart().started()); trigger_channel.listen_dma();
dac1_spi.inner().cr1.modify(|_, w| w.cstart().started()); trigger_channel.to_output_compare(0);
dac0_spi.listen(hal::spi::Event::Error); // The stream constantly writes to the TX FIFO to write new update codes.
dac1_spi.listen(hal::spi::Event::Error); 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 // Construct the trigger stream to write from memory to the peripheral.
// generate new DAC outputs. let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init(
timer.pause(); stream,
timer.reset_counter(); SPI4::new(),
timer.clear_irq(); unsafe { &mut DAC0_BUF0 },
timer.listen(hal::timer::Event::TimeOut); 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 { Self {
dac0_spi, transfer,
dac1_spi, next_buffer: unsafe { Some(&mut DAC0_BUF1) },
outputs: heapless::spsc::Queue::new(), _spi: spi,
timer, first_transfer: true,
} }
} }
/// Push a set of new DAC output codes to the internal queue. /// Schedule the next set of DAC update codes.
///
/// # 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 /// # Args
/// * `dac0_value` - The value to enqueue for a DAC0 update. /// * `data` - The next samples to enqueue for transmission.
/// * `dac1_value` - The value to enqueue for a DAC1 update. pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) {
pub fn push(&mut self, dac0_value: u16, dac1_value: u16) { let next_buffer = self.next_buffer.take().unwrap();
self.outputs.enqueue((dac0_value, dac1_value)).unwrap();
self.timer.resume(); // 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 {}
} }
/// Update the DAC codes with the next set of values in the internal queue. // Start the next transfer.
/// self.transfer.clear_interrupts();
/// # Note let (prev_buffer, _) =
/// This is intended to be called from the TIM3 update ISR. self.transfer.next_transfer(next_buffer).unwrap();
///
/// If the last value in the queue is used, the timer is stopped. self.next_buffer.replace(prev_buffer);
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();
} }
};
} }
/// Write immediate values to the DAC outputs. /// Represents the data output stream from DAC1.
/// pub struct Dac1Output {
/// # Note next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
/// The DACs will be updated as soon as the SPI transfer completes, which will be nominally _spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
/// 320nS after this function call. transfer: Transfer<
hal::dma::dma::Stream5<hal::stm32::DMA1>,
SPI5,
MemoryToPeripheral,
&'static mut [u16; SAMPLE_BUFFER_SIZE],
>,
first_transfer: bool,
}
impl Dac1Output {
/// Construct a new DAC1 output data stream.
/// ///
/// # Args /// # Args
/// * `dac0_value` - The output code to write to DAC0. /// * `spi` - The SPI interface connected to DAC1.
/// * `dac1_value` - The output code to write to DAC1. /// * `stream` - The DMA stream used to write DAC codes the SPI TX FIFO.
pub fn write(&mut self, dac0_value: u16, dac1_value: u16) { /// * `trigger_channel` - The timer channel used to generate DMA requests for DAC updates.
// In order to optimize throughput and minimize latency, the DAC codes are written directly pub fn new(
// into the SPI TX FIFO. No error checking is conducted. Errors are handled via interrupts spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Enabled, u16>,
// instead. stream: hal::dma::dma::Stream5<hal::stm32::DMA1>,
unsafe { trigger_channel: sampling_timer::Timer2Channel4,
core::ptr::write_volatile( ) -> Self {
&self.dac0_spi.inner().txdr as *const _ as *mut u16, // Generate DMA events when an output compare of the timer hitting zero (timer roll over)
dac0_value, // 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,
); );
core::ptr::write_volatile( // Listen for any SPI errors, as this may indicate that we are not generating updates on the
&self.dac1_spi.inner().txdr as *const _ as *mut u16, // DAC.
dac1_value, 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,
} }
} }
/// 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]) {
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);
}
} }

View File

@ -51,8 +51,12 @@ use smoltcp::wire::Ipv4Address;
use heapless::{consts::*, String}; use heapless::{consts::*, String};
// The desired sampling frequency of the ADCs.
const SAMPLE_FREQUENCY_KHZ: u32 = 500; const SAMPLE_FREQUENCY_KHZ: u32 = 500;
// The desired ADC sample processing buffer size.
const SAMPLE_BUFFER_SIZE: usize = 1;
#[link_section = ".sram3.eth"] #[link_section = ".sram3.eth"]
static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new(); static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new();
@ -66,7 +70,7 @@ mod sampling_timer;
mod server; mod server;
use adc::{Adc0Input, Adc1Input, AdcInputs}; use adc::{Adc0Input, Adc1Input, AdcInputs};
use dac::DacOutputs; use dac::{Dac0Output, Dac1Output, DacOutputs};
#[cfg(not(feature = "semihosting"))] #[cfg(not(feature = "semihosting"))]
fn init_log() {} fn init_log() {}
@ -426,13 +430,17 @@ const APP: () = {
) )
}; };
let timer = dp.TIM3.timer( let dac0 = Dac0Output::new(
SAMPLE_FREQUENCY_KHZ.khz(), dac0_spi,
ccdr.peripheral.TIM3, dma_streams.4,
&ccdr.clocks, sampling_timer_channels.ch3,
); );
let dac1 = Dac1Output::new(
DacOutputs::new(dac0_spi, dac1_spi, timer) dac1_spi,
dma_streams.5,
sampling_timer_channels.ch4,
);
DacOutputs::new(dac0, dac1)
}; };
let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); 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)] #[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) = let (adc0_samples, adc1_samples) =
c.resources.adcs.transfer_complete_handler(); c.resources.adcs.transfer_complete_handler();
for (adc0, adc1) in adc0_samples.iter().zip(adc1_samples.iter()) { let mut dac0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
let result_adc0 = { 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 x0 = f32::from(*adc0 as i16);
let y0 = c.resources.iir_ch[0] let y0 = c.resources.iir_ch[0]
.update(&mut c.resources.iir_state[0], x0); .update(&mut c.resources.iir_state[0], x0);
y0 as i16 as u16 ^ 0x8000 y0 as i16 as u16 ^ 0x8000
}; };
let result_adc1 = { dac1[i] = {
let x1 = f32::from(*adc1 as i16); let x1 = f32::from(*adc1 as i16);
let y1 = c.resources.iir_ch[1] let y1 = c.resources.iir_ch[1]
.update(&mut c.resources.iir_state[1], x1); .update(&mut c.resources.iir_state[1], x1);
y1 as i16 as u16 ^ 0x8000 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])] #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])]

View File

@ -103,5 +103,45 @@ impl Timer2Channel2 {
/// Representation of CH3 of TIM2. /// Representation of CH3 of TIM2.
pub struct Timer2Channel3 {} 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. /// Representation of CH4 of TIM2.
pub struct Timer2Channel4 {} 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) });
}
}