Merge branch 'feature/dma-updates' into feature/qspi-stream

This commit is contained in:
Ryan Summers 2020-11-17 10:29:03 +01:00
commit 1c8e385e6d
12 changed files with 716 additions and 241 deletions

View File

@ -2,10 +2,9 @@ name: Continuous Integration
on: on:
push: push:
branches: branches: [master, staging, trying]
- staging pull_request:
- trying branches: [master]
- master
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always

74
Cargo.lock generated
View File

@ -344,37 +344,12 @@ dependencies = [
"cortex-m-semihosting", "cortex-m-semihosting",
] ]
[[package]]
name = "paste"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45ca20c77d80be666aef2b45486da86238fabe33e38306bd3118fe4af33fa880"
dependencies = [
"paste-impl",
"proc-macro-hack",
]
[[package]] [[package]]
name = "paste" name = "paste"
version = "1.0.2" version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba7ae1a2180ed02ddfdb5ab70c70d596a26dd642e097bb6fe78b1bde8588ed97" checksum = "ba7ae1a2180ed02ddfdb5ab70c70d596a26dd642e097bb6fe78b1bde8588ed97"
[[package]]
name = "paste-impl"
version = "0.1.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d95a7db200b97ef370c8e6de0088252f7e0dfff7d047a28528e47456c0fc98b6"
dependencies = [
"proc-macro-hack",
]
[[package]]
name = "proc-macro-hack"
version = "0.5.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.24" version = "1.0.24"
@ -478,7 +453,6 @@ checksum = "0fe46639fd2ec79eadf8fe719f237a7a0bd4dac5d957f1ca5bbdbc1c3c39e53a"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"byteorder", "byteorder",
"log",
"managed", "managed",
] ]
@ -503,8 +477,7 @@ dependencies = [
"serde", "serde",
"serde-json-core", "serde-json-core",
"smoltcp", "smoltcp",
"stm32h7-ethernet", "stm32h7xx-hal",
"stm32h7xx-hal 0.8.0",
] ]
[[package]] [[package]]
@ -513,17 +486,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]
name = "stm32h7"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9beb5e2a223c82f263c3051bba4614aebc6e98bd40217df3cd8817c83ac7bd8"
dependencies = [
"bare-metal 0.2.5",
"cortex-m",
"vcell",
]
[[package]] [[package]]
name = "stm32h7" name = "stm32h7"
version = "0.12.1" version = "0.12.1"
@ -536,38 +498,10 @@ dependencies = [
"vcell", "vcell",
] ]
[[package]]
name = "stm32h7-ethernet"
version = "0.1.1"
source = "git+https://github.com/quartiq/stm32h7-ethernet.git#cf9b8bb2e1b440d8ada6ac6048f48dc4ed9c269a"
dependencies = [
"cortex-m",
"log",
"smoltcp",
"stm32h7xx-hal 0.5.0",
]
[[package]]
name = "stm32h7xx-hal"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "987c66628f30012ed9a41cc738421c5caece03292c0cc8fd1e99956f122735bd"
dependencies = [
"bare-metal 0.2.5",
"cast",
"cortex-m",
"cortex-m-rt",
"embedded-hal",
"nb 0.1.3",
"paste 0.1.18",
"stm32h7 0.11.0",
"void",
]
[[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/stabilizer-dma#8516690d4f35bc4bb184eba2ee8b48d4490ec85b" 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",
@ -576,9 +510,9 @@ dependencies = [
"embedded-dma", "embedded-dma",
"embedded-hal", "embedded-hal",
"nb 1.0.0", "nb 1.0.0",
"paste 1.0.2", "paste",
"smoltcp", "smoltcp",
"stm32h7 0.12.1", "stm32h7",
"void", "void",
] ]

View File

@ -52,15 +52,10 @@ default-features = false
[dependencies.ad9959] [dependencies.ad9959]
path = "ad9959" path = "ad9959"
[dependencies.stm32h7-ethernet]
git = "https://github.com/quartiq/stm32h7-ethernet.git"
branch = "master"
features = ["stm32h743v"]
[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/stabilizer-dma" branch = "dma"
[features] [features]
semihosting = ["panic-semihosting", "cortex-m-log/semihosting"] semihosting = ["panic-semihosting", "cortex-m-log/semihosting"]
@ -70,7 +65,7 @@ nightly = ["cortex-m/inline-asm"]
[profile.dev] [profile.dev]
codegen-units = 1 codegen-units = 1
incremental = false incremental = false
opt-level = 1 opt-level = 3
[profile.release] [profile.release]
opt-level = 3 opt-level = 3

View File

@ -1 +1 @@
"1626aw5ln581s1jzsf74y0djh715hdsjxzd3ck0xnb84a6kd4hkw" "05b1xcr9jachnih0d6i63cfjcb88xrddmr2kf4h3vfwpjf8y9w10"

View File

@ -26,6 +26,3 @@ set var $t0=*$cc
continue continue
end end
#set var $t0=*$cc #set var $t0=*$cc
source ../../PyCortexMDebug/cmdebug/svd_gdb.py
svd_load ~/Downloads/STM32H743x.svd

View File

@ -1,27 +1,48 @@
///! 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::{ use super::{
hal, DMAReq, DmaConfig, MemoryToPeripheral, PeripheralToMemory, Priority, hal, sampling_timer, DMAReq, DmaConfig, MemoryToPeripheral,
Stream, TargetAddress, Transfer, PeripheralToMemory, Priority, TargetAddress, Transfer, SAMPLE_BUFFER_SIZE,
}; };
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"] #[link_section = ".axisram.buffers"]
static mut SPI_START: [u16; 1] = [0x00]; 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"] #[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
/// whenever the tim2 update dma request occurs.
struct SPI2 {} struct SPI2 {}
impl SPI2 { impl SPI2 {
pub fn new() -> Self { pub fn new() -> Self {
Self {} Self {}
@ -29,18 +50,23 @@ impl SPI2 {
} }
unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 { unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 {
/// SPI2 is configured to operate using 16-bit transfer words.
type MemSize = u16; type MemSize = u16;
const REQUEST_LINE: Option<u8> = Some(DMAReq::TIM2_UP as u8); /// SPI2 DMA requests are generated whenever TIM2 CH1 comparison occurs.
const REQUEST_LINE: Option<u8> = 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 { fn address(&self) -> u32 {
let regs = unsafe { &*hal::stm32::SPI2::ptr() }; let regs = unsafe { &*hal::stm32::SPI2::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
/// whenever the tim2 update dma request occurs.
struct SPI3 {} struct SPI3 {}
impl SPI3 { impl SPI3 {
pub fn new() -> Self { pub fn new() -> Self {
Self {} Self {}
@ -48,179 +74,285 @@ impl SPI3 {
} }
unsafe impl TargetAddress<MemoryToPeripheral> for SPI3 { unsafe impl TargetAddress<MemoryToPeripheral> for SPI3 {
/// SPI3 is configured to operate using 16-bit transfer words.
type MemSize = u16; type MemSize = u16;
const REQUEST_LINE: Option<u8> = Some(DMAReq::TIM2_UP as u8); /// 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 { fn address(&self) -> u32 {
let regs = unsafe { &*hal::stm32::SPI3::ptr() }; let regs = unsafe { &*hal::stm32::SPI3::ptr() };
&regs.txdr as *const _ as u32 &regs.txdr as *const _ as u32
} }
} }
/// Represents both ADC input channels.
pub struct AdcInputs { pub struct AdcInputs {
adc0: Adc0Input, adc0: Adc0Input,
adc1: Adc1Input, adc1: Adc1Input,
} }
impl AdcInputs { impl AdcInputs {
/// Construct the ADC inputs.
pub fn new(adc0: Adc0Input, adc1: Adc1Input) -> Self { pub fn new(adc0: Adc0Input, adc1: Adc1Input) -> Self {
Self { adc0, adc1 } 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( 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)
} }
} }
/// 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<
hal::dma::dma::Stream0<hal::stm32::DMA1>,
SPI2,
MemoryToPeripheral,
&'static mut [u16; 1],
>, >,
} }
impl Adc0Input { 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.
/// * `_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::SPI2, hal::spi::Enabled, u16>,
trigger_stream: hal::dma::dma::Stream0<hal::stm32::DMA1>, trigger_stream: hal::dma::dma::Stream0<hal::stm32::DMA1>,
data_stream: hal::dma::dma::Stream1<hal::stm32::DMA1>, data_stream: hal::dma::dma::Stream1<hal::stm32::DMA1>,
trigger_channel: sampling_timer::Timer2Channel1,
) -> Self { ) -> 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() let trigger_config = DmaConfig::default()
.memory_increment(false) .memory_increment(false)
.peripheral_increment(false) .peripheral_increment(false)
.priority(Priority::High) .priority(Priority::High)
.circular_buffer(true); .circular_buffer(true);
// Construct the trigger stream to write from memory to the peripheral.
let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> =
Transfer::init( Transfer::init(
trigger_stream, trigger_stream,
&SPI2::new(), SPI2::new(),
unsafe { &mut SPI_START }, unsafe { &mut SPI_START },
None, None,
trigger_config, 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() let data_config = DmaConfig::default()
.memory_increment(true) .memory_increment(true)
.priority(Priority::VeryHigh) .priority(Priority::VeryHigh)
.peripheral_increment(false); .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(); let mut spi = spi.disable();
spi.listen(hal::spi::Event::Error); 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, _> = let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> =
Transfer::init( Transfer::init(
data_stream, data_stream,
&spi, spi,
unsafe { &mut ADC0_BUF0 }, unsafe { &mut ADC0_BUF0 },
None, None,
data_config, data_config,
); );
data_transfer.start(|spi| {
// Allow the SPI FIFOs to operate using only DMA data channels.
spi.enable_dma_rx(); spi.enable_dma_rx();
spi.enable_dma_tx(); spi.enable_dma_tx();
let spi = spi.enable(); // 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()); spi.inner().cr1.modify(|_, w| w.cstart().started());
});
data_transfer.start(); trigger_transfer.start(|_| {});
trigger_transfer.start();
Self { Self {
next_buffer: unsafe { Some(&mut ADC0_BUF1) }, next_buffer: unsafe { Some(&mut ADC0_BUF1) },
transfer: data_transfer, transfer: data_transfer,
_trigger_transfer: trigger_transfer,
} }
} }
pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { /// 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(); let next_buffer = self.next_buffer.take().unwrap();
while hal::dma::dma::Stream1::<hal::stm32::DMA1>::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(); 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);
self.next_buffer.as_ref().unwrap() self.next_buffer.as_ref().unwrap()
} }
} }
/// 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<
hal::dma::dma::Stream2<hal::stm32::DMA1>,
SPI3,
MemoryToPeripheral,
&'static mut [u16; 1],
>, >,
} }
impl Adc1Input { 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.
/// * `trigger_channel` - The ADC sampling timer output compare channel for read triggers.
pub fn new( pub fn new(
spi: hal::spi::Spi<hal::stm32::SPI3, hal::spi::Enabled, u16>, spi: hal::spi::Spi<hal::stm32::SPI3, hal::spi::Enabled, u16>,
trigger_stream: hal::dma::dma::Stream2<hal::stm32::DMA1>, trigger_stream: hal::dma::dma::Stream2<hal::stm32::DMA1>,
data_stream: hal::dma::dma::Stream3<hal::stm32::DMA1>, data_stream: hal::dma::dma::Stream3<hal::stm32::DMA1>,
trigger_channel: sampling_timer::Timer2Channel2,
) -> Self { ) -> 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() let trigger_config = DmaConfig::default()
.memory_increment(false) .memory_increment(false)
.peripheral_increment(false) .peripheral_increment(false)
.priority(Priority::High) .priority(Priority::High)
.circular_buffer(true); .circular_buffer(true);
// Construct the trigger stream to write from memory to the peripheral.
let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> = let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> =
Transfer::init( Transfer::init(
trigger_stream, trigger_stream,
&SPI3::new(), SPI3::new(),
unsafe { &mut SPI_START }, unsafe { &mut SPI_START },
None, None,
trigger_config, 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() let data_config = DmaConfig::default()
.memory_increment(true) .memory_increment(true)
.transfer_complete_interrupt(true) .transfer_complete_interrupt(true)
.priority(Priority::VeryHigh) .priority(Priority::VeryHigh)
.peripheral_increment(false); .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(); let mut spi = spi.disable();
spi.listen(hal::spi::Event::Error); 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, _> = let mut data_transfer: Transfer<_, _, PeripheralToMemory, _> =
Transfer::init( Transfer::init(
data_stream, data_stream,
&spi, spi,
unsafe { &mut ADC1_BUF0 }, unsafe { &mut ADC1_BUF0 },
None, None,
data_config, data_config,
); );
data_transfer.start(|spi| {
// Allow the SPI FIFOs to operate using only DMA data channels.
spi.enable_dma_rx(); spi.enable_dma_rx();
spi.enable_dma_tx(); spi.enable_dma_tx();
let spi = spi.enable(); // 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()); spi.inner().cr1.modify(|_, w| w.cstart().started());
});
data_transfer.start(); trigger_transfer.start(|_| {});
trigger_transfer.start();
Self { Self {
next_buffer: unsafe { Some(&mut ADC1_BUF1) }, next_buffer: unsafe { Some(&mut ADC1_BUF1) },
transfer: data_transfer, transfer: data_transfer,
_trigger_transfer: trigger_transfer,
} }
} }
pub fn transfer_complete_handler(&mut self) -> &[u16; INPUT_BUFFER_SIZE] { /// 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(); let next_buffer = self.next_buffer.take().unwrap();
while hal::dma::dma::Stream3::<hal::stm32::DMA1>::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(); 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);
self.next_buffer.as_ref().unwrap() self.next_buffer.as_ref().unwrap()
} }

View File

@ -1,62 +1,279 @@
use super::hal; ///! Stabilizer DAC management interface
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,
};
// 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,
outputs: heapless::spsc::Queue<(u16, u16), consts::U32>,
timer: hal::timer::Timer<hal::stm32::TIM3>,
} }
impl DacOutputs { impl DacOutputs {
/// 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<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(
dac0_spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>, spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>,
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 {
dac0_spi.inner().cr1.modify(|_, w| w.cstart().started()); // Generate DMA events when an output compare of the timer hitting zero (timer roll over)
dac1_spi.inner().cr1.modify(|_, w| w.cstart().started()); // occurs.
timer.pause(); trigger_channel.listen_dma();
timer.reset_counter(); trigger_channel.to_output_compare(0);
timer.clear_irq();
timer.listen(hal::timer::Event::TimeOut); // The stream constantly writes to the TX FIFO to write new update codes.
let trigger_config = DmaConfig::default()
.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(),
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 { Self {
dac0_spi, transfer,
dac1_spi, next_buffer: unsafe { Some(&mut DAC0_BUF1) },
outputs: heapless::spsc::Queue::new(), _spi: spi,
timer, first_transfer: true,
} }
} }
pub fn push(&mut self, dac0_value: u16, dac1_value: u16) { /// Schedule the next set of DAC update codes.
self.outputs.enqueue((dac0_value, dac1_value)).unwrap(); ///
self.timer.resume(); /// # Args
/// * `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 {}
} }
pub fn update(&mut self) { // Start the next transfer.
self.timer.clear_irq(); self.transfer.clear_interrupts();
match self.outputs.dequeue() { let (prev_buffer, _) =
Some((dac0, dac1)) => self.write(dac0, dac1), self.transfer.next_transfer(next_buffer).unwrap();
None => {
self.timer.pause(); self.next_buffer.replace(prev_buffer);
self.timer.reset_counter();
self.timer.clear_irq();
} }
};
} }
pub fn write(&mut self, dac0_value: u16, dac1_value: u16) { /// Represents the data output stream from DAC1.
unsafe { pub struct Dac1Output {
core::ptr::write_volatile( next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
&self.dac0_spi.inner().txdr as *const _ as *mut u16, _spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
dac0_value, 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
/// * `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::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,
); );
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

@ -47,7 +47,8 @@ impl HighResTimerE {
let minimum_duration = set_duration + set_offset; let minimum_duration = set_duration + set_offset;
let source_frequency: u32 = self.clocks.timy_ker_ck().0; let source_frequency: u32 = self.clocks.timy_ker_ck().0;
let source_cycles = (minimum_duration * source_frequency as f32) as u32 + 1; let source_cycles =
(minimum_duration * source_frequency as f32) as u32 + 1;
// Determine the clock divider, which may be 1, 2, or 4. We will choose a clock divider that // Determine the clock divider, which may be 1, 2, or 4. We will choose a clock divider that
// allows us the highest resolution per tick, so lower dividers are favored. // allows us the highest resolution per tick, so lower dividers are favored.
@ -92,7 +93,6 @@ impl HighResTimerE {
} }
} }
// Enable the timer now that it is configured. // Enable the timer now that it is configured.
self.master.mcr.modify(|_, w| w.tecen().set_bit()); self.master.mcr.modify(|_, w| w.tecen().set_bit());
} }

