A 25 Hz square wave can give an integrator a nearly triangular output, yet adding just +20 mV to the input can make that triangle walk toward the negative supply. Build the circuit around a Texas Instruments OPA197, measure the walk in volts per second and add a 1 MΩ resistor across the feedback capacitor. The triangle still swings at 25 Hz, but its average voltage settles. Remove that resistor and check that the walk comes back.

Why the triangle walks

An operational amplifier (op amp) drives its output to keep its two input voltages close while negative feedback is working. Here the noninverting input is held at circuit ground, G0. The inverting input, SUM, stays near G0 in the usable part of the waveform. The voltage at VIN then sets the current through the input resistor RIN. With only the capacitor CF in the feedback path, most of that current charges the capacitor. A positive VIN makes VOUT fall.

For an ideal inverting stage, the change in output since a starting time t0 equals the negative area under VIN divided by RINCF. The capacitor's starting charge sets VOUT(t0). A square wave that spends equal time at +0.100 V and −0.100 V gives opposite slopes of 10 V/s and a nominal 0.200 V peak-to-peak triangle at 25 Hz. Peak-to-peak, written Vpp, means the difference between the highest and lowest voltages. Shift the input levels to +0.120 and −0.080 V and the slopes become −12 and +8 V/s. Each 40 ms cycle then leaves the output 80 mV lower, equivalent to a −2 V/s average drift.

The average voltage of a waveform is its direct-current (DC) component. The 1 MΩ resistor RF gives the current a path at DC. It puts an opposing term proportional to VOUT into the capacitor equation. At a repeatable periodic state the average capacitor current is zero, so the average output is −(RF/RIN) times the input mean. At +20 mV that is −0.20 V. Any initial error from the periodic waveform decays with the time constant RFCF = 100 ms, so 0.8 s gives roughly eight time constants with nominal components. The resulting corner is 1/(2πRFCF) ≈ 1.59 Hz. A corner is the characteristic frequency where the simple low- and high-frequency behaviors start to cross over. Keeping the 25 Hz square well above it preserves a near-triangle. For equal 20 ms halves its steady swing is 2(RF/RIN)(0.100 V) × tanh[0.040 s/(4RFCF)] ≈ 0.199 Vpp.

An OPA197 inverting integrator has a permanent 100 nanofarad capacitor, an optional one megohm resistor and a separate reset branch across output and inverting input. The drawing shows independent positive and negative bench supplies and three calculated output traces.
The permanent capacitor, removable RF branch and normally open reset branch share the same two nodes. The calculated plot gives the two capacitor-only curves the same initial voltage and draws the parallel-RF curve after settling. The offset-restore stage would repeat the falling trend from its own initial voltage. The drawing omits the DHO804 power adapter and separate chassis earth lead; connect them as described before adding any input or output cables. Full-size PNG · Editable SVG

Build the feedback network and split supply

Before connecting any input or output cables, connect the RIGOL DHO804's rear Ground Terminal to earth ground using the supplied ground cable, as required by the DHO800 User Guide. Its Type-C power input does not ground the instrument through the power cord. Use the supplied power adapter. Keep the AFG1022 and SPD3303X protective earth connections intact. The probe ground clips and any signal cable shields share G0 as described below; they do not replace this required chassis earth lead.

Use OPA197IDBVR in Texas Instruments' five-pin DBV small-outline transistor package, also called SOT-23-5, on a matching soldered breakout. Use the manufacturer's top-view pin drawing and find pin 1 before adding power. A generic SOIC-8 adaptor has a different pin map. Use a nearby RIN of 100 kΩ and an RF of 1 MΩ, each Vishay MRS25 ±1%, and the nonpolar Vishay Roederstein MKT1820410015 polyester film CF (100 nF, ±10%, 100 VDC, 10 mm lead spacing). Use a short, clean layout around the inverting node. Use a 1 kΩ MRS25 in series with a momentary normally open switch for reset and two 100 nF nonpolar ceramic supply bypass capacitors close to the amplifier.

U1 pinConnect toLocal component
1 OUTVOUT and scope CH2 tipOne end of each feedback branch
2 V−−5 V100 nF to G0
3 +ING0Direct connection
4 −INSUM100 kΩ from VIN and the other end of each feedback branch
5 V++5 V100 nF to G0

