> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lagerdata.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Oscilloscope

> Python SDK for oscilloscope control

The oscilloscope module provides Python interfaces for waveform capture, triggering, and measurements.

## Overview

Use the scope module to control oscilloscopes for analog signal capture, triggering on specific events, and automated measurements.

## Instrument support

The same object and the same calls work for three scopes: a Rigol MSO5000, a
Rigol DS1000Z (DS1054Z, DS1074Z, DS1104Z), and a PicoScope. The PicoScope can be
a 2000, 2000a, 3000a, 4000a or 5000a. The oscilloscope daemon on the box drives all three. The difference is
underneath: a Rigol takes SCPI over USB, and a PicoScope is a USB device with a
vendor SDK.

A DS1000Z differs from the MSO5000 in these ways:

* **Its live view is the screen record.** It has no video output, so each
  streamed frame is the scope's 1200-point record of each channel. Over
  full-speed USB, that is about 2.4 frames a second with three channels on. No
  capture card is needed.
* **It has no digital channels, no cursors on the instrument and no roll mode.**
  The `scope.cursor` methods raise; `lager scope <net> cursor time` and
  `cursor volts` still read the captured samples.
* **Timing measurements read as unavailable for 5 to 25 s after `autoscale()`.**
  The scope reports no frequency or period until its measurements settle.

Know these differences before you write a script for a PicoScope:

* **Measurements are computed, not queried.** No PicoTech API has an equivalent
  of `:MEAS:VPP?`, so the box computes the value from a captured block. One
  capture yields the whole set, so `scope.measurement.all()` costs the same as
  a single `voltage_peak_to_peak()` and reading five values individually costs
  five captures.
* **While running, they describe the capture last streamed out.** The box
  computes a measurement or a cursor reading from the block it last sent to
  subscribers. The numbers therefore agree with the trace on screen. Repeated reads
  change only as fast as captures arrive: two calls between captures return
  the same value. Stopped, they describe the last capture, as a stopped bench
  scope does.
* **`display` and `measurement_cursor` do nothing.** They put a reading on the
  instrument's own screen, and a PicoScope has none. They are accepted and
  ignored so a script written for a Rigol still runs.
* **Some features raise instead of returning.** On-screen cursors, protocol
  triggers, the logic analyzer, and the measurements listed as Rigol-only below raise
  `UnsupportedScopeFeature` naming the gap, rather than returning a
  plausible-looking zero. Catch it if a script needs to run against both.

Channels are letters on a PicoScope (A-D) and numbers on a Rigol (1-4). Every
method accepts either and normalizes, so a script written against one instrument
keeps working against the other.

## Import

```python theme={null}
from lager import Net, NetType
```

## Usage

```python theme={null}
from lager import Net, NetType

# Get scope net
scope = Net.get('ANALOG1', type=NetType.Analog)

# Enable the channel
scope.enable()

# Start capture
scope.start_capture()

# Take measurements
freq = scope.measurement.frequency()
period = scope.measurement.period()

# Stop and disable
scope.stop_capture()
scope.disable()
```

## Methods

### Channel Control

#### `enable()`

Enable the oscilloscope channel.

```python theme={null}
scope.enable()
```

#### `disable()`

Disable the oscilloscope channel.

```python theme={null}
scope.disable()
```

### Capture Control

#### `start_capture()`

Start continuous waveform capture.

```python theme={null}
scope.start_capture()
```

#### `start_single_capture()`

Start single-shot capture (captures one triggered event).

```python theme={null}
scope.start_single_capture()
```

#### `stop_capture()`

Stop waveform capture.

```python theme={null}
scope.stop_capture()
```

#### `force_trigger()`

Trigger now rather than waiting for the configured condition. Use it when a
signal does not cross the trigger level and the script needs a capture anyway.
The scope must be running: a stopped PicoScope refuses it.

```python theme={null}
scope.force_trigger()
```

### Measurements

Access comprehensive measurements through the `measurement` attribute.

#### Availability

Everything below works on a Rigol, except the period area and the delay and
phase measurements. A Rigol MSO5000 on firmware 00.01.03.00.03 rejects those
queries, so they raise `UnsupportedScopeFeature` at once, before anything is
sent. On a PicoScope the box computes measurements from the captured samples,
and these fourteen are the ones it computes:

| Available on both | |
| - | - |
| `voltage_max` | `voltage_min` |
| `voltage_peak_to_peak` | `voltage_average` |
| `voltage_rms` | `voltage_overshoot` |
| `frequency` | `period` |
| `rise_time` | `fall_time` |
| `pulse_width_positive` | `pulse_width_negative` |
| `duty_cycle_positive` | `duty_cycle_negative` |