View File

@ -105,14 +105,4 @@ impl IIR {
xy[xy.len() / 2] = y0; xy[xy.len() / 2] = y0;
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
}
} }

View File

@ -1,3 +1,4 @@
#![deny(warnings)]
#![allow(clippy::missing_safety_doc)] #![allow(clippy::missing_safety_doc)]
#![no_std] #![no_std]
#![no_main] #![no_main]
@ -38,17 +39,24 @@ use hal::{
dma::{ dma::{
config::Priority, config::Priority,
dma::{DMAReq, DmaConfig}, dma::{DMAReq, DmaConfig},
traits::{Stream, TargetAddress}, traits::TargetAddress,
MemoryToPeripheral, PeripheralToMemory, Transfer, MemoryToPeripheral, PeripheralToMemory, Transfer,
}, },
ethernet::{self, PHY}, ethernet::{self, PHY},
}; };
use smoltcp as net; use smoltcp as net;
use smoltcp::iface::Routes;
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();
@ -59,10 +67,12 @@ mod eeprom;
mod hrtimer; mod hrtimer;
mod iir; mod iir;
mod pounder; mod pounder;
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};
use pounder::DdsOutput;
#[cfg(not(feature = "semihosting"))] #[cfg(not(feature = "semihosting"))]
fn init_log() {} fn init_log() {}
@ -91,6 +101,7 @@ mod build_info {
pub struct NetStorage { pub struct NetStorage {
ip_addrs: [net::wire::IpCidr; 1], ip_addrs: [net::wire::IpCidr; 1],
neighbor_cache: [Option<(net::wire::IpAddress, net::iface::Neighbor)>; 8], neighbor_cache: [Option<(net::wire::IpAddress, net::iface::Neighbor)>; 8],
routes_storage: [Option<(smoltcp::wire::IpCidr, smoltcp::iface::Route)>; 1],
} }
static mut NET_STORE: NetStorage = NetStorage { static mut NET_STORE: NetStorage = NetStorage {
@ -100,6 +111,8 @@ static mut NET_STORE: NetStorage = NetStorage {
)], )],
neighbor_cache: [None; 8], neighbor_cache: [None; 8],
routes_storage: [None; 1],
}; };
const SCALE: f32 = ((1 << 15) - 1) as f32; const SCALE: f32 = ((1 << 15) - 1) as f32;
@ -181,9 +194,7 @@ const APP: () = {
eeprom_i2c: hal::i2c::I2c<hal::stm32::I2C2>, eeprom_i2c: hal::i2c::I2c<hal::stm32::I2C2>,
timer: hal::timer::Timer<hal::stm32::TIM2>, dds_output: DdsOutput,
profiles: heapless::spsc::Queue<[u32; 4], heapless::consts::U32>,
// Note: It appears that rustfmt generates a format that GDB cannot recognize, which // Note: It appears that rustfmt generates a format that GDB cannot recognize, which
// results in GDB breakpoints being set improperly. // results in GDB breakpoints being set improperly.
@ -260,6 +271,16 @@ const APP: () = {
let dma_streams = let dma_streams =
hal::dma::dma::StreamsTuple::new(dp.DMA1, ccdr.peripheral.DMA1); 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. // Configure the SPI interfaces to the ADCs and DACs.
let adcs = { let adcs = {
let adc0 = { let adc0 = {
@ -292,7 +313,12 @@ const APP: () = {
&ccdr.clocks, &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 = { let adc1 = {
@ -325,7 +351,12 @@ const APP: () = {
&ccdr.clocks, &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) AdcInputs::new(adc0, adc1)
@ -403,13 +434,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();
@ -471,9 +506,7 @@ const APP: () = {
}; };
let mut reset_pin = gpioa.pa0.into_push_pull_output(); let mut reset_pin = gpioa.pa0.into_push_pull_output();
let mut io_update = gpiog let mut io_update = gpiog.pg7.into_push_pull_output();
.pg7
.into_push_pull_output();
let ad9959 = ad9959::Ad9959::new( let ad9959 = ad9959::Ad9959::new(
qspi_interface, qspi_interface,
@ -702,6 +735,10 @@ const APP: () = {
24, 24,
); );
let default_v4_gw = Ipv4Address::new(10, 0, 16, 1);
let mut routes = Routes::new(&mut store.routes_storage[..]);
routes.add_default_ipv4_route(default_v4_gw).unwrap();
let neighbor_cache = let neighbor_cache =
net::iface::NeighborCache::new(&mut store.neighbor_cache[..]); net::iface::NeighborCache::new(&mut store.neighbor_cache[..]);
@ -709,6 +746,7 @@ const APP: () = {
.ethernet_addr(mac_addr) .ethernet_addr(mac_addr)
.neighbor_cache(neighbor_cache) .neighbor_cache(neighbor_cache)
.ip_addrs(&mut store.ip_addrs[..]) .ip_addrs(&mut store.ip_addrs[..])
.routes(routes)
.finalize(); .finalize();
(interface, lan8742a) (interface, lan8742a)
@ -724,16 +762,18 @@ const APP: () = {
// Utilize the cycle counter for RTIC scheduling. // Utilize the cycle counter for RTIC scheduling.
cp.DWT.enable_cycle_counter(); cp.DWT.enable_cycle_counter();
// Configure timer 2 to trigger conversions for the ADC let dds_output = {
let timer2 = dp.TIM2.timer( let timer3 = dp.TIM3.timer(
SAMPLE_FREQUENCY_KHZ.khz(), SAMPLE_FREQUENCY_KHZ.khz(),
ccdr.peripheral.TIM2, ccdr.peripheral.TIM3,
&ccdr.clocks, &ccdr.clocks,
); );
{
let t2_regs = unsafe { &*hal::stm32::TIM2::ptr() }; DdsOutput::new(timer3)
t2_regs.dier.modify(|_, w| w.ude().set_bit()); };
}
// Start sampling ADCs.
sampling_timer.start();
init::LateResources { init::LateResources {
afe0: afe0, afe0: afe0,
@ -741,61 +781,72 @@ const APP: () = {
adcs, adcs,
dacs, dacs,
dds_output,
timer: timer2,
pounder: pounder_devices, pounder: pounder_devices,
eeprom_i2c, eeprom_i2c,
net_interface: network_interface, net_interface: network_interface,
eth_mac, eth_mac,
mac_addr, mac_addr,
profiles: heapless::spsc::Queue::new(),
} }
} }
#[task(binds = TIM3, resources=[dacs, profiles, pounder], priority = 3)] #[task(binds = TIM3, resources=[dds_output, pounder], priority = 3)]
fn dac_update(c: dac_update::Context) { fn dds_update(c: dds_update::Context) {
c.resources.dacs.update();
if let Some(pounder) = c.resources.pounder { if let Some(pounder) = c.resources.pounder {
if let Some(profile) = c.resources.profiles.dequeue() { if let Some(profile) = c.resources.dds_output.update_handler() {
pounder.ad9959.interface.write_profile(profile).unwrap(); pounder.ad9959.interface.write_profile(profile).unwrap();
pounder.io_update_trigger.trigger(); pounder.io_update_trigger.trigger();
} }
} }
} }
#[task(binds=DMA1_STR3, resources=[adcs, dacs, pounder, profiles, iir_state, iir_ch], priority=2)] #[task(binds=DMA1_STR3, resources=[adcs, dacs, pounder, dds_output, iir_state, iir_ch], priority=2)]
fn adc_update(mut c: adc_update::Context) { fn adc_update(mut 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 = c.resources.iir_ch[0] let mut dac1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
.update_from_adc_sample(*adc0, &mut c.resources.iir_state[0]);
let result_adc1 = c.resources.iir_ch[1] for (i, (adc0, adc1)) in
.update_from_adc_sample(*adc1, &mut c.resources.iir_state[1]); 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
};
c.resources dac1[i] = {
.dacs let x1 = f32::from(*adc1 as i16);
.lock(|dacs| dacs.push(result_adc0, result_adc1)); let y1 = c.resources.iir_ch[1]
.update(&mut c.resources.iir_state[1], x1);
y1 as i16 as u16 ^ 0x8000
};
let profiles = &mut c.resources.profiles; let dds_output = &mut c.resources.dds_output;
c.resources.pounder.lock(|pounder| { c.resources.pounder.lock(|pounder| {
if let Some(pounder) = pounder { if let Some(pounder) = pounder {
profiles.lock(|profiles| { dds_output.lock(|dds_output| {
let profile = pounder.ad9959.serialize_profile(pounder::Channel::Out0.into(), let profile = pounder
.ad9959
.serialize_profile(
pounder::Channel::Out0.into(),
100_000_000_f32, 100_000_000_f32,
0.0_f32, 0.0_f32,
*adc0 as f32 / 0xFFFF as f32).unwrap(); *adc0 as f32 / 0xFFFF as f32,
)
.unwrap();
dds_output.push(profile);
});
}
});
}
profiles.enqueue(profile).unwrap(); 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])]
@ -982,6 +1033,16 @@ const APP: () = {
panic!("ADC0 input overrun"); 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" { extern "C" {
// hw interrupt handlers for RTIC to use for scheduling tasks // hw interrupt handlers for RTIC to use for scheduling tasks
// one per priority // one per priority

View File

@ -1,8 +1,11 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
mod attenuators; mod attenuators;
mod dds_output;
mod rf_power; mod rf_power;
pub use dds_output::DdsOutput;
use super::hal; use super::hal;
use super::hrtimer::HighResTimerE; use super::hrtimer::HighResTimerE;
@ -124,9 +127,9 @@ impl QspiInterface {
unsafe { unsafe {
qspi_regs.dlr.write(|w| w.dl().bits(0xFFFF_FFFF)); qspi_regs.dlr.write(|w| w.dl().bits(0xFFFF_FFFF));
qspi_regs qspi_regs.ccr.modify(|_, w| {
.ccr w.imode().bits(0).fmode().bits(0).admode().bits(0)
.modify(|_, w| w.imode().bits(0).fmode().bits(0).admode().bits(0)); });
} }
self.streaming = true; self.streaming = true;

147
src/sampling_timer.rs Normal file
View File

@ -0,0 +1,147 @@
///! 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<hal::stm32::TIM2>,
channels: Option<TimerChannels>,
}
impl SamplingTimer {
/// Construct the sampling timer.
pub fn new(mut timer: hal::timer::Timer<hal::stm32::TIM2>) -> 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 {}
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) });
}
}