180: Feature/adc dac io macros r=jordens a=jordens

I wanted to try macros.
This moves the ADC and DAC DMA setup into macros reducing code footprint. Hopefully no functional changes there.
I didn't test this on hardware and I may have missed differences between `Adc0`/`Adc1` and `Dac0`/`Dac1`.

It removes the `AdcInputs` and `DacOutputs` structs and replaces them with tuples as they were just fan-outs/fan-ins.
It also does some minor tweaks in the `process()` ISR towards higher flexibility enforces some data patterns to help the compiler.

Differences missing:
* [x] `.transfer_complete_interrupt(true)` for `Adc1` only: needed
* [x] `.circular_buffer(true);` for `Dac1` only: close #183 

Co-authored-by: Robert Jördens <rj@quartiq.de>
This commit is contained in:
bors[bot] 2020-12-02 13:57:50 +00:00 committed by GitHub
commit 051715ea32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 341 additions and 684 deletions

View File

@ -27,126 +27,66 @@ static mut SPI_START: [u16; 1] = [0x00];
// The following global buffers are used for the ADC sample DMA transfers. Two buffers are used for // 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 // 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 // processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on
// startup are undefined. // startup are undefined. The dimensions are `ADC_BUF[adc_index][ping_pong_index][sample_index]`.
#[link_section = ".axisram.buffers"] #[link_section = ".axisram.buffers"]
static mut ADC0_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; static mut ADC_BUF: [[[u16; SAMPLE_BUFFER_SIZE]; 2]; 2] =
[[[0; SAMPLE_BUFFER_SIZE]; 2]; 2];
#[link_section = ".axisram.buffers"] macro_rules! adc_input {
static mut ADC0_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; ($name:ident, $index:literal, $trigger_stream:ident, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
#[link_section = ".axisram.buffers"] /// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
static mut ADC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
#[link_section = ".axisram.buffers"]
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. /// whenever the tim2 update dma request occurs.
struct SPI2 { struct $spi {
_channel: sampling_timer::tim2::Channel1, _channel: sampling_timer::tim2::$trigger_channel,
} }
impl SPI2 { impl $spi {
pub fn new(_channel: sampling_timer::tim2::Channel1) -> Self { pub fn new(
_channel: sampling_timer::tim2::$trigger_channel,
) -> Self {
Self { _channel } Self { _channel }
} }
} }
// Note(unsafe): This structure is only safe to instantiate once. The DMA request is hard-coded and // 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 // may only be used if ownership of the timer2 $trigger_channel compare channel is assured, which is
// ensured by maintaining ownership of the channel. // ensured by maintaining ownership of the channel.
unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 { unsafe impl TargetAddress<MemoryToPeripheral> for $spi {
/// SPI2 is configured to operate using 16-bit transfer words. /// SPI is configured to operate using 16-bit transfer words.
type MemSize = u16; type MemSize = u16;
/// SPI2 DMA requests are generated whenever TIM2 CH1 comparison occurs. /// SPI DMA requests are generated whenever TIM2 CHx ($dma_req) comparison occurs.
const REQUEST_LINE: Option<u8> = Some(DMAReq::TIM2_CH1 as u8); const REQUEST_LINE: Option<u8> = Some(DMAReq::$dma_req as u8);
/// Whenever the DMA request occurs, it should write into SPI2's TX FIFO to start a DMA /// Whenever the DMA request occurs, it should write into SPI's TX FIFO to start a DMA
/// transfer. /// transfer.
fn address(&self) -> u32 { fn address(&self) -> u32 {
// Note(unsafe): It is assumed that SPI2 is owned by another DMA transfer and this DMA is // Note(unsafe): It is assumed that SPI is owned by another DMA transfer and this DMA is
// only used for the transmit-half of DMA. // only used for the transmit-half of DMA.
let regs = unsafe { &*hal::stm32::SPI2::ptr() }; let regs = unsafe { &*hal::stm32::$spi::ptr() };
&regs.txdr as *const _ as u32 &regs.txdr as *const _ as u32
} }
} }
/// SPI3 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI3 TX FIFO /// Represents data associated with ADC.
/// whenever the tim2 update dma request occurs. pub struct $name {
struct SPI3 {
_channel: sampling_timer::tim2::Channel2,
}
impl SPI3 {
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<MemoryToPeripheral> for SPI3 {
/// SPI3 is configured to operate using 16-bit transfer words.
type MemSize = u16;
/// SPI3 DMA requests are generated whenever TIM2 CH2 comparison occurs.
const REQUEST_LINE: Option<u8> = 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 {
// 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() };
&regs.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; 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)
}
}
/// Represents data associated with ADC0.
pub struct Adc0Input {
next_buffer: Option<&'static mut [u16; SAMPLE_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::$data_stream<hal::stm32::DMA1>,
hal::spi::Spi<hal::stm32::SPI2, hal::spi::Disabled, u16>, hal::spi::Spi<hal::stm32::$spi, hal::spi::Disabled, u16>,
PeripheralToMemory, PeripheralToMemory,
&'static mut [u16; SAMPLE_BUFFER_SIZE], &'static mut [u16; SAMPLE_BUFFER_SIZE],
>, >,
_trigger_transfer: Transfer< _trigger_transfer: Transfer<
hal::dma::dma::Stream0<hal::stm32::DMA1>, hal::dma::dma::$trigger_stream<hal::stm32::DMA1>,
SPI2, $spi,
MemoryToPeripheral, MemoryToPeripheral,
&'static mut [u16; 1], &'static mut [u16; 1],
>, >,
} }
impl Adc0Input { impl $name {
/// Construct the ADC0 input channel. /// Construct the ADC input channel.
/// ///
/// # Args /// # Args
/// * `spi` - The SPI interface used to communicate with the ADC. /// * `spi` - The SPI interface used to communicate with the ADC.
@ -155,10 +95,12 @@ impl Adc0Input {
/// * `data_stream` - The DMA stream used to read samples received over SPI into a data buffer. /// * `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. /// * `_trigger_channel` - The ADC sampling timer output compare channel for read triggers.
pub fn new( pub fn new(
spi: hal::spi::Spi<hal::stm32::SPI2, hal::spi::Enabled, u16>, spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Enabled, u16>,
trigger_stream: hal::dma::dma::Stream0<hal::stm32::DMA1>, trigger_stream: hal::dma::dma::$trigger_stream<
data_stream: hal::dma::dma::Stream1<hal::stm32::DMA1>, hal::stm32::DMA1,
trigger_channel: sampling_timer::tim2::Channel1, >,
data_stream: hal::dma::dma::$data_stream<hal::stm32::DMA1>,
trigger_channel: sampling_timer::tim2::$trigger_channel,
) -> Self { ) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over) // Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs. // occurs.
@ -173,10 +115,14 @@ impl Adc0Input {
.circular_buffer(true); .circular_buffer(true);
// Construct the trigger stream to write from memory to the peripheral. // Construct the trigger stream to write from memory to the peripheral.
let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = let mut trigger_transfer: Transfer<
Transfer::init( _,
_,
MemoryToPeripheral,
_,
> = Transfer::init(
trigger_stream, trigger_stream,
SPI2::new(trigger_channel), $spi::new(trigger_channel),
// Note(unsafe): Because this is a Memory->Peripheral transfer, this data is never // 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 // actually modified. It technically only needs to be immutably borrowed, but the
// current HAL API only supports mutable borrows. // current HAL API only supports mutable borrows.
@ -187,10 +133,11 @@ impl Adc0Input {
// The data stream constantly reads from the SPI RX FIFO into a RAM buffer. The peripheral // 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 // 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 // after the requested number of samples have been collected. Note that only ADC1's (sic!)
// stream is used to trigger a transfer completion interrupt. // data stream is used to trigger a transfer completion interrupt.
let data_config = DmaConfig::default() let data_config = DmaConfig::default()
.memory_increment(true) .memory_increment(true)
.transfer_complete_interrupt($index == 1)
.priority(Priority::VeryHigh); .priority(Priority::VeryHigh);
// A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This // A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This
@ -206,9 +153,9 @@ impl Adc0Input {
Transfer::init( Transfer::init(
data_stream, data_stream,
spi, spi,
// Note(unsafe): The ADC0_BUF0 is "owned" by this peripheral. It shall not be used // Note(unsafe): The ADC_BUF[$index][0] is "owned" by this peripheral.
// anywhere else in the module. // It shall not be used anywhere else in the module.
unsafe { &mut ADC0_BUF0 }, unsafe { &mut ADC_BUF[$index][0] },
None, None,
data_config, data_config,
); );
@ -226,159 +173,38 @@ impl Adc0Input {
trigger_transfer.start(|_| {}); trigger_transfer.start(|_| {});
Self { Self {
// Note(unsafe): The ADC0_BUF1 is "owned" by this peripheral. It shall not be used // Note(unsafe): The ADC_BUF[$index][1] is "owned" by this peripheral. It shall not be used
// anywhere else in the module. // anywhere else in the module.
next_buffer: unsafe { Some(&mut ADC0_BUF1) }, next_buffer: unsafe { Some(&mut ADC_BUF[$index][1]) },
transfer: data_transfer, transfer: data_transfer,
_trigger_transfer: trigger_transfer, _trigger_transfer: trigger_transfer,
} }
} }
/// Handle a transfer completion. /// Obtain a buffer filled with ADC samples.
/// ///
/// # 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; SAMPLE_BUFFER_SIZE] { pub fn acquire_buffer(&mut self) -> &[u16; SAMPLE_BUFFER_SIZE] {
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.
// Note: If a device hangs up, check that this conditional is passing correctly, as there is // 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. // no time-out checks here in the interest of execution speed.
while !self.transfer.get_transfer_complete_flag() {} while !self.transfer.get_transfer_complete_flag() {}
let next_buffer = self.next_buffer.take().unwrap();
// Start the next transfer. // Start the next transfer.
self.transfer.clear_interrupts(); self.transfer.clear_interrupts();
let (prev_buffer, _) = let (prev_buffer, _) =
self.transfer.next_transfer(next_buffer).unwrap(); self.transfer.next_transfer(next_buffer).unwrap();
self.next_buffer.replace(prev_buffer); self.next_buffer.replace(prev_buffer); // .unwrap_none() https://github.com/rust-lang/rust/issues/62633
self.next_buffer.as_ref().unwrap() self.next_buffer.as_ref().unwrap()
} }
} }
};
/// Represents the data input stream from ADC1
pub struct Adc1Input {
next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
transfer: Transfer<
hal::dma::dma::Stream3<hal::stm32::DMA1>,
hal::spi::Spi<hal::stm32::SPI3, hal::spi::Disabled, u16>,
PeripheralToMemory,
&'static mut [u16; SAMPLE_BUFFER_SIZE],
>,
_trigger_transfer: Transfer<
hal::dma::dma::Stream2<hal::stm32::DMA1>,
SPI3,
MemoryToPeripheral,
&'static mut [u16; 1],
>,
} }
impl Adc1Input { adc_input!(Adc0Input, 0, Stream0, Stream1, SPI2, Channel1, TIM2_CH1);
/// Construct a new ADC1 input data stream. adc_input!(Adc1Input, 1, Stream2, Stream3, SPI3, Channel2, TIM2_CH2);
///
/// # 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.
/// * `trigger_channel` - The ADC sampling timer output compare channel for read triggers.
pub fn new(
spi: hal::spi::Spi<hal::stm32::SPI3, hal::spi::Enabled, u16>,
trigger_stream: hal::dma::dma::Stream2<hal::stm32::DMA1>,
data_stream: hal::dma::dma::Stream3<hal::stm32::DMA1>,
trigger_channel: sampling_timer::tim2::Channel2,
) -> 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.
let trigger_config = DmaConfig::default()
.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(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,
);
// 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);
// 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,
// 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,
);
data_transfer.start(|spi| {
// Allow the SPI FIFOs to operate using only DMA data channels.
spi.enable_dma_rx();
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());
});
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,
}
}
/// 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; SAMPLE_BUFFER_SIZE] {
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() {}
// 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()
}
}