All other measurements are **Rigol only**, and raise `UnsupportedScopeFeature`
on a PicoScope. These are the flat-top and threshold voltages, preshoot, period
RMS, time-at-extreme, slew rates, edge and pulse counts, area and variance. The
delay and phase measurements are Rigol only too, because they compare two
channels. The box has no command for that on a PicoScope.

On a Rigol, each call is the scope's own reading of its full memory. The query
adds a readout to the scope's measurement bar, and lager clears that readout
again. Readouts you added at the front panel stay. Lager finds the readout in
the live view, so a Rigol with no capture card paired keeps it on screen. `display=True` keeps the
reading on the scope's screen.

Units differ between the two ways of reading the duty cycles and overshoot on
a Rigol. `duty_cycle_positive()`, `duty_cycle_negative()` and
`voltage_overshoot()` return the scope's ratio, such as `0.5` for 50 %.
`all()`, the CLI and the web UI give the same quantities in percent. On a
PicoScope every surface gives percent.

`period`, `frequency`, the pulse widths, the duty cycles, the rise and fall
times and overshoot need a resolvable waveform. On a PicoScope, a period needs
two full cycles in the capture. With fewer, the call raises rather than return
an imprecise guess. Put at least two cycles on screen before you measure timing.

#### `all()`

Every measurement on the net's channel, in one call, keyed `vpp`, `vmax`,
`frequency` and so on. The box computes them from a single capture, so this is
the cheap way to read more than one value. On a Rigol the capture is the
channel's screen record, 1000 points on an MSO5000 and 1200 on a DS1000Z, read
in about 0.2 s. On a PicoScope it is a
captured block.

The screen record limits what it can time on a Rigol. It is too coarse to time
an edge, so rise and fall are left out: call `rise_time()` and `fall_time()`
for the scope's own reading. Period, frequency and the duty cycles need two full cycles
on screen. Overshoot and the duty cycles can differ from the scope's own
readings by a point or more, the record's resolution.

It reads analog channel nets only. It raises `UnsupportedScopeFeature` on a
logic net, and on the scope's instrument net, which names no channel.

```python theme={null}
values = scope.measurement.all()
print(values['vpp'], values['frequency'])
```

#### Voltage Measurements

```python theme={null}
# Basic voltage
vmax = scope.measurement.voltage_max()      # Maximum voltage
vmin = scope.measurement.voltage_min()      # Minimum voltage
vpp = scope.measurement.voltage_peak_to_peak()  # Peak-to-peak
vavg = scope.measurement.voltage_average()  # Average voltage
vrms = scope.measurement.voltage_rms()      # RMS voltage

# Waveform characteristics
vtop = scope.measurement.voltage_flat_top()    # Flat top voltage
vbase = scope.measurement.voltage_flat_base()  # Flat base voltage
vamp = scope.measurement.voltage_flat_amplitude()  # Amplitude

# Thresholds
vupper = scope.measurement.voltage_threshold_upper()
vlower = scope.measurement.voltage_threshold_lower()
vmid = scope.measurement.voltage_threshold_mid()

# Signal quality
overshoot = scope.measurement.voltage_overshoot()
preshoot = scope.measurement.voltage_preshoot()
```

#### Timing Measurements

```python theme={null}
# Frequency and period
freq = scope.measurement.frequency()
period = scope.measurement.period()

# Rise and fall times
rise = scope.measurement.rise_time()
fall = scope.measurement.fall_time()

# Pulse widths
pos_width = scope.measurement.pulse_width_positive()
neg_width = scope.measurement.pulse_width_negative()

# Duty cycles
pos_duty = scope.measurement.duty_cycle_positive()
neg_duty = scope.measurement.duty_cycle_negative()

# Time at voltage extremes
t_vmax = scope.measurement.time_at_voltage_max()
t_vmin = scope.measurement.time_at_voltage_min()

# Slew rates
pos_slew = scope.measurement.positive_slew_rate()
neg_slew = scope.measurement.negative_slew_rate()
```

#### Counting Measurements

```python theme={null}
# Edge counts
pos_edges = scope.measurement.positive_edge_count()
neg_edges = scope.measurement.negative_edge_count()

# Pulse counts
pos_pulses = scope.measurement.positive_pulse_count()
neg_pulses = scope.measurement.negative_pulse_count()
```

#### Area Measurements

```python theme={null}
area = scope.measurement.waveform_area()
period_area = scope.measurement.waveform_period_area()
```

#### Statistical Measurements

```python theme={null}
variance = scope.measurement.variance()
pvrms = scope.measurement.voltage_rms_period()  # Period RMS voltage
```