Configure a SIGLENT SPD3303X with CH1 and CH2 independent (internal series and parallel modes off), each at 5.00 V and 20 mA with both outputs off for wiring. This supply's independent outputs are isolated from ground. Link CH1− to CH2+ at G0, take +5 V from CH1+ and −5 V from CH2−. With a handheld DC voltmeter referenced to G0, verify the polarity and 4.90–5.10 V magnitude of both rails. When running, verify both channels show constant-voltage mode. The 10 V total is within the TI recommended 4.5–36 V total range. The 20 mA setpoint limits the bench supply and the ±2.80 V output screen leaves margin to the rails for this lightly loaded circuit. Keep protective earth connected on all instruments.

Take VIN from the Tektronix AFG1022 CH1 BNC center conductor before RIN. A BNC connector carries the signal on its center conductor and the return on its shell. Connect its shell and both RIGOL DHO804 probe ground clips only to G0. Put the CH1 tip at VIN and the CH2 tip at VOUT. No scope clip goes on a supply rail, SUM or VOUT. Use the PVP2350 probes at 1× with matching channel scale factors, DC coupling and the scope's high-impedance inputs. Avoid probing SUM, where leakage and capacitance may change what the circuit does. Connect RF and the separate 1 kΩ/reset-switch branch between SUM and VOUT as drawn. In the three capacitor-only stages the RF link is open.

Record four captures with one controlled change at a time

  1. Set the signal. Choose a 25 Hz, 50% duty-cycle square on AFG1022 CH1. Duty cycle is the fraction of each period spent high. Set 0.200 Vpp and the High Z load display, which tells the generator to display the voltage for a high-impedance load. Its physical output resistance is still nominally 50 Ω. Analyze the voltage measured at VIN, after that resistance. With both scope channels DC-coupled, touch each probe tip to G0 at its intended scale and attenuation setting. Check that CH1 averages within ±2 mV of zero before returning its tip to VIN. If it does not, correct the scope setup before trying to resolve a ±4 mV input mean. Use a CH1 setting around 50 mV/div and keep both plateaus visible. Use a CH1 rising-edge trigger near the waveform midpoint. Start near 50–100 ms/div and adjust from the actual stored timestamps and visible range. Set memory depth to 10 kpts with both channels active and use real-time acquisition, with no trace averaging.
  2. Make the zero and offset records. Start with RF disconnected. With the source and both rails on, hold S1 approximately 0.25 s, then release and start a fresh acquisition. The 1 kΩ branch has nominal R×C = 0.10 ms while closed and gives a temporary DC path. Set 0 mV generator offset for zero.csv. Then set +20 mV without changing square amplitude or frequency, repeat the reset and capture offset.csv. Save captures that start after release. For the biased capacitor-only stages finish the acquisition in about a second after release, and stop/reset whenever VOUT nears ±2.80 V. Check the local output window on the scope before exporting. A record with a flat end where the output ran out of swing cannot show the integration slope.
  3. Add the DC path. Switch off the AFG output and both rails before closing the RF jumper. Verify that the stored voltage and rails have returned near G0 before touching wiring. Restore power, reset, release and wait at least 0.8 s at the unchanged +20 mV setting before starting an acquisition for feedback.csv. Use a narrower CH2 scale if needed to resolve the centered ripple and repeat the grounded-tip zero check after changing the setting. Record center and ripple with the smallest range that captures the full trace.
  4. Restore capacitor-only feedback. Switch off source and rails, verify the circuit has discharged, and reopen the RF jumper. Restore power and repeat the same short reset/release acquisition at +20 mV for restore.csv. Hold reset or switch off the source and rails after measuring. The original slope can return even though the new capacitor starts at a different voltage after reset.
  5. Save real sample pairs. On the DHO804, use Storage → Save → Choose → Save Wave, select Memory and save as comma-separated values (CSV). Inspect the headings and time units. Retain aligned CH1/CH2 sample values and original relative seconds. Normalize the file to exactly time_s,vin_v,vout_v with both voltages in volts. Aim for about 12–22 clean cycles, with at least eight complete periods and consecutive samples at most 0.50 ms apart. Trim only leading or trailing idle/reset intervals if needed, keeping sample pairs and gaps inside the retained data as acquired. Keep all four independent captures and the original exports.