View File

@ -11,29 +11,24 @@ use super::{
// The following global buffers are used for the DAC code DMA transfers. Two buffers are used for // 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 // 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 // processed). Note that the contents of AXI SRAM is uninitialized, so the buffer contents on
// startup are undefined. // startup are undefined. The dimensions are `ADC_BUF[adc_index][ping_pong_index][sample_index]`.
#[link_section = ".axisram.buffers"] #[link_section = ".axisram.buffers"]
static mut DAC0_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; static mut DAC_BUF: [[[u16; SAMPLE_BUFFER_SIZE]; 2]; 2] =
[[[0; SAMPLE_BUFFER_SIZE]; 2]; 2];
#[link_section = ".axisram.buffers"] macro_rules! dac_output {
static mut DAC0_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; ($name:ident, $index:literal, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
#[link_section = ".axisram.buffers"] /// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
static mut DAC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE]; struct $spi {
spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Disabled, u16>,
#[link_section = ".axisram.buffers"] _channel: sampling_timer::tim2::$trigger_channel,
static mut DAC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
/// SPI4 is used as a type for indicating a DMA transfer into the SPI4 TX FIFO
struct SPI4 {
spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Disabled, u16>,
_channel: sampling_timer::tim2::Channel3,
} }
impl SPI4 { impl $spi {
pub fn new( pub fn new(
_channel: sampling_timer::tim2::Channel3, _channel: sampling_timer::tim2::$trigger_channel,
spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Disabled, u16>, spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Disabled, u16>,
) -> Self { ) -> Self {
Self { _channel, spi } Self { _channel, spi }
} }
@ -42,111 +37,43 @@ impl SPI4 {
// Note(unsafe): This is safe because the DMA request line is logically owned by this module. // Note(unsafe): This is safe because the DMA request line is logically owned by this module.
// Additionally, the SPI is owned by this structure and is known to be configured for u16 word // Additionally, the SPI is owned by this structure and is known to be configured for u16 word
// sizes. // sizes.
unsafe impl TargetAddress<MemoryToPeripheral> for SPI4 { unsafe impl TargetAddress<MemoryToPeripheral> for $spi {
/// SPI2 is configured to operate using 16-bit transfer words. /// SPI is configured to operate using 16-bit transfer words.
type MemSize = u16; type MemSize = u16;
/// SPI4 DMA requests are generated whenever TIM2 CH3 comparison occurs. /// SPI DMA requests are generated whenever TIM2 CHx ($dma_req) comparison occurs.
const REQUEST_LINE: Option<u8> = Some(DMAReq::TIM2_CH3 as u8); const REQUEST_LINE: Option<u8> = Some(DMAReq::$dma_req as u8);
/// Whenever the DMA request occurs, it should write into SPI4's TX FIFO. /// Whenever the DMA request occurs, it should write into SPI's TX FIFO.
fn address(&self) -> u32 { fn address(&self) -> u32 {
&self.spi.inner().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 /// Represents data associated with DAC.
struct SPI5 { pub struct $name {
_channel: sampling_timer::tim2::Channel4,
spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
}
impl SPI5 {
pub fn new(
_channel: sampling_timer::tim2::Channel4,
spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
) -> Self {
Self { _channel, spi }
}
}
// Note(unsafe): This is safe because the DMA request line is logically owned by this module.
// Additionally, the SPI is owned by this structure and is known to be configured for u16 word
// sizes.
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 {
&self.spi.inner().txdr as *const _ as u32
}
}
/// Represents both DAC output channels.
pub struct DacOutputs {
dac0: Dac0Output,
dac1: Dac1Output,
}
impl DacOutputs {
/// Construct the DAC outputs.
pub fn new(dac0: Dac0Output, dac1: Dac1Output) -> Self {
Self { dac0, dac1 }
}
/// Borrow the next DAC output buffers to populate the DAC output codes in-place.
///
/// # 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,
) -> (
&mut [u16; SAMPLE_BUFFER_SIZE],
&mut [u16; SAMPLE_BUFFER_SIZE],
) {
(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();
}
}
/// Represents data associated with DAC0.
pub struct Dac0Output {
next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>, 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. // Note: SPI TX functionality may not be used from this structure to ensure safety with DMA.
transfer: Transfer< transfer: Transfer<
hal::dma::dma::Stream4<hal::stm32::DMA1>, hal::dma::dma::$data_stream<hal::stm32::DMA1>,
SPI4, $spi,
MemoryToPeripheral, MemoryToPeripheral,
&'static mut [u16; SAMPLE_BUFFER_SIZE], &'static mut [u16; SAMPLE_BUFFER_SIZE],
>, >,
first_transfer: bool, first_transfer: bool,
} }
impl Dac0Output { impl $name {
/// Construct the DAC0 output channel. /// Construct the DAC output channel.
/// ///
/// # Args /// # Args
/// * `spi` - The SPI interface used to communicate with the ADC. /// * `spi` - The SPI interface used to communicate with the ADC.
/// * `stream` - The DMA stream used to write DAC codes over SPI. /// * `stream` - The DMA stream used to write DAC codes over SPI.
/// * `trigger_channel` - The sampling timer output compare channel for update triggers. /// * `trigger_channel` - The sampling timer output compare channel for update triggers.
pub fn new( pub fn new(
spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>, spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Enabled, u16>,
stream: hal::dma::dma::Stream4<hal::stm32::DMA1>, stream: hal::dma::dma::$data_stream<hal::stm32::DMA1>,
trigger_channel: sampling_timer::tim2::Channel3, trigger_channel: sampling_timer::tim2::$trigger_channel,
) -> Self { ) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over) // Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs. // occurs.
@ -171,11 +98,12 @@ impl Dac0Output {
spi.inner().cr1.modify(|_, w| w.cstart().started()); spi.inner().cr1.modify(|_, w| w.cstart().started());
// Construct the trigger stream to write from memory to the peripheral. // Construct the trigger stream to write from memory to the peripheral.
let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init( let transfer: Transfer<_, _, MemoryToPeripheral, _> =
Transfer::init(
stream, stream,
SPI4::new(trigger_channel, spi), $spi::new(trigger_channel, spi),
// Note(unsafe): This buffer is only used once and provided for the DMA transfer. // Note(unsafe): This buffer is only used once and provided for the DMA transfer.
unsafe { &mut DAC0_BUF0 }, unsafe { &mut DAC_BUF[$index][0] },
None, None,
trigger_config, trigger_config,
); );
@ -183,23 +111,26 @@ impl Dac0Output {
Self { Self {
transfer, transfer,
// Note(unsafe): This buffer is only used once and provided for the next DMA transfer. // Note(unsafe): This buffer is only used once and provided for the next DMA transfer.
next_buffer: unsafe { Some(&mut DAC0_BUF1) }, next_buffer: unsafe { Some(&mut DAC_BUF[$index][1]) },
first_transfer: true, first_transfer: true,
} }
} }
/// Mutably borrow the next output buffer to populate it with DAC codes. /// Acquire the next output buffer to populate it with DAC codes.
pub fn prepare_buffer(&mut self) -> &mut [u16; SAMPLE_BUFFER_SIZE] { pub fn acquire_buffer(
self.next_buffer.as_mut().unwrap() &mut self,
) -> &'static mut [u16; SAMPLE_BUFFER_SIZE] {
self.next_buffer.take().unwrap()
} }
/// Enqueue the next buffer for transmission to the DAC. /// Enqueue the next buffer for transmission to the DAC.
/// ///
/// # Args /// # Args
/// * `data` - The next data to write to the DAC. /// * `data` - The next data to write to the DAC.
pub fn commit_buffer(&mut self) { pub fn release_buffer(
let next_buffer = self.next_buffer.take().unwrap(); &mut self,
next_buffer: &'static mut [u16; SAMPLE_BUFFER_SIZE],
) {
// If the last transfer was not complete, we didn't write all our previous DAC codes. // 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. // Wait for all the DAC codes to get written as well.
if self.first_transfer { if self.first_transfer {
@ -215,102 +146,12 @@ impl Dac0Output {
let (prev_buffer, _) = let (prev_buffer, _) =
self.transfer.next_transfer(next_buffer).unwrap(); self.transfer.next_transfer(next_buffer).unwrap();
// .unwrap_none() https://github.com/rust-lang/rust/issues/62633
self.next_buffer.replace(prev_buffer); self.next_buffer.replace(prev_buffer);
} }
} }
};
/// Represents the data output stream from DAC1.
pub struct Dac1Output {
next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
transfer: Transfer<
hal::dma::dma::Stream5<hal::stm32::DMA1>,
SPI5,
MemoryToPeripheral,
&'static mut [u16; SAMPLE_BUFFER_SIZE],
>,
first_transfer: bool,
} }
impl Dac1Output { dac_output!(Dac0Output, 0, Stream4, SPI4, Channel3, TIM2_CH3);
/// Construct a new DAC1 output data stream. dac_output!(Dac1Output, 1, Stream5, SPI5, Channel4, TIM2_CH4);
///
/// # 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<hal::stm32::SPI5, hal::spi::Enabled, u16>,
stream: hal::dma::dma::Stream5<hal::stm32::DMA1>,
trigger_channel: sampling_timer::tim2::Channel4,
) -> 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);
// 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());
// 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,
first_transfer: true,
}
}
/// 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 commit_buffer(&mut self) {
let next_buffer = self.next_buffer.take().unwrap();
// 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 {
// 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() {}
}
// 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

@ -72,8 +72,8 @@ mod pounder;
mod sampling_timer; mod sampling_timer;
mod server; mod server;
use adc::{Adc0Input, Adc1Input, AdcInputs}; use adc::{Adc0Input, Adc1Input};
use dac::{Dac0Output, Dac1Output, DacOutputs}; use dac::{Dac0Output, Dac1Output};
use dsp::iir; use dsp::iir;
#[cfg(not(feature = "semihosting"))] #[cfg(not(feature = "semihosting"))]
@ -190,11 +190,10 @@ macro_rules! route_request {
#[rtic::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)] #[rtic::app(device = stm32h7xx_hal::stm32, peripherals = true, monotonic = rtic::cyccnt::CYCCNT)]
const APP: () = { const APP: () = {
struct Resources { struct Resources {
afe0: AFE0, afes: (AFE0, AFE1),
afe1: AFE1,
adcs: AdcInputs, adcs: (Adc0Input, Adc1Input),
dacs: DacOutputs, dacs: (Dac0Output, Dac1Output),
eeprom_i2c: hal::i2c::I2c<hal::stm32::I2C2>, eeprom_i2c: hal::i2c::I2c<hal::stm32::I2C2>,
@ -361,7 +360,7 @@ const APP: () = {
) )
}; };
AdcInputs::new(adc0, adc1) (adc0, adc1)
}; };
let dacs = { let dacs = {
@ -446,7 +445,7 @@ const APP: () = {
dma_streams.5, dma_streams.5,
sampling_timer_channels.ch4, sampling_timer_channels.ch4,
); );
DacOutputs::new(dac0, dac1) (dac0, dac1)
}; };
let mut fp_led_0 = gpiod.pd5.into_push_pull_output(); let mut fp_led_0 = gpiod.pd5.into_push_pull_output();
@ -734,8 +733,7 @@ const APP: () = {
sampling_timer.start(); sampling_timer.start();
init::LateResources { init::LateResources {
afe0, afes: (afe0, afe1),
afe1,
adcs, adcs,
dacs, dacs,
@ -750,42 +748,34 @@ const APP: () = {
} }
#[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(c: adc_update::Context) { fn process(c: process::Context) {
let (adc0_samples, adc1_samples) = let adc_samples = [
c.resources.adcs.transfer_complete_handler(); c.resources.adcs.0.acquire_buffer(),
c.resources.adcs.1.acquire_buffer(),
];
let dac_samples = [
c.resources.dacs.0.acquire_buffer(),
c.resources.dacs.1.acquire_buffer(),
];
let (dac0, dac1) = c.resources.dacs.prepare_data(); for channel in 0..adc_samples.len() {
for sample in 0..adc_samples[0].len() {
for (i, (adc0, adc1)) in let x = f32::from(adc_samples[channel][sample] as i16);
adc0_samples.iter().zip(adc1_samples.iter()).enumerate() let y = c.resources.iir_ch[channel]
{ .update(&mut c.resources.iir_state[channel], x);
dac0[i] = {
let x0 = f32::from(*adc0 as i16);
let y0 = c.resources.iir_ch[0]
.update(&mut c.resources.iir_state[0], x0);
// Note(unsafe): The filter limits ensure that the value is in range. // Note(unsafe): The filter limits ensure that the value is in range.
// The truncation introduces 1/2 LSB distortion. // The truncation introduces 1/2 LSB distortion.
let y0 = unsafe { y0.to_int_unchecked::<i16>() }; let y = unsafe { y.to_int_unchecked::<i16>() };
// Convert to DAC code // Convert to DAC code
y0 as u16 ^ 0x8000 dac_samples[channel][sample] = y as u16 ^ 0x8000;
}; }
}
dac1[i] = { let [dac0, dac1] = dac_samples;
let x1 = f32::from(*adc1 as i16); c.resources.dacs.0.release_buffer(dac0);
let y1 = c.resources.iir_ch[1] c.resources.dacs.1.release_buffer(dac1);
.update(&mut c.resources.iir_state[1], x1);
// Note(unsafe): The filter limits ensure that the value is in range.
// The truncation introduces 1/2 LSB distortion.
let y1 = unsafe { y1.to_int_unchecked::<i16>() };
// Convert to DAC code
y1 as u16 ^ 0x8000
};
} }
c.resources.dacs.commit_data(); #[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afes])]
}
#[idle(resources=[net_interface, pounder, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])]
fn idle(mut c: idle::Context) -> ! { fn idle(mut c: idle::Context) -> ! {
let mut socket_set_entries: [_; 8] = Default::default(); let mut socket_set_entries: [_; 8] = Default::default();
let mut sockets = let mut sockets =
@ -845,8 +835,8 @@ const APP: () = {
Ok::<server::Status, ()>(state) Ok::<server::Status, ()>(state)
}), }),
"stabilizer/afe0/gain": (|| c.resources.afe0.get_gain()), "stabilizer/afe0/gain": (|| c.resources.afes.0.get_gain()),
"stabilizer/afe1/gain": (|| c.resources.afe1.get_gain()), "stabilizer/afe1/gain": (|| c.resources.afes.1.get_gain()),
"pounder/in0": (|| { "pounder/in0": (|| {
match c.resources.pounder { match c.resources.pounder {
Some(pounder) => Some(pounder) =>
@ -941,11 +931,11 @@ const APP: () = {
} }
}), }),
"stabilizer/afe0/gain": afe::Gain, (|gain| { "stabilizer/afe0/gain": afe::Gain, (|gain| {
c.resources.afe0.set_gain(gain); c.resources.afes.0.set_gain(gain);
Ok::<(), ()>(()) Ok::<(), ()>(())
}), }),
"stabilizer/afe1/gain": afe::Gain, (|gain| { "stabilizer/afe1/gain": afe::Gain, (|gain| {
c.resources.afe1.set_gain(gain); c.resources.afes.1.set_gain(gain);
Ok::<(), ()>(()) Ok::<(), ()>(())
}) })
] ]