#### Delay and Phase Measurements

```python theme={null}
# Delay measurements (between channels)
rr_delay = scope.measurement.delay_rising_rising_edge()
rf_delay = scope.measurement.delay_rising_falling_edge()
fr_delay = scope.measurement.delay_falling_rising_edge()
ff_delay = scope.measurement.delay_falling_falling_edge()

# Phase measurements
rr_phase = scope.measurement.phase_rising_rising_edge()
rf_phase = scope.measurement.phase_rising_falling_edge()
fr_phase = scope.measurement.phase_falling_rising_edge()
ff_phase = scope.measurement.phase_falling_falling_edge()
```

#### Measurement Options

Most measurements accept optional parameters:

```python theme={null}
# Keep measurement displayed on scope
freq = scope.measurement.frequency(display=True)

# Enable cursor measurement mode
vpp = scope.measurement.voltage_peak_to_peak(measurement_cursor=True)
```

## Streaming

Streaming works on both makes. An MSO5000 streams from the live view paired with
it by `lager nets set-capture`. Until one is paired, `stream_start()`,
`stream_frames()` and `stream_capture()` raise `UnsupportedScopeFeature`.
A DS1000Z streams its screen record and needs no pairing. `capture()` reads the
scope's own record and needs no live view.

### `stream_start(channel, volts_per_div, time_per_div, trigger_level, trigger_slope, capture_mode, coupling, channels)`

Start streaming acquisition. Every parameter is optional. Only the settings you give are
applied, so a later call with a new trigger level keeps the coupling set earlier.

**Parameters:**

* `channel` (str): Channel to enable - `"A"`, `"B"`, `"1"`, `"2"`
* `volts_per_div` (float): Vertical scale
* `time_per_div` (float): Horizontal scale in seconds
* `trigger_level` (float): Trigger level in volts
* `trigger_slope` (str): `"rising"`, `"falling"`, `"either"`
* `capture_mode` (str): `"auto"`, `"normal"`, `"single"`
* `coupling` (str): `"dc"`, `"ac"`
* `channels` (list): Several channels for a multi-channel capture. With `channel` as well, both are enabled. With neither, the net's own channel is used

> [!NOTE]
>
> `"gnd"` is accepted by the API but refused by 2000-series units, which have no
> ground switch: `ps2000_set_channel` carries a single flag for coupling. Use
> `"ac"` to block the DC component, or unplug the probe to see where zero sits.

```python theme={null}
scope.stream_start(
    channel="A",
    volts_per_div=1.0,
    time_per_div=0.001,
    trigger_level=0.5,
    trigger_slope="rising",
    capture_mode="auto",
    coupling="dc"
)
```

### `stream_stop()`

Stop streaming acquisition.

```python theme={null}
scope.stream_stop()
```

### `stream_capture(output=None, duration=1.0, samples=None, timeout=None)`

Capture for `duration` seconds, writing a CSV.

**Parameters:**

* `output` (str): Output file path. Omit it to count samples without writing a file
* `duration` (float): Capture duration in seconds
* `samples` (int): Cap on rows per channel (optional). A cap, not a target: the capture still stops at `duration`
* `timeout` (float): Seconds to wait for a capture before giving up (optional). Defaults to `duration`

Returns a summary rather than the samples themselves — `captures`,
`samples_per_channel`, `rows` and `output`. The CSV columns are `capture`,
`channel`, `sample_index`, `time_ns` and `voltage`, the same layout
`lager scope stream capture` writes.

Each capture the scope takes in that time is recorded once. The scope must be
running already, from `stream_start()`, `start_capture()` or
`start_single_capture()`. A stopped scope raises at once, rather than after
`duration` with nothing recorded. A relative `output` path is relative to the
script's working directory on the box.

```python theme={null}
result = scope.stream_capture(
    output="waveform.csv",
    duration=5.0
)
print(result['samples_per_channel'], "samples per channel")
```

### `capture(timeout)`

One triggered capture, decoded into a frame with the samples included. It has
the same frame interface as `stream_frames()`. On a Rigol the samples are the
scope's exact record, read over SCPI.

```python theme={null}
frame = scope.capture()
print(frame.sample_rate_hz, frame.volts('A').max())
```

### `stream_frames(count, timeout)`

Yield captures as decoded frames instead of writing a file. This is the
zero-copy path: a frame's `counts()` is a view over the received buffer, so
nothing is converted until asked for. Use it when the samples go into numpy
rather than onto disk.

Each frame is a new capture, never one it yielded before. When no capture
arrives within `timeout`, it raises `ScopeDaemonTimeout`. Start the scope first,
and in normal mode make sure the signal crosses the trigger level.

