Skip to main content

instrument/classes/
fgen.rs

1use instrument_core::error::Result;
2use instrument_core::scpi::ScpiSession;
3use instrument_core::InstrumentSession;
4
5/// Waveform shape for function generators.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Waveform {
8    Sine,
9    Square,
10    Ramp,
11    Pulse,
12    Noise,
13    Dc,
14}
15
16impl Waveform {
17    pub(crate) fn scpi_name(self) -> &'static str {
18        match self {
19            Self::Sine => "SIN",
20            Self::Square => "SQU",
21            Self::Ramp => "RAMP",
22            Self::Pulse => "PULS",
23            Self::Noise => "NOIS",
24            Self::Dc => "DC",
25        }
26    }
27}
28
29/// Function / arbitrary waveform generator session view.
30pub struct FunctionGenerator {
31    session: InstrumentSession,
32}
33
34impl FunctionGenerator {
35    pub fn new(session: InstrumentSession) -> Self {
36        Self { session }
37    }
38
39    pub fn session(&self) -> &InstrumentSession {
40        &self.session
41    }
42
43    pub fn session_mut(&mut self) -> &mut InstrumentSession {
44        &mut self.session
45    }
46
47    /// Sets the output waveform.
48    pub fn set_waveform(&mut self, waveform: Waveform) -> Result<()> {
49        self.session
50            .scpi_mut()
51            .write(&format!(":SOUR:FUNC {}", waveform.scpi_name()))
52    }
53
54    /// Sets output frequency in hertz (SI).
55    pub fn set_frequency(&mut self, hz: f64) -> Result<()> {
56        self.session.scpi_mut().write(&format!(":SOUR:FREQ {hz}"))
57    }
58
59    /// Sets peak-to-peak amplitude in volts (SI).
60    pub fn set_amplitude(&mut self, vpp: f64) -> Result<()> {
61        self.session.scpi_mut().write(&format!(":SOUR:VOLT {vpp}"))
62    }
63
64    /// Sets DC offset in volts (SI).
65    pub fn set_offset(&mut self, volts: f64) -> Result<()> {
66        self.session
67            .scpi_mut()
68            .write(&format!(":SOUR:VOLT:OFFS {volts}"))
69    }
70
71    /// Enables or disables the output.
72    pub fn output_enable(&mut self, enabled: bool) -> Result<()> {
73        let state = if enabled { "ON" } else { "OFF" };
74        self.session.scpi_mut().write(&format!(":OUTP {state}"))
75    }
76
77    /// Reads the configured frequency in hertz (SI).
78    pub fn read_frequency(&mut self) -> Result<f64> {
79        let resp = self.session.scpi_mut().query(":SOUR:FREQ?")?;
80        ScpiSession::parse_f64(&resp)
81    }
82}