Compare slopes and centers in the same units

StageInput meanOutput prediction
zero0 mV0 V/s, arbitrary center
offset+20 mV−2 V/s while in range
feedback+20 mV0 V/s near −0.20 V
restore+20 mV−2 V/s again

These are calculations with nominal component values. Even the capacitor-only zero record can drift. Amplifier input offset (the voltage error referred to the input), input bias current, leakage through the board or switch, and any source or scope offset can all leave a residual. The Texas Instruments offset and bias-current tables refer to specific supply, common-mode and temperature conditions. With the clean capacitor, Vishay specifies more than 15,000 MΩ insulation resistance for this value and rating under its test conditions. An illustrative purely resistive 15 GΩ leakage path would pass about 0.19 nA at 2.8 V, far below the 0.20 µA input-current change caused by +20 mV across 100 kΩ. Dirt or damp surfaces around SUM can dominate that insulation figure. Example slopes also move with the film capacitor's ±10% tolerance. Use the zero trace as the local slope reference and calculate the expected slope change from the measured difference in input means.

The program derives rising and falling crossings from the VIN midpoint, checks each complete period and both plateaus, and integrates both channels over the same rising-edge-to-rising-edge windows. It linearly interpolates boundary samples and applies the trapezoid rule on the actual timestamps. Each complete cycle contributes one average and one time midpoint, so the output slope is a fit to cycle means. The displayed output voltage is the mean of those cycle means. Comparing it with the DC-gain calculation is meaningful for the settled feedback run. The other three absolute centers depend on starting charge and when acquisition began.

The setup screens accept 39–41 ms periods, 47.5–52.5% duty and 0.180–0.220 V plateau span. Input means must stay within ±4 mV for zero and between +15 and +25 mV for the biased records, whose means must match one another within 3 mV. The program also checks both output half-cycle changes for their expected inverting directions and plausible size. The two capacitor-only changes must follow the negative nominal slope within a tolerance of 23% of the predicted change plus 0.12 V/s, and their measured drifts must agree within 0.45 V/s. The feedback trace must fit a slope within ±0.18 V/s and a mean within 45 mV of the predicted center. These are experiment-specific consistency screens. For unresolved data, first check source offset from CH1, rail and ground connections, scope ranges, reset timing and RF continuity with the fixture off. A successful run supports the comparison in the recorded windows without determining exact capacitance, op-amp input offset or time to reach a rail.

Run the complete offline analyzer

Use Python 3.10 or later with its standard library. Download the editable figure, program, tests and four synthetic captures, or copy the complete program below. Start from the blank CSV header for actual readings. The first command uses bench files you supply. The second uses mathematical traces bundled in the archive. Exit code 0 means the four records met the screens, 1 means the experiment is unresolved and 2 indicates a data or command error. The synthetic data are examples of analysis behavior.

python3 integrator_drift.py zero.csv offset.csv feedback.csv restore.csv
python3 integrator_drift.py synthetic/zero.csv synthetic/offset.csv synthetic/feedback.csv synthetic/restore.csv
python3 -m unittest -v test_integrator_drift
#!/usr/bin/env python3
"""Qualify four raw records of the same OPA197 integrator experiment."""
import argparse
from bisect import bisect_left, bisect_right
import csv
from dataclasses import dataclass
from hashlib import sha256
import io
from math import isfinite
from pathlib import Path
from statistics import mean, median
import sys

HEADER = ["time_s", "vin_v", "vout_v"]
STAGES = ("zero", "offset", "feedback", "restore")
MAX_BYTES = 2_000_000
MAX_ROWS = 30_000
EPS = 1e-10
RIN = 100_000
CAP = 100e-9
RF = 1_000_000


class Unresolved(Exception):
    """Usable file format, but the capture does not qualify."""


def screen(condition, reason):
    if not condition:
        raise Unresolved(reason)


def between(value, low, high):
    return low - EPS <= value <= high + EPS