**Parameters:**

* `count` (int): Number of captures to yield (default 1)
* `timeout` (float): Seconds to wait for each capture (default 10)

```python theme={null}
for frame in scope.stream_frames(count=10):
    volts = frame.volts('A')          # numpy array, converted on request
    times = frame.time_axis()         # seconds relative to the trigger
    print(frame.sample_rate_hz, volts.max())
```

> [!NOTE]
>
> `volts()` gives the voltage at the probe tip. With a 10x probe it reports the
> signal at the tip, not the tenth of it that reaches the BNC. `volts_per_div`,
> the trigger level and the measurement functions are also at the tip. Set the
> ratio with `set_channel_probe()` before you capture. A 2000-series unit starts
> at 10x, and the 2000a, 3000a, 4000a and 5000a families start at 1x.

## Complete Example

```python theme={null}
from lager import Net, NetType
import time

def measure_pwm_signal():
    """Measure PWM signal characteristics."""

    # Get scope net
    pwm_net = Net.get('PWM_OUTPUT', type=NetType.Analog)

    try:
        # Enable channel
        pwm_net.enable()

        # Configure trigger
        pwm_net.trigger_settings.set_mode_normal()
        pwm_net.trigger_settings.edge.set_source(pwm_net)
        pwm_net.trigger_settings.edge.set_slope_rising()
        pwm_net.trigger_settings.edge.set_level(1.65)  # 50% of 3.3V

        # Start capture
        pwm_net.start_capture()
        time.sleep(0.5)  # Wait for stable capture

        # Take measurements
        frequency = pwm_net.measurement.frequency()
        period = pwm_net.measurement.period()

        print(f"PWM Frequency: {frequency:.2f} Hz")
        print(f"PWM Period: {period*1000:.3f} ms")

        # Calculate duty cycle from pulse width if available
        # ...

    finally:
        pwm_net.stop_capture()
        pwm_net.disable()

if __name__ == "__main__":
    measure_pwm_signal()
```

### Trace Settings

Configure vertical and horizontal scale through `trace_settings`:

```python theme={null}
# Vertical scale (V/div)
scope.trace_settings.set_volts_per_div(1.0)
volts = scope.trace_settings.get_volts_per_div()

# Vertical offset
scope.trace_settings.set_volt_offset(0.5)
offset = scope.trace_settings.get_volt_offset()

# Horizontal scale (s/div)
scope.trace_settings.set_time_per_div(0.001)  # 1ms/div
time_scale = scope.trace_settings.get_time_per_div()  # 0.001024 -- see below

# Horizontal offset
scope.trace_settings.set_time_offset(0.0)
time_offset = scope.trace_settings.get_time_offset()
```

> [!NOTE]
>
> Time/div is one tenth of the capture, as on a ten-division screen, so
> `set_time_per_div(0.001)` asks for a 10 ms window.
>
> `get_time_per_div()` returns the scale in use, which is rarely the one asked
> for. A scope samples at a fixed ladder of intervals, each twice the last. The
> box rounds a request to the closest one: 1 ms/div on a 2204A is really
> 1.024 ms/div. Read it back if you need the exact window. Better still, use
> `get_sample_rate()` and the frame's own time axis, not arithmetic on the value
> you set.
>
> The fastest screen a unit can reach depends on the block depth and the maximum
> sample rate, because the two multiply out to the window. A 2204A at
> 100 MS/s over 8000 samples bottoms out at 8 us/div, and asking for anything
> faster gets you that. Enabling a second channel halves the buffer, which makes
> the fastest screen faster rather than slower.

> [!NOTE]
>
> `set_time_offset()` moves the capture window in time relative to the trigger.
> Use it to look at signal past the left or right edge of one capture. Positive
> values look forward, at signal later than the trigger; negative values look
> back before it.
>
> On a PicoScope the travel is one window each way. The window is a block, and a
> block is all the scope holds. So the box clamps the offset where the capture is
> entirely before or entirely after the trigger. Setting it re-arms the scope,
> because a window somewhere else must be captured to be seen. The offset then
> applies to every capture until you change it.
>
> On a Rigol the scope moves its own window, as its horizontal position knob does,
> and a stopped scope stays stopped.

### Advanced Trigger Settings

Access advanced trigger configuration through `trigger_settings`:

