Merge branch 'master' into feature/qspi-stream

This commit is contained in:
Ryan Summers 2020-12-02 14:13:53 +01:00
commit 01a169ca69
19 changed files with 570 additions and 395 deletions

View File

@ -17,7 +17,7 @@ jobs:
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
toolchain: nightly
override: true
components: rustfmt
- name: cargo fmt --check
@ -33,15 +33,14 @@ jobs:
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
toolchain: nightly
target: thumbv7em-none-eabihf
override: true
components: clippy
- name: cargo clippy
uses: actions-rs/cargo@v1
- uses: actions-rs/clippy-check@v1
continue-on-error: true
with:
command: clippy
token: ${{ secrets.GITHUB_TOKEN }}
compile:
runs-on: ubuntu-latest

17
Cargo.lock generated
View File

@ -185,6 +185,13 @@ dependencies = [
"cortex-m",
]
[[package]]
name = "dsp"
version = "0.1.0"
dependencies = [
"serde",
]
[[package]]
name = "embedded-dma"
version = "0.1.2"
@ -336,9 +343,9 @@ checksum = "de96540e0ebde571dc55c73d60ef407c653844e6f9a1e2fdbd40c07b9252d812"
[[package]]
name = "panic-semihosting"
version = "0.5.4"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aed16eb761d0ee9161dd1319cb38c8007813b20f9720a5a682b283e7b8cdfe58"
checksum = "c3d55dedd501dfd02514646e0af4d7016ce36bc12ae177ef52056989966a1eec"
dependencies = [
"cortex-m",
"cortex-m-semihosting",
@ -346,9 +353,9 @@ dependencies = [
[[package]]
name = "paste"
version = "1.0.2"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba7ae1a2180ed02ddfdb5ab70c70d596a26dd642e097bb6fe78b1bde8588ed97"
checksum = "7151b083b0664ed58ed669fcdd92f01c3d2fdbf10af4931a301474950b52bfa9"
[[package]]
name = "proc-macro2"
@ -466,6 +473,7 @@ dependencies = [
"cortex-m-log",
"cortex-m-rt",
"cortex-m-rtic",
"dsp",
"embedded-hal",
"enum-iterator",
"heapless",
@ -474,6 +482,7 @@ dependencies = [
"nb 1.0.0",
"panic-halt",
"panic-semihosting",
"paste",
"serde",
"serde-json-core",
"smoltcp",

View File

@ -40,6 +40,8 @@ embedded-hal = "0.2.4"
nb = "1.0.0"
asm-delay = "0.9.0"
enum-iterator = "0.6.0"
paste = "1"
dsp = { path = "dsp" }
[dependencies.mcp23017]
git = "https://github.com/mrd0ll4r/mcp23017.git"

View File

@ -1,4 +1,4 @@
![Continuous Integration](https://github.com/quartiq/stabilizer/workflows/Continuous%20Integration/badge.svg)
[![QUARTIQ Matrix Chat](https://img.shields.io/matrix/quartiq:matrix.org)](https://matrix.to/#/#quartiq:matrix.org)
# Stabilizer Firmware

View File

@ -117,46 +117,42 @@ impl<I: Interface> Ad9959<I> {
communication_mode: desired_mode,
};
// Reset the AD9959
reset_pin.set_high().or_else(|_| Err(Error::Pin))?;
io_update.set_low().or(Err(Error::Pin))?;
io_update.set_low().or_else(|_| Err(Error::Pin))?;
// Reset the AD9959
reset_pin.set_high().or(Err(Error::Pin))?;
io_update.set_low().or(Err(Error::Pin))?;
// Delay for a clock cycle to allow the device to reset.
delay.delay_ms((1000.0 / clock_frequency as f32) as u8);
reset_pin.set_low().or_else(|_| Err(Error::Pin))?;
reset_pin.set_low().or(Err(Error::Pin))?;
ad9959
.interface
.configure_mode(Mode::SingleBitTwoWire)
.map_err(|_| Error::Interface)?;
.or(Err(Error::Interface))?;
// Program the interface configuration in the AD9959. Default to all channels enabled.
let mut csr: [u8; 1] = [0xF0];
csr[0].set_bits(1..3, desired_mode as u8);
ad9959
.interface
.write(Register::CSR as u8, &csr)
.map_err(|_| Error::Interface)?;
ad9959.write(Register::CSR, &csr)?;
// Latch the new interface configuration.
io_update.set_high().or_else(|_| Err(Error::Pin))?;
io_update.set_high().or(Err(Error::Pin))?;
// Delay for a clock cycle to allow the device to reset.
delay.delay_ms(2 * (1000.0 / clock_frequency as f32) as u8);
io_update.set_low().or_else(|_| Err(Error::Pin))?;
io_update.set_low().or(Err(Error::Pin))?;
ad9959
.interface
.configure_mode(desired_mode)
.map_err(|_| Error::Interface)?;
.or(Err(Error::Interface))?;
// Read back the CSR to ensure it specifies the mode correctly.
let mut updated_csr: [u8; 1] = [0];
ad9959
.interface
.read(Register::CSR as u8, &mut updated_csr)
.map_err(|_| Error::Interface)?;
ad9959.read(Register::CSR, &mut updated_csr)?;
if updated_csr[0] != csr[0] {
return Err(Error::Check);
}
@ -166,6 +162,18 @@ impl<I: Interface> Ad9959<I> {
Ok(ad9959)
}
fn read(&mut self, reg: Register, data: &mut [u8]) -> Result<(), Error> {
self.interface
.read(reg as u8, data)
.or(Err(Error::Interface))
}
fn write(&mut self, reg: Register, data: &[u8]) -> Result<(), Error> {
self.interface
.write(reg as u8, data)
.or(Err(Error::Interface))
}
/// Configure the internal system clock of the chip.
///
/// Arguments:
@ -181,7 +189,7 @@ impl<I: Interface> Ad9959<I> {
) -> Result<f32, Error> {
self.reference_clock_frequency = reference_clock_frequency;
if multiplier != 1 && (multiplier > 20 || multiplier < 4) {
if multiplier != 1 && !(4..=20).contains(&multiplier) {
return Err(Error::Bounds);
}
@ -193,17 +201,13 @@ impl<I: Interface> Ad9959<I> {
// TODO: Update / disable any enabled channels?
let mut fr1: [u8; 3] = [0, 0, 0];
self.interface
.read(Register::FR1 as u8, &mut fr1)
.map_err(|_| Error::Interface)?;
self.read(Register::FR1, &mut fr1)?;
fr1[0].set_bits(2..=6, multiplier);
let vco_range = frequency > 255e6;
fr1[0].set_bit(7, vco_range);
self.interface
.write(Register::FR1 as u8, &fr1)
.map_err(|_| Error::Interface)?;
self.write(Register::FR1, &fr1)?;
self.system_clock_multiplier = multiplier;
Ok(self.system_clock_frequency())
@ -217,9 +221,7 @@ impl<I: Interface> Ad9959<I> {
/// Get the current reference clock multiplier.
pub fn get_reference_clock_multiplier(&mut self) -> Result<u8, Error> {
let mut fr1: [u8; 3] = [0, 0, 0];
self.interface
.read(Register::FR1 as u8, &mut fr1)
.map_err(|_| Error::Interface)?;
self.read(Register::FR1, &mut fr1)?;
Ok(fr1[0].get_bits(2..=6) as u8)
}
@ -233,46 +235,34 @@ impl<I: Interface> Ad9959<I> {
/// True if the self test succeeded. False otherwise.
pub fn self_test(&mut self) -> Result<bool, Error> {
let mut csr: [u8; 1] = [0];
self.interface
.read(Register::CSR as u8, &mut csr)
.map_err(|_| Error::Interface)?;
self.read(Register::CSR, &mut csr)?;
let old_csr = csr[0];
// Enable all channels.
csr[0].set_bits(4..8, 0xF);
self.interface
.write(Register::CSR as u8, &csr)
.map_err(|_| Error::Interface)?;
self.write(Register::CSR, &csr)?;
// Read back the enable.
csr[0] = 0;
self.interface
.read(Register::CSR as u8, &mut csr)
.map_err(|_| Error::Interface)?;
self.read(Register::CSR, &mut csr)?;
if csr[0].get_bits(4..8) != 0xF {
return Ok(false);
}
// Clear all channel enables.
csr[0].set_bits(4..8, 0x0);
self.interface
.write(Register::CSR as u8, &csr)
.map_err(|_| Error::Interface)?;
self.write(Register::CSR, &csr)?;
// Read back the enable.
csr[0] = 0xFF;
self.interface
.read(Register::CSR as u8, &mut csr)
.map_err(|_| Error::Interface)?;
self.read(Register::CSR, &mut csr)?;
if csr[0].get_bits(4..8) != 0 {
return Ok(false);
}
// Restore the CSR.
csr[0] = old_csr;
self.interface
.write(Register::CSR as u8, &csr)
.map_err(|_| Error::Interface)?;
self.write(Register::CSR, &csr)?;
Ok(true)
}
@ -305,9 +295,7 @@ impl<I: Interface> Ad9959<I> {
.write(Register::CSR as u8, &[csr])
.map_err(|_| Error::Interface)?;
self.interface
.write(register as u8, &data)
.map_err(|_| Error::Interface)?;
self.write(register, &data)?;
Ok(())
}
@ -327,27 +315,18 @@ impl<I: Interface> Ad9959<I> {
// Disable all other channels in the CSR so that we can read the configuration register of
// only the desired channel.
let mut csr: [u8; 1] = [0];
self.interface
.read(Register::CSR as u8, &mut csr)
.map_err(|_| Error::Interface)?;
self.read(Register::CSR, &mut csr)?;
let mut new_csr = csr;
new_csr[0].set_bits(4..8, 0);
new_csr[0].set_bit(4 + channel as usize, true);
self.interface
.write(Register::CSR as u8, &new_csr)
.map_err(|_| Error::Interface)?;
self.interface
.read(register as u8, &mut data)
.map_err(|_| Error::Interface)?;
self.write(Register::CSR, &new_csr)?;
self.read(register, &mut data)?;
// Restore the previous CSR. Note that the re-enable of the channel happens immediately, so
// the CSR update does not need to be latched.
self.interface
.write(Register::CSR as u8, &csr)
.map_err(|_| Error::Interface)?;
self.write(Register::CSR, &csr)?;
Ok(())
}
@ -406,7 +385,7 @@ impl<I: Interface> Ad9959<I> {
channel: Channel,
amplitude: f32,
) -> Result<f32, Error> {
if amplitude < 0.0 || amplitude > 1.0 {
if !(0.0..=1.0).contains(&amplitude) {
return Err(Error::Bounds);
}

63
dsp/Cargo.lock generated Normal file
View File

@ -0,0 +1,63 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "dsp"
version = "0.1.0"
dependencies = [
"serde",
]
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
version = "1.0.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "443b4178719c5a851e1bde36ce12da21d74a0e60b4d982ec3385a933c812f0f6"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"

8
dsp/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "dsp"
version = "0.1.0"
authors = ["Robert Jördens <rj@quartiq.de>"]
edition = "2018"
[dependencies]
serde = { version = "1.0", features = ["derive"], default-features = false }

176
dsp/src/iir.rs Normal file
View File

@ -0,0 +1,176 @@
use core::ops::{Add, Mul};
use serde::{Deserialize, Serialize};
use core::f32;
// These are implemented here because core::f32 doesn't have them (yet).
// They are naive and don't handle inf/nan.
// `compiler-intrinsics`/llvm should have better (robust, universal, and
// faster) implementations.
fn abs(x: f32) -> f32 {
if x >= 0. {
x
} else {
-x
}
}
fn copysign(x: f32, y: f32) -> f32 {
if (x >= 0. && y >= 0.) || (x <= 0. && y <= 0.) {
x
} else {
-x
}
}
fn max(x: f32, y: f32) -> f32 {
if x > y {
x
} else {
y
}
}
fn min(x: f32, y: f32) -> f32 {
if x < y {
x
} else {
y
}
}
// Multiply-accumulate vectors `x` and `a`.
//
// A.k.a. dot product.
// Rust/LLVM optimize this nicely.
fn macc<T>(y0: T, x: &[T], a: &[T]) -> T
where
T: Add<Output = T> + Mul<Output = T> + Copy,
{
x.iter()
.zip(a)
.map(|(&x, &a)| x * a)
.fold(y0, |y, xa| y + xa)
}
/// IIR state and coefficients type.
///
/// To represent the IIR state (input and output memory) during the filter update
/// this contains the three inputs (x0, x1, x2) and the two outputs (y1, y2)
/// concatenated.
/// To represent the IIR coefficients, this contains the feed-forward
/// coefficients (b0, b1, b2) followd by the feed-back coefficients (a1, a2),
/// all normalized such that a0 = 1.
pub type IIRState = [f32; 5];
/// IIR configuration.
///
/// Contains the coeeficients `ba`, the output offset `y_offset`, and the
/// output limits `y_min` and `y_max`.
///
/// This implementation achieves several important properties:
///
/// * Its transfer function is universal in the sense that any biquadratic
/// transfer function can be implemented (high-passes, gain limits, second
/// order integrators with inherent anti-windup, notches etc) without code
/// changes preserving all features.
/// * It inherits a universal implementation of "integrator anti-windup", also
/// and especially in the presence of set-point changes and in the presence
/// of proportional or derivative gain without any back-off that would reduce
/// steady-state output range.
/// * It has universal derivative-kick (undesired, unlimited, and un-physical
/// amplification of set-point changes by the derivative term) avoidance.
/// * An offset at the input of an IIR filter (a.k.a. "set-point") is
/// equivalent to an offset at the output. They are related by the
/// overall (DC feed-forward) gain of the filter.
/// * It stores only previous outputs and inputs. These have direct and
/// invariant interpretation (independent of gains and offsets).
/// Therefore it can trivially implement bump-less transfer.
/// * Cascading multiple IIR filters allows stable and robust
/// implementation of transfer functions beyond bequadratic terms.
#[derive(Copy, Clone, Deserialize, Serialize)]
pub struct IIR {
pub ba: IIRState,
pub y_offset: f32,
pub y_min: f32,
pub y_max: f32,
}
impl IIR {
/// Configures IIR filter coefficients for proportional-integral behavior
/// with gain limit.
///
/// # Arguments
///
/// * `kp` - Proportional gain. Also defines gain sign.
/// * `ki` - Integral gain at Nyquist. Sign taken from `kp`.
/// * `g` - Gain limit.
pub fn set_pi(&mut self, kp: f32, ki: f32, g: f32) -> Result<(), &str> {
let ki = copysign(ki, kp);
let g = copysign(g, kp);
let (a1, b0, b1) = if abs(ki) < f32::EPSILON {
(0., kp, 0.)
} else {
let c = if abs(g) < f32::EPSILON {
1.
} else {
1. / (1. + ki / g)
};
let a1 = 2. * c - 1.;
let b0 = ki * c + kp;
let b1 = ki * c - a1 * kp;
if abs(b0 + b1) < f32::EPSILON {
return Err("low integrator gain and/or gain limit");
}
(a1, b0, b1)
};
self.ba.copy_from_slice(&[b0, b1, 0., a1, 0.]);
Ok(())
}
/// Compute the overall (DC feed-forward) gain.
pub fn get_k(&self) -> f32 {
self.ba[..3].iter().sum()
}
/// Compute input-referred (`x`) offset from output (`y`) offset.
pub fn get_x_offset(&self) -> Result<f32, &str> {
let k = self.get_k();
if abs(k) < f32::EPSILON {
Err("k is zero")
} else {
Ok(self.y_offset / k)
}
}
/// Convert input (`x`) offset to equivalent output (`y`) offset and apply.
///
/// # Arguments
/// * `xo`: Input (`x`) offset.
pub fn set_x_offset(&mut self, xo: f32) {
self.y_offset = xo * self.get_k();
}
/// Feed a new input value into the filter, update the filter state, and
/// return the new output. Only the state `xy` is modified.
///
/// # Arguments
/// * `xy` - Current filter state.
/// * `x0` - New input.
pub fn update(&self, xy: &mut IIRState, x0: f32) -> f32 {
// `xy` contains x0 x1 y0 y1 y2
// Increment time x1 x2 y1 y2 y3
// Rotate y3 x1 x2 y1 y2
xy.rotate_right(1);
// Store x0 x0 x1 x2 y1 y2
xy[0] = x0;
// Compute y0 by multiply-accumulate
let y0 = macc(self.y_offset, xy, &self.ba);
// Limit y0
let y0 = max(self.y_min, min(self.y_max, y0));
// Store y0 x0 x1 y0 y1 y2
xy[xy.len() / 2] = y0;
y0
}
}

3
dsp/src/lib.rs Normal file
View File

@ -0,0 +1,3 @@
#![no_std]
pub mod iir;

View File

@ -17,7 +17,7 @@ SECTIONS {
*(.itcm .itcm.*);
. = ALIGN(8);
} > ITCM
.axisram : ALIGN(8) {
.axisram (NOLOAD) : ALIGN(8) {
*(.axisram .axisram.*);
. = ALIGN(8);
} > AXISRAM

View File

@ -42,13 +42,18 @@ static mut ADC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
/// SPI2 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI2 TX FIFO
/// whenever the tim2 update dma request occurs.
struct SPI2 {}
struct SPI2 {
_channel: sampling_timer::tim2::Channel1,
}
impl SPI2 {
pub fn new() -> Self {
Self {}
pub fn new(_channel: sampling_timer::tim2::Channel1) -> Self {
Self { _channel }
}
}
// Note(unsafe): This structure is only safe to instantiate once. The DMA request is hard-coded and
// may only be used if ownership of the timer2 channel 1 compare channel is assured, which is
// ensured by maintaining ownership of the channel.
unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 {
/// SPI2 is configured to operate using 16-bit transfer words.
type MemSize = u16;
@ -59,6 +64,8 @@ unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 {
/// Whenever the DMA request occurs, it should write into SPI2's TX FIFO to start a DMA
/// transfer.
fn address(&self) -> u32 {
// Note(unsafe): It is assumed that SPI2 is owned by another DMA transfer and this DMA is
// only used for the transmit-half of DMA.
let regs = unsafe { &*hal::stm32::SPI2::ptr() };
&regs.txdr as *const _ as u32
}
@ -66,13 +73,18 @@ unsafe impl TargetAddress<MemoryToPeripheral> for SPI2 {
/// SPI3 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI3 TX FIFO
/// whenever the tim2 update dma request occurs.
struct SPI3 {}
struct SPI3 {
_channel: sampling_timer::tim2::Channel2,
}
impl SPI3 {
pub fn new() -> Self {
Self {}
pub fn new(_channel: sampling_timer::tim2::Channel2) -> Self {
Self { _channel }
}
}
// Note(unsafe): This structure is only safe to instantiate once. The DMA request is hard-coded and
// may only be used if ownership of the timer2 channel 2 compare channel is assured, which is
// ensured by maintaining ownership of the channel.
unsafe impl TargetAddress<MemoryToPeripheral> for SPI3 {
/// SPI3 is configured to operate using 16-bit transfer words.
type MemSize = u16;
@ -83,6 +95,8 @@ unsafe impl TargetAddress<MemoryToPeripheral> for SPI3 {
/// Whenever the DMA request occurs, it should write into SPI3's TX FIFO to start a DMA
/// transfer.
fn address(&self) -> u32 {
// Note(unsafe): It is assumed that SPI3 is owned by another DMA transfer and this DMA is
// only used for the transmit-half of DMA.
let regs = unsafe { &*hal::stm32::SPI3::ptr() };
&regs.txdr as *const _ as u32
}
@ -144,7 +158,7 @@ impl Adc0Input {
spi: hal::spi::Spi<hal::stm32::SPI2, hal::spi::Enabled, u16>,
trigger_stream: hal::dma::dma::Stream0<hal::stm32::DMA1>,
data_stream: hal::dma::dma::Stream1<hal::stm32::DMA1>,
trigger_channel: sampling_timer::Timer2Channel1,
trigger_channel: sampling_timer::tim2::Channel1,
) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs.
@ -155,8 +169,6 @@ impl Adc0Input {
// contents). Thus, neither the memory or peripheral address ever change. This is run in
// circular mode to be completed at every DMA request.
let trigger_config = DmaConfig::default()
.memory_increment(false)
.peripheral_increment(false)
.priority(Priority::High)
.circular_buffer(true);
@ -164,7 +176,10 @@ impl Adc0Input {
let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> =
Transfer::init(
trigger_stream,
SPI2::new(),
SPI2::new(trigger_channel),
// Note(unsafe): Because this is a Memory->Peripheral transfer, this data is never
// actually modified. It technically only needs to be immutably borrowed, but the
// current HAL API only supports mutable borrows.
unsafe { &mut SPI_START },
None,
trigger_config,
@ -176,8 +191,7 @@ impl Adc0Input {
// stream is used to trigger a transfer completion interrupt.
let data_config = DmaConfig::default()
.memory_increment(true)
.priority(Priority::VeryHigh)
.peripheral_increment(false);
.priority(Priority::VeryHigh);
// A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This
// indicates that samples were dropped due to excessive processing time in the main
@ -192,6 +206,8 @@ impl Adc0Input {
Transfer::init(
data_stream,
spi,
// Note(unsafe): The ADC0_BUF0 is "owned" by this peripheral. It shall not be used
// anywhere else in the module.
unsafe { &mut ADC0_BUF0 },
None,
data_config,
@ -210,6 +226,8 @@ impl Adc0Input {
trigger_transfer.start(|_| {});
Self {
// Note(unsafe): The ADC0_BUF1 is "owned" by this peripheral. It shall not be used
// anywhere else in the module.
next_buffer: unsafe { Some(&mut ADC0_BUF1) },
transfer: data_transfer,
_trigger_transfer: trigger_transfer,
@ -224,7 +242,9 @@ impl Adc0Input {
let next_buffer = self.next_buffer.take().unwrap();
// Wait for the transfer to fully complete before continuing.
while self.transfer.get_transfer_complete_flag() == false {}
// 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();
@ -265,7 +285,7 @@ impl Adc1Input {
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::Timer2Channel2,
trigger_channel: sampling_timer::tim2::Channel2,
) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs.
@ -276,8 +296,6 @@ impl Adc1Input {
// contents). Thus, neither the memory or peripheral address ever change. This is run in
// circular mode to be completed at every DMA request.
let trigger_config = DmaConfig::default()
.memory_increment(false)
.peripheral_increment(false)
.priority(Priority::High)
.circular_buffer(true);
@ -285,7 +303,9 @@ impl Adc1Input {
let mut trigger_transfer: Transfer<_, _, MemoryToPeripheral, _> =
Transfer::init(
trigger_stream,
SPI3::new(),
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,
@ -298,8 +318,7 @@ impl Adc1Input {
let data_config = DmaConfig::default()
.memory_increment(true)
.transfer_complete_interrupt(true)
.priority(Priority::VeryHigh)
.peripheral_increment(false);
.priority(Priority::VeryHigh);
// A SPI peripheral error interrupt is used to determine if the RX FIFO overflows. This
// indicates that samples were dropped due to excessive processing time in the main
@ -314,6 +333,8 @@ impl Adc1Input {
Transfer::init(
data_stream,
spi,
// Note(unsafe): The ADC1_BUF0 is "owned" by this peripheral. It shall not be used
// anywhere else in the module.
unsafe { &mut ADC1_BUF0 },
None,
data_config,
@ -332,6 +353,8 @@ impl Adc1Input {
trigger_transfer.start(|_| {});
Self {
// Note(unsafe): The ADC1_BUF1 is "owned" by this peripheral. It shall not be used
// anywhere else in the module.
next_buffer: unsafe { Some(&mut ADC1_BUF1) },
transfer: data_transfer,
_trigger_transfer: trigger_transfer,
@ -346,7 +369,9 @@ impl Adc1Input {
let next_buffer = self.next_buffer.take().unwrap();
// Wait for the transfer to fully complete before continuing.
while self.transfer.get_transfer_complete_flag() == false {}
// 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();

View File

@ -24,14 +24,24 @@ static mut DAC1_BUF0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
#[link_section = ".axisram.buffers"]
static mut DAC1_BUF1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
/// SPI4 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI4 TX FIFO
struct SPI4 {}
/// 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 {
pub fn new() -> Self {
Self {}
pub fn new(
_channel: sampling_timer::tim2::Channel3,
spi: hal::spi::Spi<hal::stm32::SPI4, 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 SPI4 {
/// SPI2 is configured to operate using 16-bit transfer words.
type MemSize = u16;
@ -41,19 +51,28 @@ unsafe impl TargetAddress<MemoryToPeripheral> for SPI4 {
/// 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
&self.spi.inner().txdr as *const _ as u32
}
}
/// SPI5 is used as a ZST (zero-sized type) for indicating a DMA transfer into the SPI5 TX FIFO
struct SPI5 {}
struct SPI5 {
_channel: sampling_timer::tim2::Channel4,
spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
}
impl SPI5 {
pub fn new() -> Self {
Self {}
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;
@ -63,8 +82,7 @@ unsafe impl TargetAddress<MemoryToPeripheral> for SPI5 {
/// 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
&self.spi.inner().txdr as *const _ as u32
}
}
@ -80,25 +98,35 @@ impl DacOutputs {
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.
///
/// # 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);
/// # 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]>,
_spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Disabled, u16>,
// Note: SPI TX functionality may not be used from this structure to ensure safety with DMA.
transfer: Transfer<
hal::dma::dma::Stream4<hal::stm32::DMA1>,
SPI4,
@ -118,7 +146,7 @@ impl Dac0Output {
pub fn new(
spi: hal::spi::Spi<hal::stm32::SPI4, hal::spi::Enabled, u16>,
stream: hal::dma::dma::Stream4<hal::stm32::DMA1>,
trigger_channel: sampling_timer::Timer2Channel3,
trigger_channel: sampling_timer::tim2::Channel3,
) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs.
@ -130,15 +158,6 @@ impl Dac0Output {
.memory_increment(true)
.peripheral_increment(false);
// Construct the trigger stream to write from memory to the peripheral.
let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init(
stream,
SPI4::new(),
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();
@ -151,30 +170,44 @@ impl Dac0Output {
spi.inner().cr1.modify(|_, w| w.spe().set_bit());
spi.inner().cr1.modify(|_, w| w.cstart().started());
// Construct the trigger stream to write from memory to the peripheral.
let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init(
stream,
SPI4::new(trigger_channel, spi),
// Note(unsafe): This buffer is only used once and provided for the DMA transfer.
unsafe { &mut DAC0_BUF0 },
None,
trigger_config,
);
Self {
transfer,
// Note(unsafe): This buffer is only used once and provided for the next DMA transfer.
next_buffer: unsafe { Some(&mut DAC0_BUF1) },
_spi: spi,
first_transfer: true,
}
}
/// Schedule the next set of DAC update codes.
/// Mutably borrow the next output buffer to populate it with DAC codes.
pub fn prepare_buffer(&mut self) -> &mut [u16; SAMPLE_BUFFER_SIZE] {
self.next_buffer.as_mut().unwrap()
}
/// Enqueue the next buffer for transmission to the DAC.
///
/// # Args
/// * `data` - The next samples to enqueue for transmission.
pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) {
/// * `data` - The next data to write to the DAC.
pub fn commit_buffer(&mut self) {
let next_buffer = self.next_buffer.take().unwrap();
// Copy data into the next buffer
next_buffer.copy_from_slice(data);
// If the last transfer was not complete, we didn't write all our previous DAC codes.
// Wait for all the DAC codes to get written as well.
if self.first_transfer {
self.first_transfer = false
} else {
while self.transfer.get_transfer_complete_flag() == false {}
// 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.
@ -189,7 +222,6 @@ impl Dac0Output {
/// Represents the data output stream from DAC1.
pub struct Dac1Output {
next_buffer: Option<&'static mut [u16; SAMPLE_BUFFER_SIZE]>,
_spi: hal::spi::Spi<hal::stm32::SPI5, hal::spi::Disabled, u16>,
transfer: Transfer<
hal::dma::dma::Stream5<hal::stm32::DMA1>,
SPI5,
@ -209,7 +241,7 @@ impl Dac1Output {
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,
trigger_channel: sampling_timer::tim2::Channel4,
) -> Self {
// Generate DMA events when an output compare of the timer hitting zero (timer roll over)
// occurs.
@ -222,15 +254,6 @@ impl Dac1Output {
.peripheral_increment(false)
.circular_buffer(true);
// Construct the stream to write from memory to the peripheral.
let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init(
stream,
SPI5::new(),
unsafe { &mut DAC1_BUF0 },
None,
trigger_config,
);
// Listen for any SPI errors, as this may indicate that we are not generating updates on the
// DAC.
let mut spi = spi.disable();
@ -243,30 +266,44 @@ impl Dac1Output {
spi.inner().cr1.modify(|_, w| w.spe().set_bit());
spi.inner().cr1.modify(|_, w| w.cstart().started());
// Construct the stream to write from memory to the peripheral.
let transfer: Transfer<_, _, MemoryToPeripheral, _> = Transfer::init(
stream,
SPI5::new(trigger_channel, spi),
// Note(unsafe): This buffer is only used once and provided to the transfer.
unsafe { &mut DAC1_BUF0 },
None,
trigger_config,
);
Self {
// Note(unsafe): This buffer is only used once and provided for the next DMA transfer.
next_buffer: unsafe { Some(&mut DAC1_BUF1) },
transfer,
_spi: spi,
first_transfer: true,
}
}
/// Mutably borrow the next output buffer to populate it with DAC codes.
pub fn prepare_buffer(&mut self) -> &mut [u16; SAMPLE_BUFFER_SIZE] {
self.next_buffer.as_mut().unwrap()
}
/// Enqueue the next buffer for transmission to the DAC.
///
/// # Args
/// * `data` - The next data to write to the DAC.
pub fn next_data(&mut self, data: &[u16; SAMPLE_BUFFER_SIZE]) {
pub fn commit_buffer(&mut self) {
let next_buffer = self.next_buffer.take().unwrap();
// Copy data into the next buffer
next_buffer.copy_from_slice(data);
// If the last transfer was not complete, we didn't write all our previous DAC codes.
// Wait for all the DAC codes to get written as well.
if self.first_transfer {
self.first_transfer = false
} else {
while self.transfer.get_transfer_complete_flag() == false {}
// 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.

6
src/design_parameters.rs Normal file
View File

@ -0,0 +1,6 @@
/// The ADC setup time is the number of seconds after the CSn line goes low before the serial clock
/// may begin. This is used for performing the internal ADC conversion.
pub const ADC_SETUP_TIME: f32 = 220e-9;
/// The maximum DAC/ADC serial clock line frequency. This is a hardware limit.
pub const ADC_DAC_SCK_MHZ_MAX: u32 = 50;

View File

@ -1,108 +0,0 @@
use core::ops::{Add, Mul};
use serde::{Deserialize, Serialize};
use core::f32;
pub type IIRState = [f32; 5];
#[derive(Copy, Clone, Deserialize, Serialize)]
pub struct IIR {
pub ba: IIRState,
pub y_offset: f32,
pub y_min: f32,
pub y_max: f32,
}
fn abs(x: f32) -> f32 {
if x >= 0. {
x
} else {
-x
}
}
fn copysign(x: f32, y: f32) -> f32 {
if (x >= 0. && y >= 0.) || (x <= 0. && y <= 0.) {
x
} else {
-x
}
}
fn max(x: f32, y: f32) -> f32 {
if x > y {
x
} else {
y
}
}
fn min(x: f32, y: f32) -> f32 {
if x < y {
x
} else {
y
}
}
fn macc<T>(y0: T, x: &[T], a: &[T]) -> T
where
T: Add<Output = T> + Mul<Output = T> + Copy,
{
x.iter()
.zip(a.iter())
.map(|(&i, &j)| i * j)
.fold(y0, |y, xa| y + xa)
}
impl IIR {
pub fn set_pi(&mut self, kp: f32, ki: f32, g: f32) -> Result<(), &str> {
let ki = copysign(ki, kp);
let g = copysign(g, kp);
let (a1, b0, b1) = if abs(ki) < f32::EPSILON {
(0., kp, 0.)
} else {
let c = if abs(g) < f32::EPSILON {
1.
} else {
1. / (1. + ki / g)
};
let a1 = 2. * c - 1.;
let b0 = ki * c + kp;
let b1 = ki * c - a1 * kp;
if abs(b0 + b1) < f32::EPSILON {
return Err("low integrator gain and/or gain limit");
}
(a1, b0, b1)
};
self.ba[0] = b0;
self.ba[1] = b1;
self.ba[2] = 0.;
self.ba[3] = a1;
self.ba[4] = 0.;
Ok(())
}
pub fn get_x_offset(&self) -> Result<f32, &str> {
let b: f32 = self.ba[..3].iter().sum();
if abs(b) < f32::EPSILON {
Err("b is zero")
} else {
Ok(self.y_offset / b)
}
}
pub fn set_x_offset(&mut self, xo: f32) {
let b: f32 = self.ba[..3].iter().sum();
self.y_offset = xo * b;
}
pub fn update(&self, xy: &mut IIRState, x0: f32) -> f32 {
xy.rotate_right(1);
xy[0] = x0;
let y0 = macc(self.y_offset, xy, &self.ba);
let y0 = max(self.y_min, min(self.y_max, y0));
xy[xy.len() / 2] = y0;
y0
}
}

View File

@ -63,9 +63,9 @@ static mut DES_RING: ethernet::DesRing = ethernet::DesRing::new();
mod adc;
mod afe;
mod dac;
mod design_parameters;
mod eeprom;
mod hrtimer;
mod iir;
mod pounder;
mod sampling_timer;
mod server;
@ -73,6 +73,7 @@ mod server;
use adc::{Adc0Input, Adc1Input, AdcInputs};
use dac::{Dac0Output, Dac1Output, DacOutputs};
use pounder::DdsOutput;
use dsp::iir;
#[cfg(not(feature = "semihosting"))]
fn init_log() {}
@ -141,6 +142,7 @@ macro_rules! route_request {
match $request.attribute {
$(
$read_attribute => {
#[allow(clippy::redundant_closure_call)]
let value = match $getter() {
Ok(data) => data,
Err(_) => return server::Response::error($request.attribute,
@ -169,6 +171,7 @@ macro_rules! route_request {
"Failed to decode value"),
};
#[allow(clippy::redundant_closure_call)]
match $setter(new_value) {
Ok(_) => server::Response::success($request.attribute, &$request.value),
Err(_) => server::Response::error($request.attribute,
@ -303,12 +306,12 @@ const APP: () = {
})
.manage_cs()
.suspend_when_inactive()
.cs_delay(220e-9);
.cs_delay(design_parameters::ADC_SETUP_TIME);
let spi: hal::spi::Spi<_, _, u16> = dp.SPI2.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
50.mhz(),
design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(),
ccdr.peripheral.SPI2,
&ccdr.clocks,
);
@ -341,12 +344,12 @@ const APP: () = {
})
.manage_cs()
.suspend_when_inactive()
.cs_delay(220e-9);
.cs_delay(design_parameters::ADC_SETUP_TIME);
let spi: hal::spi::Spi<_, _, u16> = dp.SPI3.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
50.mhz(),
design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(),
ccdr.peripheral.SPI3,
&ccdr.clocks,
);
@ -396,7 +399,7 @@ const APP: () = {
dp.SPI4.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
50.mhz(),
design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(),
ccdr.peripheral.SPI4,
&ccdr.clocks,
)
@ -428,7 +431,7 @@ const APP: () = {
dp.SPI5.spi(
(spi_sck, spi_miso, hal::spi::NoMosi),
config,
50.mhz(),
design_parameters::ADC_DAC_SCK_MHZ_MAX.mhz(),
ccdr.peripheral.SPI5,
&ccdr.clocks,
)
@ -721,7 +724,7 @@ const APP: () = {
dp.ETHERNET_MTL,
dp.ETHERNET_DMA,
&mut DES_RING,
mac_addr.clone(),
mac_addr,
ccdr.peripheral.ETH1MAC,
&ccdr.clocks,
)
@ -773,8 +776,8 @@ const APP: () = {
sampling_timer.start();
init::LateResources {
afe0: afe0,
afe1: afe1,
afe0,
afe1,
adcs,
dacs,
@ -793,8 +796,7 @@ const APP: () = {
let (adc0_samples, adc1_samples) =
c.resources.adcs.transfer_complete_handler();
let mut dac0: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
let mut dac1: [u16; SAMPLE_BUFFER_SIZE] = [0; SAMPLE_BUFFER_SIZE];
let (dac0, dac1) = c.resources.dacs.prepare_data();
for (i, (adc0, adc1)) in
adc0_samples.iter().zip(adc1_samples.iter()).enumerate()
@ -825,7 +827,7 @@ const APP: () = {
dds_output.write_profile(profile);
}
c.resources.dacs.next_data(&dac0, &dac1);
c.resources.dacs.commit_data();
}
#[idle(resources=[net_interface, mac_addr, eth_mac, iir_state, iir_ch, afe0, afe1])]
@ -916,10 +918,12 @@ const APP: () = {
})
}),
"stabilizer/afe0/gain": afe::Gain, (|gain| {
Ok::<(), ()>(c.resources.afe0.set_gain(gain))
c.resources.afe0.set_gain(gain);
Ok::<(), ()>(())
}),
"stabilizer/afe1/gain": afe::Gain, (|gain| {
Ok::<(), ()>(c.resources.afe1.set_gain(gain))
c.resources.afe1.set_gain(gain);
Ok::<(), ()>(())
})
]
)
@ -931,7 +935,7 @@ const APP: () = {
&mut sockets,
net::time::Instant::from_millis(time as i64),
) {
Ok(changed) => changed == false,
Ok(changed) => !changed,
Err(net::Error::Unrecognized) => true,
Err(e) => {
info!("iface poll error: {:?}", e);
@ -950,22 +954,22 @@ const APP: () = {
unsafe { ethernet::interrupt_handler() }
}
#[task(binds = SPI2, priority = 1)]
#[task(binds = SPI2, priority = 3)]
fn spi2(_: spi2::Context) {
panic!("ADC0 input overrun");
}
#[task(binds = SPI3, priority = 1)]
#[task(binds = SPI3, priority = 3)]
fn spi3(_: spi3::Context) {
panic!("ADC0 input overrun");
}
#[task(binds = SPI4, priority = 1)]
#[task(binds = SPI4, priority = 3)]
fn spi4(_: spi4::Context) {
panic!("DAC0 output error");
}
#[task(binds = SPI5, priority = 1)]
#[task(binds = SPI5, priority = 3)]
fn spi5(_: spi5::Context) {
panic!("DAC1 output error");
}

View File

@ -19,7 +19,7 @@ pub trait AttenuatorInterface {
channel: Channel,
attenuation: f32,
) -> Result<f32, Error> {
if attenuation > 31.5 || attenuation < 0.0 {
if !(0.0..=31.5).contains(&attenuation) {
return Err(Error::Bounds);
}

View File

@ -20,7 +20,7 @@ const ATT_RST_N_PIN: u8 = 8 + 5;
const ATT_LE3_PIN: u8 = 8 + 3;
const ATT_LE2_PIN: u8 = 8 + 2;
const ATT_LE1_PIN: u8 = 8 + 1;
const ATT_LE0_PIN: u8 = 8 + 0;
const ATT_LE0_PIN: u8 = 8;
#[derive(Debug, Copy, Clone)]
pub enum Error {

View File

@ -1,12 +1,10 @@
///! The sampling timer is used for managing ADC sampling and external reference timestamping.
use super::hal;
pub use hal::stm32::tim2::ccmr2_input::CC4S_A;
/// The timer used for managing ADC sampling.
pub struct SamplingTimer {
timer: hal::timer::Timer<hal::stm32::TIM2>,
channels: Option<TimerChannels>,
channels: Option<tim2::Channels>,
}
impl SamplingTimer {
@ -16,12 +14,17 @@ impl SamplingTimer {
Self {
timer,
channels: Some(TimerChannels::new()),
// Note(unsafe): Once these channels are taken, we guarantee that we do not modify any
// of the underlying timer channel registers, as ownership of the channels is now
// provided through the associated channel structures. We additionally guarantee this
// can only be called once because there is only one Timer2 and this resource takes
// ownership of it once instantiated.
channels: unsafe { Some(tim2::Channels::new()) },
}
}
/// Get the timer capture/compare channels.
pub fn channels(&mut self) -> TimerChannels {
pub fn channels(&mut self) -> tim2::Channels {
self.channels.take().unwrap()
}
@ -32,116 +35,85 @@ impl SamplingTimer {
}
}
/// The capture/compare channels for the sampling timer.
macro_rules! timer_channel {
($name:ident, $TY:ty, ($ccxde:expr, $ccrx:expr, $ccmrx_output:expr, $ccxs:expr)) => {
pub struct $name {}
paste::paste! {
impl $name {
/// Construct a new timer channel.
///
/// # Note
/// This should not be instantiated directly.
pub struct TimerChannels {
pub ch1: Timer2Channel1,
pub ch2: Timer2Channel2,
pub ch3: Timer2Channel3,
pub ch4: Timer2Channel4,
/// Note(unsafe): This function must only be called once. Once constructed, the
/// constructee guarantees to never modify the timer channel.
unsafe fn new() -> Self {
Self {}
}
impl TimerChannels {
fn new() -> Self {
/// Allow CH4 to generate DMA requests.
pub fn listen_dma(&self) {
let regs = unsafe { &*<$TY>::ptr() };
regs.dier.modify(|_, w| w.[< $ccxde >]().set_bit());
}
/// Operate CH2 as an output-compare.
///
/// # Args
/// * `value` - The value to compare the sampling timer's counter against.
pub fn to_output_compare(&self, value: u32) {
let regs = unsafe { &*<$TY>::ptr() };
assert!(value <= regs.arr.read().bits());
regs.[< $ccrx >].write(|w| w.ccr().bits(value));
regs.[< $ccmrx_output >]()
.modify(|_, w| unsafe { w.[< $ccxs >]().bits(0) });
}
}
}
};
}
pub mod tim2 {
use stm32h7xx_hal as hal;
/// The channels representing the timer.
pub struct Channels {
pub ch1: Channel1,
pub ch2: Channel2,
pub ch3: Channel3,
pub ch4: Channel4,
}
impl Channels {
/// Construct a new set of channels.
///
/// Note(unsafe): This is only safe to call once.
pub unsafe fn new() -> Self {
Self {
ch1: Timer2Channel1 {},
ch2: Timer2Channel2 {},
ch3: Timer2Channel3 {},
ch4: Timer2Channel4 {},
ch1: Channel1::new(),
ch2: Channel2::new(),
ch3: Channel3::new(),
ch4: Channel4::new(),
}
}
}
/// 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) });
}
timer_channel!(
Channel1,
hal::stm32::TIM2,
(cc1de, ccr1, ccmr1_output, cc1s)
);
timer_channel!(
Channel2,
hal::stm32::TIM2,
(cc2de, ccr2, ccmr1_output, cc1s)
);
timer_channel!(
Channel3,
hal::stm32::TIM2,
(cc3de, ccr3, ccmr2_output, cc3s)
);
timer_channel!(
Channel4,
hal::stm32::TIM2,
(cc4de, ccr4, ccmr2_output, cc4s)
);
}

View File

@ -89,7 +89,7 @@ impl Response {
/// Args:
/// * `attrbute` - The attribute of the success.
/// * `value` - The value of the attribute.
pub fn success<'a, 'b>(attribute: &'a str, value: &'b str) -> Self {
pub fn success(attribute: &str, value: &str) -> Self {
let mut res = Self {
code: 200,
attribute: String::from(attribute),
@ -106,7 +106,7 @@ impl Response {
/// Args:
/// * `attrbute` - The attribute of the success.
/// * `message` - The message denoting the error.
pub fn error<'a, 'b>(attribute: &'a str, message: &'b str) -> Self {
pub fn error(attribute: &str, message: &str) -> Self {
let mut res = Self {
code: 400,
attribute: String::from(attribute),
@ -123,7 +123,7 @@ impl Response {
/// Args:
/// * `attrbute` - The attribute of the success.
/// * `message` - The message denoting the status.
pub fn custom<'a>(code: i32, message: &'a str) -> Self {
pub fn custom(code: i32, message: &str) -> Self {
let mut res = Self {
code,
attribute: String::from(""),