def read_capture(path):
    with path.open("rb") as handle:
        data = handle.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise ValueError(f"file exceeds {MAX_BYTES} bytes")
    rows = csv.reader(io.StringIO(data.decode("utf-8-sig"), newline=""), strict=True)
    if next(rows, None) != HEADER:
        raise ValueError("expected time_s,vin_v,vout_v header")
    t, vi, vo = [], [], []
    for number, row in enumerate(rows, 2):
        if number > MAX_ROWS + 1:
            raise ValueError(f"file exceeds {MAX_ROWS} samples")
        if len(row) != 3:
            raise ValueError(f"line {number}: expected three values")
        try:
            second, input_v, output_v = map(float, row)
        except ValueError as error:
            raise ValueError(f"line {number}: invalid number") from error
        if not all(map(isfinite, (second, input_v, output_v))):
            raise ValueError(f"line {number}: nonfinite sample")
        if abs(second) > 10:
            raise ValueError(f"line {number}: time must be relative and within ±10 s")
        if t and second <= t[-1]:
            raise ValueError(f"line {number}: time must strictly increase")
        t.append(second)
        vi.append(input_v)
        vo.append(output_v)
    if len(t) < 2:
        raise ValueError("expected at least two samples")
    digest = sha256(data).hexdigest()
    # Parsed values are compared too, so reformatting an identical recording fails.
    return (t, vi, vo), digest


def interpolate(t, values, instant):
    i = bisect_left(t, instant)
    if t[i] == instant:
        return values[i]
    share = (instant - t[i - 1]) / (t[i] - t[i - 1])
    return values[i - 1] + share * (values[i] - values[i - 1])


def cycle_average(t, values, start, stop):
    start_i, stop_i = bisect_right(t, start), bisect_left(t, stop)
    previous_time, previous_v = start, interpolate(t, values, start)
    area = 0.0
    for i in range(start_i, stop_i):
        area += (t[i] - previous_time) * (previous_v + values[i]) / 2
        previous_time, previous_v = t[i], values[i]
    last_v = interpolate(t, values, stop)
    area += (stop - previous_time) * (previous_v + last_v) / 2
    return area / (stop - start)


def midpoint_crossings(t, values, threshold):
    rises, falls = [], []
    for previous, current, before, after in zip(t, t[1:], values, values[1:]):
        if before < threshold <= after:
            target = rises
        elif before >= threshold > after:
            target = falls
        else:
            continue
        target.append(previous + (current - previous) * (threshold - before) / (after - before))
    return rises, falls


def plateau(t, values, start, end):
    points = [interpolate(t, values, start + fraction * (end - start))
              for fraction in (0.15, 0.40, 0.60, 0.85)]
    screen(max(points) - min(points) <= 0.007 + EPS, "square plateaus vary within a half-cycle")
    return median(points)


@dataclass
class Capture:
    cycles: int
    input_vpp: float
    input_mean: float
    output_mean: float
    slope: float


def summarize(samples):
    t, vi, vo = samples
    screen(max(right - left for left, right in zip(t, t[1:])) <= 0.00050 + EPS,
           "sample interval exceeds 0.50 ms")
    screen(max(map(abs, vi)) <= 0.20 + EPS, "input voltage exceeds the fixture screen")
    screen(max(map(abs, vo)) <= 2.80 + EPS, "output voltage exceeds ±2.80 V")
    midpoint = (max(vi) + min(vi)) / 2
    rises, falls = midpoint_crossings(t, vi, midpoint)
    screen(8 <= len(rises) - 1 <= 30, "expected 8–30 complete cycles")
    centers, input_means, output_means, spans = [], [], [], []
    for left, right in zip(rises, rises[1:]):
        period = right - left
        screen(between(period, 0.039, 0.041), "input period is outside 39–41 ms")
        fall_i = bisect_right(falls, left)
        screen(bisect_left(falls, right) - fall_i == 1, "expected one falling crossing per cycle")
        middle = falls[fall_i]
        screen(between((middle - left) / period, 0.475, 0.525), "input duty is outside 47.5–52.5%")
        high = plateau(t, vi, left, middle)
        low = plateau(t, vi, middle, right)
        span = high - low
        screen(between(span, 0.180, 0.220), "input span is outside 0.180–0.220 V")
        start_v, turn_v, end_v = (interpolate(t, vo, x) for x in (left, middle, right))
        screen(between(start_v - turn_v, 0.085, 0.34) and between(end_v - turn_v, 0.085, 0.34),
               "output half-cycle changes do not have the expected inverting triangle sense or size")
        centers.append((left + right) / 2)
        input_means.append(cycle_average(t, vi, left, right))
        output_means.append(cycle_average(t, vo, left, right))
        spans.append(span)

    screen(max(input_means) - min(input_means) <= 0.004 + EPS, "cycle input means vary too much")
    screen(max(spans) - min(spans) <= 0.008 + EPS, "input span varies too much")
    center_t, center_v = mean(centers), mean(output_means)
    slope = sum((x - center_t) * (y - center_v) for x, y in zip(centers, output_means))
    slope /= sum((x - center_t) ** 2 for x in centers)
    residual = max(abs(y - (center_v + slope * (x - center_t))) for x, y in zip(centers, output_means))
    screen(residual <= 0.035 + EPS, "output cycle means are not consistent with the fitted trend")
    return Capture(len(centers), mean(spans), mean(input_means), center_v, slope)


