pounder_test/src/bin/lockin.rs

513 lines
16 KiB
Rust
Raw Normal View History

2021-07-15 19:28:19 +08:00
//! # Lockin
//!
//! THe `lockin` application implements a lock-in amplifier using either an external or internally
//! generated
//!
//! ## Features
//! * Up to 800 kHz sampling
//! * Up to 400 kHz modulation frequency
//! * Supports internal and external reference sources:
//! 1. Internal: Generate reference internally and output on one of the channel outputs
//! 2. External: Reciprocal PLL, reference input applied to DI0.
//! * Adjustable PLL and locking time constants
//! * Adjustable phase offset and harmonic index
//! * Run-time configurable output modes (in-phase, quadrature, magnitude, log2 power, phase, frequency)
//! * Input/output data streamng via UDP
//!
//! ## Settings
//! Refer to the [Settings] structure for documentation of run-time configurable settings for this
//! application.
//!
//! ## Telemetry
//! Refer to [Telemetry] for information about telemetry reported by this application.
//!
//! ## Livestreaming
//! This application streams raw ADC and DAC data over UDP. Refer to
//! [stabilizer::net::data_stream](../stabilizer/net/data_stream/index.html) for more information.
#![deny(warnings)]
#![no_std]
#![no_main]
use core::{
convert::TryFrom,
sync::atomic::{fence, Ordering},
};
2021-03-02 02:48:45 +08:00
use mutex_trait::prelude::*;
2021-03-02 02:48:45 +08:00
use dsp::{Accu, Complex, ComplexExt, Lockin, RPLL};
use stabilizer::{
hardware::{
self,
adc::{Adc0Input, Adc1Input, AdcCode},
afe::Gain,
dac::{Dac0Output, Dac1Output, DacCode},
embedded_hal::digital::v2::InputPin,
hal,
input_stamper::InputStamper,
signal_generator,
system_timer::SystemTimer,
DigitalInput0, DigitalInput1, AFE0, AFE1,
},
net::{
data_stream::{FrameGenerator, StreamFormat, StreamTarget},
miniconf::Miniconf,
serde::Deserialize,
telemetry::{Telemetry, TelemetryBuffer},
NetworkState, NetworkUsers,
},
2021-01-20 21:29:29 +08:00
};
2021-03-02 02:48:45 +08:00
// The logarithm of the number of samples in each batch process. This corresponds with 2^3 samples
// per batch = 8 samples
const BATCH_SIZE_SIZE_LOG2: u8 = 3;
// The logarithm of the number of 100MHz timer ticks between each sample. This corresponds with a
// sampling period of 2^7 = 128 ticks. At 100MHz, 10ns per tick, this corresponds to a sampling
// period of 1.28 uS or 781.25 KHz.
const ADC_SAMPLE_TICKS_LOG2: u8 = 7;
2021-03-03 00:29:20 +08:00
#[derive(Copy, Clone, Debug, Deserialize, Miniconf)]
2021-03-02 02:48:45 +08:00
enum Conf {
2021-07-15 19:28:19 +08:00
/// Output the lockin magnitude.
2021-05-06 20:34:09 +08:00
Magnitude,
2021-07-15 19:28:19 +08:00
/// Output the phase of the lockin
Phase,
2021-07-15 19:28:19 +08:00
/// Output the lockin reference frequency as a sinusoid
ReferenceFrequency,
2021-07-15 19:28:19 +08:00
/// Output the logarithmic power of the lockin
2021-05-06 20:33:22 +08:00
LogPower,
2021-07-15 19:28:19 +08:00
/// Output the in-phase component of the lockin signal.
2021-05-06 20:33:22 +08:00
InPhase,
2021-07-15 19:28:19 +08:00
/// Output the quadrature component of the lockin signal.
2021-05-06 20:33:22 +08:00
Quadrature,
2021-07-15 19:28:19 +08:00
/// Output the lockin internal modulation frequency as a sinusoid
2021-05-06 20:33:22 +08:00
Modulation,
2021-03-02 02:48:45 +08:00
}
2021-05-06 19:08:10 +08:00
#[derive(Copy, Clone, Debug, Miniconf, Deserialize, PartialEq)]
enum LockinMode {
2021-07-15 19:28:19 +08:00
/// Utilize an internally generated reference for demodulation
2021-05-06 19:08:10 +08:00
Internal,
2021-07-15 19:28:19 +08:00
/// Utilize an external modulation signal supplied to DI0
2021-05-06 19:08:10 +08:00
External,
}
2021-03-03 00:29:20 +08:00
#[derive(Copy, Clone, Debug, Deserialize, Miniconf)]
2021-03-02 02:48:45 +08:00
pub struct Settings {
2021-07-15 19:28:19 +08:00
/// Configure the Analog Front End (AFE) gain.
///
/// # Path
/// `afe/<n>`
///
/// * <n> specifies which channel to configure. <n> := [0, 1]
///
/// # Value
/// Any of the variants of [Gain] enclosed in double quotes.
afe: [Gain; 2],
2021-07-15 19:28:19 +08:00
/// Specifies the operational mode of the lockin.
///
/// # Path
/// `lockin_mode`
///
/// # Value
/// One of the variants of [LockinMode] enclosed in double quotes.
2021-05-06 19:08:10 +08:00
lockin_mode: LockinMode,
2021-03-02 02:48:45 +08:00
2021-07-15 19:28:19 +08:00
/// Specifis the PLL time constant.
///
/// # Path
/// `pll_tc/<n>`
///
/// * <n> specifies which channel to configure. <n> := [0, 1]
///
/// # Value
/// The PLL time constant as an unsigned byte (0-255).
2021-03-02 02:48:45 +08:00
pll_tc: [u8; 2],
2021-07-15 19:28:19 +08:00
/// Specifies the lockin time constant.
///
/// # Path
/// `lockin_tc`
///
/// # Value
/// The lockin low-pass time constant as an unsigned byte (0-255).
2021-03-02 02:48:45 +08:00
lockin_tc: u8,
2021-07-15 19:28:19 +08:00
/// Specifies which harmonic to use for the lockin.
///
/// # Path
/// `lockin_harmonic`
///
/// # Value
/// Harmonic index of the LO. -1 to _de_modulate the fundamental (complex conjugate)
2021-03-02 02:48:45 +08:00
lockin_harmonic: i32,
2021-07-15 19:28:19 +08:00
/// Specifies the LO phase offset.
///
/// # Path
/// `lockin_phase`
///
/// # Value
/// Demodulation LO phase offset. Units are in terms of i32, where [i32::MIN] is equivalent to
/// -pi and [i32::MAX] is equivalent to +pi.
2021-03-02 02:48:45 +08:00
lockin_phase: i32,
2021-07-15 19:28:19 +08:00
/// Specifies DAC output mode.
///
/// # Path
/// `output_conf/<n>`
///
/// * <n> specifies which channel to configure. <n> := [0, 1]
///
/// # Value
/// One of the variants of [Conf] enclosed in double quotes.
2021-03-02 18:46:19 +08:00
output_conf: [Conf; 2],
2021-07-15 19:28:19 +08:00
/// Specifies the telemetry output period in seconds.
///
/// # Path
/// `telemetry_period`
///
/// # Value
/// Any non-zero value less than 65536.
2021-05-07 19:02:14 +08:00
telemetry_period: u16,
2021-06-15 19:22:38 +08:00
2021-07-15 19:28:19 +08:00
/// Specifies the target for data livestreaming.
///
/// # Path
/// `stream_target`
///
/// # Value
/// See [StreamTarget#miniconf]
2021-06-15 19:22:38 +08:00
stream_target: StreamTarget,
2021-03-02 02:48:45 +08:00
}
impl Default for Settings {
fn default() -> Self {
Self {
afe: [Gain::G1; 2],
2021-03-02 02:48:45 +08:00
2021-05-06 19:08:10 +08:00
lockin_mode: LockinMode::External,
2021-03-02 02:48:45 +08:00
pll_tc: [21, 21], // frequency and phase settling time (log2 counter cycles)
lockin_tc: 6, // lockin lowpass time constant
lockin_harmonic: -1, // Harmonic index of the LO: -1 to _de_modulate the fundamental (complex conjugate)
lockin_phase: 0, // Demodulation LO phase offset
2021-05-06 20:33:22 +08:00
output_conf: [Conf::InPhase, Conf::Quadrature],
2021-05-10 17:10:26 +08:00
// The default telemetry period in seconds.
2021-05-07 19:02:14 +08:00
telemetry_period: 10,
2021-06-15 19:22:38 +08:00
stream_target: StreamTarget::default(),
2021-03-02 02:48:45 +08:00
}
}
}
2021-01-20 21:29:29 +08:00
#[rtic::app(device = stabilizer::hardware::hal::stm32, peripherals = true, monotonic = stabilizer::hardware::system_timer::SystemTimer)]
const APP: () = {
struct Resources {
afes: (AFE0, AFE1),
adcs: (Adc0Input, Adc1Input),
dacs: (Dac0Output, Dac1Output),
2021-05-05 22:16:54 +08:00
network: NetworkUsers<Settings, Telemetry>,
2021-03-02 02:48:45 +08:00
settings: Settings,
2021-05-05 22:16:54 +08:00
telemetry: TelemetryBuffer,
digital_inputs: (DigitalInput0, DigitalInput1),
2021-07-22 20:45:58 +08:00
generator: FrameGenerator,
signal_generator: signal_generator::SignalGenerator,
2021-01-20 21:29:29 +08:00
timestamper: InputStamper,
2021-01-25 18:45:55 +08:00
pll: RPLL,
2021-05-10 23:31:53 +08:00
lockin: Lockin<4>,
}
2021-05-31 20:28:57 +08:00
#[init(spawn=[settings_update, telemetry, ethernet_link])]
fn init(c: init::Context) -> init::LateResources {
// Configure the microcontroller
let (mut stabilizer, _pounder) = hardware::setup::setup(
c.core,
c.device,
1 << BATCH_SIZE_SIZE_LOG2,
1 << ADC_SAMPLE_TICKS_LOG2,
);
2021-03-02 02:48:45 +08:00
2021-06-15 19:22:38 +08:00
let mut network = NetworkUsers::new(
2021-03-18 03:16:13 +08:00
stabilizer.net.stack,
stabilizer.net.phy,
stabilizer.cycle_counter,
2021-05-05 22:16:54 +08:00
env!("CARGO_BIN_NAME"),
stabilizer.net.mac_address,
2021-08-03 16:47:37 +08:00
option_env!("BROKER")
.unwrap_or("10.34.16.10")
.parse()
.unwrap(),
2021-03-18 03:16:13 +08:00
);
2021-03-02 02:48:45 +08:00
2021-07-27 19:12:57 +08:00
let generator = network.configure_streaming(
StreamFormat::AdcDacData,
1u8 << BATCH_SIZE_SIZE_LOG2,
2021-07-27 19:12:57 +08:00
);
2021-06-15 19:22:38 +08:00
2021-03-02 02:48:45 +08:00
let settings = Settings::default();
let pll = RPLL::new(ADC_SAMPLE_TICKS_LOG2 + BATCH_SIZE_SIZE_LOG2);
2021-01-20 21:29:29 +08:00
// Spawn a settings and telemetry update for default settings.
2021-03-02 02:48:45 +08:00
c.spawn.settings_update().unwrap();
c.spawn.telemetry().unwrap();
2021-03-02 02:48:45 +08:00
2021-05-31 20:28:57 +08:00
// Spawn the ethernet link servicing task.
c.spawn.ethernet_link().unwrap();
// Enable ADC/DAC events
stabilizer.adcs.0.start();
stabilizer.adcs.1.start();
stabilizer.dacs.0.start();
stabilizer.dacs.1.start();
2021-01-21 21:55:33 +08:00
// Start recording digital input timestamps.
stabilizer.timestamp_timer.start();
2021-01-21 23:12:59 +08:00
// Start sampling ADCs.
stabilizer.adc_dac_timer.start();
2021-02-03 20:03:17 +08:00
// Enable the timestamper.
stabilizer.timestamper.start();
2021-07-19 18:46:06 +08:00
let signal_config = {
let frequency_tuning_word =
(1u64 << (32 - BATCH_SIZE_SIZE_LOG2)) as u32;
2021-07-19 18:46:06 +08:00
signal_generator::Config {
// Same frequency as batch size.
frequency_tuning_word: [
frequency_tuning_word,
frequency_tuning_word,
],
// 1V Amplitude
amplitude: DacCode::try_from(1.0).unwrap().into(),
2021-07-19 18:46:06 +08:00
signal: signal_generator::Signal::Cosine,
}
};
init::LateResources {
afes: stabilizer.afes,
adcs: stabilizer.adcs,
dacs: stabilizer.dacs,
2021-05-05 21:39:33 +08:00
network,
digital_inputs: stabilizer.digital_inputs,
2021-01-20 21:29:29 +08:00
timestamper: stabilizer.timestamper,
telemetry: TelemetryBuffer::default(),
signal_generator: signal_generator::SignalGenerator::new(
2021-07-19 18:46:06 +08:00
signal_config,
),
2021-03-02 02:48:45 +08:00
settings,
2021-06-15 19:22:38 +08:00
generator,
2021-02-18 00:22:43 +08:00
2021-01-21 21:55:33 +08:00
pll,
2021-02-15 00:55:01 +08:00
lockin: Lockin::default(),
}
}
2021-02-02 22:50:31 +08:00
/// Main DSP processing routine.
///
2021-02-02 22:50:31 +08:00
/// See `dual-iir` for general notes on processing time and timing.
///
2021-02-02 22:50:31 +08:00
/// This is an implementation of a externally (DI0) referenced PLL lockin on the ADC0 signal.
/// It outputs either I/Q or power/phase on DAC0/DAC1. Data is normalized to full scale.
/// PLL bandwidth, filter bandwidth, slope, and x/y or power/phase post-filters are available.
#[task(binds=DMA1_STR4, resources=[adcs, dacs, lockin, timestamper, pll, settings, telemetry, generator, signal_generator], priority=2)]
#[inline(never)]
#[link_section = ".itcm.process"]
fn process(mut c: process::Context) {
let process::Resources {
adcs: (ref mut adc0, ref mut adc1),
dacs: (ref mut dac0, ref mut dac1),
ref settings,
ref mut telemetry,
ref mut lockin,
ref mut pll,
ref mut timestamper,
2021-06-15 19:22:38 +08:00
ref mut generator,
ref mut signal_generator,
} = c.resources;
let (reference_phase, reference_frequency) = match settings.lockin_mode
{
2021-05-06 19:08:10 +08:00
LockinMode::External => {
let timestamp = timestamper.latest_timestamp().unwrap_or(None); // Ignore data from timer capture overflows.
let (pll_phase, pll_frequency) = pll.update(
2021-05-06 19:08:10 +08:00
timestamp.map(|t| t as i32),
settings.pll_tc[0],
settings.pll_tc[1],
);
(pll_phase, (pll_frequency >> BATCH_SIZE_SIZE_LOG2) as i32)
2021-05-06 19:08:10 +08:00
}
LockinMode::Internal => {
// Reference phase and frequency are known.
(1i32 << 30, 1i32 << (32 - BATCH_SIZE_SIZE_LOG2))
2021-05-06 19:08:10 +08:00
}
};
let sample_frequency =
reference_frequency.wrapping_mul(settings.lockin_harmonic);
let sample_phase = settings.lockin_phase.wrapping_add(
reference_phase.wrapping_mul(settings.lockin_harmonic),
);
(adc0, adc1, dac0, dac1).lock(|adc0, adc1, dac0, dac1| {
let adc_samples = [adc0, adc1];
let mut dac_samples = [dac0, dac1];
2021-06-01 20:49:51 +08:00
// Preserve instruction and data ordering w.r.t. DMA flag access.
fence(Ordering::SeqCst);
let output: Complex<i32> = adc_samples[0]
.iter()
// Zip in the LO phase.
.zip(Accu::new(sample_phase, sample_frequency))
// Convert to signed, MSB align the ADC sample, update the Lockin (demodulate, filter)
.map(|(&sample, phase)| {
let s = (sample as i16 as i32) << 16;
lockin.update(s, phase, settings.lockin_tc)
})
// Decimate
.last()
.unwrap()
* 2; // Full scale assuming the 2f component is gone.
// Convert to DAC data.
for (channel, samples) in dac_samples.iter_mut().enumerate() {
for sample in samples.iter_mut() {
let value = match settings.output_conf[channel] {
Conf::Magnitude => output.abs_sqr() as i32 >> 16,
Conf::Phase => output.arg() >> 16,
Conf::LogPower => (output.log2() << 24) as i32 >> 16,
Conf::ReferenceFrequency => {
reference_frequency as i32 >> 16
}
Conf::InPhase => output.re >> 16,
Conf::Quadrature => output.im >> 16,
2021-06-29 19:23:42 +08:00
Conf::Modulation => {
signal_generator.next().unwrap() as i32
}
};
*sample = DacCode::from(value as i16).0;
}
2021-05-06 19:08:10 +08:00
}
2021-06-15 19:22:38 +08:00
2021-07-22 20:45:58 +08:00
// Stream the data.
const N: usize =
(1 << BATCH_SIZE_SIZE_LOG2) * core::mem::size_of::<u16>();
2021-07-26 18:24:36 +08:00
generator.add::<_, { N * 4 }>(|buf| {
for (data, buf) in adc_samples
.iter()
.chain(dac_samples.iter())
.zip(buf.chunks_exact_mut(N))
{
let data = unsafe {
core::slice::from_raw_parts(
data.as_ptr() as *const u8,
N,
)
};
buf.copy_from_slice(data)
}
});
2021-06-15 19:22:38 +08:00
// Update telemetry measurements.
telemetry.adcs =
[AdcCode(adc_samples[0][0]), AdcCode(adc_samples[1][0])];
telemetry.dacs =
[DacCode(dac_samples[0][0]), DacCode(dac_samples[1][0])];
2021-06-01 20:49:51 +08:00
// Preserve instruction and data ordering w.r.t. DMA flag access.
fence(Ordering::SeqCst);
});
}
2021-05-05 21:39:33 +08:00
#[idle(resources=[network], spawn=[settings_update])]
2021-03-02 02:48:45 +08:00
fn idle(mut c: idle::Context) -> ! {
loop {
match c.resources.network.lock(|net| net.update()) {
2021-05-26 19:05:54 +08:00
NetworkState::SettingsChanged => {
c.spawn.settings_update().unwrap()
}
NetworkState::Updated => {}
NetworkState::NoChange => cortex_m::asm::wfi(),
2021-03-02 02:48:45 +08:00
}
}
}
2021-05-05 21:39:33 +08:00
#[task(priority = 1, resources=[network, settings, afes])]
2021-03-02 02:48:45 +08:00
fn settings_update(mut c: settings_update::Context) {
2021-05-05 21:39:33 +08:00
let settings = c.resources.network.miniconf.settings();
2021-03-02 02:48:45 +08:00
c.resources.afes.0.set_gain(settings.afe[0]);
c.resources.afes.1.set_gain(settings.afe[1]);
2021-05-04 19:13:44 +08:00
c.resources.settings.lock(|current| *current = *settings);
2021-06-15 19:22:38 +08:00
let target = settings.stream_target.into();
c.resources.network.direct_stream(target);
2021-03-02 02:48:45 +08:00
}
2021-05-05 21:39:33 +08:00
#[task(priority = 1, resources=[network, digital_inputs, settings, telemetry], schedule=[telemetry])]
fn telemetry(mut c: telemetry::Context) {
2021-05-06 22:23:41 +08:00
let mut telemetry: TelemetryBuffer =
c.resources.telemetry.lock(|telemetry| *telemetry);
telemetry.digital_inputs = [
c.resources.digital_inputs.0.is_high().unwrap(),
c.resources.digital_inputs.1.is_high().unwrap(),
];
2021-05-07 19:04:25 +08:00
let (gains, telemetry_period) = c
.resources
.settings
.lock(|settings| (settings.afe, settings.telemetry_period));
2021-05-05 21:39:33 +08:00
2021-05-05 22:16:54 +08:00
c.resources
.network
.telemetry
2021-05-06 18:33:07 +08:00
.publish(&telemetry.finalize(gains[0], gains[1]));
// Schedule the telemetry task in the future.
c.schedule
.telemetry(
c.scheduled
+ SystemTimer::ticks_from_secs(telemetry_period as u32),
)
.unwrap();
}
2021-05-31 20:28:57 +08:00
#[task(priority = 1, resources=[network], schedule=[ethernet_link])]
fn ethernet_link(c: ethernet_link::Context) {
c.resources.network.processor.handle_link();
c.schedule
.ethernet_link(c.scheduled + SystemTimer::ticks_from_secs(1))
.unwrap();
2021-05-31 20:28:57 +08:00
}
#[task(binds = ETH, priority = 1)]
fn eth(_: eth::Context) {
unsafe { hal::ethernet::interrupt_handler() }
}
extern "C" {
// hw interrupt handlers for RTIC to use for scheduling tasks
// one per priority
fn DCMI();
fn JPEG();
fn SDMMC();
}
};