```python theme={null}
# Trigger mode
scope.trigger_settings.set_mode_auto()
scope.trigger_settings.set_mode_normal()
scope.trigger_settings.set_mode_single()
mode = scope.trigger_settings.get_mode()

# Trigger coupling (Rigol only -- a filter on the trigger path itself, which
# a PicoScope does not have. For a PicoScope, set the channel's input coupling
# with scope.set_channel_coupling('dc') instead.)
scope.trigger_settings.set_coupling_DC()
scope.trigger_settings.set_coupling_AC()
scope.trigger_settings.set_coupling_low_freq_reject()
scope.trigger_settings.set_coupling_high_freq_reject()
coupling = scope.trigger_settings.get_coupling()

# Edge trigger settings
scope.trigger_settings.edge.set_source(scope)
scope.trigger_settings.edge.set_slope_rising()
scope.trigger_settings.edge.set_slope_falling()
scope.trigger_settings.edge.set_slope_both()
scope.trigger_settings.edge.set_level(1.65)

# Get status
status = scope.trigger_settings.get_status()
```

### Cursor Control

Access cursor functions through the `cursor` attribute.

> [!NOTE]
>
> `scope.cursor.*` is **Rigol only**. These are markers on the instrument's own
> display, positioned in screen coordinates and read back over SCPI. A PicoScope
> has no display, so every method here raises `UnsupportedScopeFeature` on one.
>
> Cursors over the *captured samples* are a different thing, and a PicoScope has
> them. You place them with a time and a voltage, not a pixel, so they have
> their own API. Use
> `lager scope <net> cursor time <t1> <t2>`, the same `cursor` verb in the web
> UI's console, or `set_cursors()` / `measure_cursors()` on the driver:
>
> ```python theme={null}
> scope.set_cursors(time=(0.0, 1e-3))
> readings = scope.measure_cursors()["readings"]
> readings["frequency"]       # 1/dt, so a pair a cycle apart reads the frequency
> readings["trace_delta_v"]   # the trace's voltage change between them
> ```
>
> The box holds the pair. Cursors placed from a script, the terminal CLI or the
> web UI's console are the same two markers, and the web UI draws them.
>
> These calls work on a PicoScope net and on a Rigol MSO5000 net. On a Rigol, the
> sample cursor calls, `get_sample_rate()` and `capabilities()` go to the box driver that
> `lager scope` uses. A script and the CLI read the same cursors.

```python theme={null}
# Set cursor positions
scope.cursor.set_a(x=100, y=50)
scope.cursor.set_b(x=200, y=50)

# Get cursor positions
ax, ay = scope.cursor.get_a()
bx, by = scope.cursor.get_b()

# Move cursors relatively
scope.cursor.move_a(x_del=10, y_del=5)
scope.cursor.move_b(x_del=-10, y_del=0)

# Read cursor measurements
x_delta = scope.cursor.x_delta()  # Time difference
y_delta = scope.cursor.y_delta()  # Voltage difference
inv_x = scope.cursor.frequency()  # Frequency

# Get individual values
ax_val = scope.cursor.a_x()
ay_val = scope.cursor.a_y()
bx_val = scope.cursor.b_x()
by_val = scope.cursor.b_y()

# Hide cursor
scope.cursor.hide()
```

## Supported Hardware

| Manufacturer | Model Series | Features |
| - | - | - |
| Rigol | MSO5000 | 2 or 4 analog channels (by model) + 16 digital, edge and SPI triggers, cursors, measurements on the scope's full memory |
| Rigol | DS1000Z (DS1054Z, DS1074Z, DS1104Z) | 4 analog channels, edge trigger with holdoff, autoscale, measurements on the scope's full memory, streaming from the 1200-point screen record |
| PicoScope | 2000, 2000a, 3000a, 4000a, 5000a | Capture control, scaling, edge trigger, 14 computed measurements, continuous streaming |

Both makes stream. An MSO5000 streams once a live view is paired with
`lager nets set-capture`; a DS1000Z streams without one.

The box detects an attached PicoScope's channel count, voltage ranges,
bandwidth, memory depth and ADC resolution at runtime. Models within a series
therefore work without configuration. Read them with `scope.capabilities()`.

## Notes

* Use `NetType.Analog` for oscilloscope channels (1-4)
* Use `NetType.Logic` for digital channels (D0-D15) on MSO scopes
* An MSO5000 streams only once a live view is paired with `lager nets set-capture`
* Configure trigger before starting capture for reliable measurements
* Measurement methods return `float` on success, or `None` if the measurement is invalid (e.g., no signal, no trigger, wrong channel). On Rigol hardware, the instrument returns 9.9E+37 for invalid measurements, which is automatically converted to `None`.
* For protocol triggering (UART, I2C, SPI, CAN), see the [Logic Analyzer](https://docs.lagerdata.com/source/reference/python/logic.md) documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.