def qualify(rows):
    zero, offset, feedback, restore = rows
    screen(abs(zero.input_mean) <= 0.004 + EPS, "zero input mean must be within ±4 mV")
    biased = [row.input_mean for row in rows[1:]]
    screen(all(between(v, 0.015, 0.025) for v in biased),
           "biased input means must be 15–25 mV")
    screen(max(biased) - min(biased) <= 0.003 + EPS, "offset match exceeds 3 mV")
    spans = [row.input_vpp for row in rows]
    screen(max(spans) - min(spans) <= 0.012 + EPS, "drive amplitudes differ by more than 12 mV")
    screen(abs(zero.slope) <= 0.55 + EPS, "zero control drifts faster than 0.55 V/s")

    for stage, row in (("offset", offset), ("restore", restore)):
        drive_change = row.input_mean - zero.input_mean
        predicted = -drive_change / (RIN * CAP)
        measured = row.slope - zero.slope
        tolerance = 0.23 * abs(predicted) + 0.12
        screen(between(measured, predicted - tolerance, predicted + tolerance) and row.slope < -0.8,
               f"{stage} drift does not follow the signed nominal RC prediction")
    screen(abs(offset.slope - restore.slope) <= 0.45 + EPS, "restored drift differs by more than 0.45 V/s")
    screen(abs(feedback.slope) <= 0.18 + EPS, "feedback slope exceeds ±0.18 V/s")
    expected_center = -(RF / RIN) * feedback.input_mean
    screen(abs(feedback.output_mean - expected_center) <= 0.045 + EPS,
           "feedback center differs from the nominal DC prediction by more than 45 mV")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for stage in STAGES:
        parser.add_argument(stage, type=Path, metavar=f"{stage}.csv")
    args = parser.parse_args()
    samples, hashes = [], set()
    for stage in STAGES:
        try:
            record, digest = read_capture(getattr(args, stage))
            if digest in hashes or record in samples:
                raise ValueError("identical capture supplied for more than one stage")
            samples.append(record)
            hashes.add(digest)
        except UnicodeError:
            print(f"DATA ERROR: {stage}: expected UTF-8 CSV", file=sys.stderr)
            return 2
        except (OSError, ValueError, csv.Error) as error:
            print(f"DATA ERROR: {stage}: {error}", file=sys.stderr)
            return 2

    try:
        rows = []
        for stage, record in zip(STAGES, samples):
            try:
                row = summarize(record)
            except Unresolved as error:
                raise Unresolved(f"{stage}: {error}") from error
            rows.append(row)
            print(f"{stage:>8}  {row.cycles:2d} cycles  input {1e3 * row.input_mean:+6.1f} mV"
                  f"  output {row.output_mean:+.3f} V  drift {row.slope:+.2f} V/s")
        qualify(rows)
    except Unresolved as error:
        print(f"UNRESOLVED: {error}", file=sys.stderr)
        return 1
    print("QUALIFIED: added DC accumulated, feedback bounded the center, and removal restored drift.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Predict the effect of halving the feedback resistor

If VIN still averages +20 mV and RF is changed from 1 MΩ to 500 kΩ, where would the output be centered, how quickly would the starting-voltage error decay, and where would the new corner be?

Show the calculation

The nominal DC gain becomes −5, so the center becomes −0.10 V. The 100 nF capacitor gives a 50 ms time constant, half the original. The corner doubles to about 3.18 Hz, so the lower feedback resistance also pushes the useful integration band upward.

Sources and related experiments