Swap two capacitors in a Sallen–Key low-pass filter and measure what changes. The two parts keep the same product, so the circuit has the same calculated natural frequency. Their positions set the damping. Around 2.225 kHz, one arrangement can pass a larger sine wave than it receives while the other strongly attenuates it.
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.
A Sallen–Key low-pass filter uses an amplifier and a network of two resistors and two capacitors. The amplifier here is a voltage follower. Its output follows its non-inverting input because the output is wired directly to the inverting input. The feedback capacitor brings part of the changing output back to the midpoint of the two resistors. The other capacitor leads from the non-inverting input to ground. Changing their positions changes how those paths work together.
Use the Texas Instruments (TI) TLV9001IDBVR in its five-pin small-outline transistor package, SOT-23, package code DBV. Figure 6-1 and Table 6-1 of the TLV900x data sheet give the standard top view and pin functions. The TLV9001U has a different DBV pin assignment. Fit the exact standard part on a short soldered adapter and verify its pin 1 position before mounting it. It uses all five pins, with no extra enable pin. The recommended supply range is 1.8–5.5 V. Use 5.00 V with the input and output centered near mid-supply. The absolute maximum for supply voltage in the table is 7 V, a stress limit. Keep a 100 nF bypass directly between the supply pins.
Use two 3.30 kΩ, 1% Vishay MRS25 resistors in series. For the capacitors that swap, use one 47 nF KEMET R82EC2470DQ60K and one 10 nF R82EC2100DQ50K. Both are non-polarized polyester-film parts with ±10% tolerance and a 100 V direct-current rating. Use the same physical parts in both positions. Fit the bypass, for example a Vishay MKT1820410015 100 nF film part, on its own short supply loop. The filter parts stay separate from that bypass.
| Net | Connect |
|---|---|
| VIN | AFG1022 CH1 center, scope CH1 tip, first end of R1 |
| M | R1–R2 junction and one end of the feedback capacitor, CF |
| IN+ | Pin 3, far end of R2, top of grounded capacitor CG |
| OUT | Pins 1 and 4, other end of CF, scope CH2 tip |
| +5 V | Pin 5 and bypass top |
| G0 | Pin 2, bypass bottom, CG return, supply negative, generator shell and both scope grounds |
Write the ratio of output to the measured input as H(s), with s the complex frequency variable. For an ideal follower, output and the signal at the non-inverting pin are equal. The current through R2 then equals the current in CG. Applying the current balance at the resistor midpoint gives this denominator.
H(s) = 1 / [1 + s(R1 + R2)CG + s²R1R2CFCG]
f0 = 1 / (2π√(R1R2CFCG))
Q = √(R1R2CF/CG) / (R1 + R2)
Natural frequency, f0, is the frequency parameter set by the second-order term. Q, the quality factor, describes damping. A smaller Q gives more damping. With equal 3.30 kΩ resistors, Q reduces to ½√(CF/CG). The original layout gives Q ≈ 1.084. The swapped layout gives Q ≈ 0.231 and is overdamped. Both layouts give f0 ≈ 2.225 kHz nominally. At f0 the ideal real part of the denominator cancels, the magnitude is Q and the output phase is −90°. A cutoff defined by a 3 dB drop is a different frequency. The overdamped arrangement has no magnitude peak.
Using 1% resistor and 10% capacitor tolerance limits independently gives an ideal natural-frequency interval of about 2.00–2.50 kHz. Real component values shift that estimate. Swapping the same pair preserves their product even when both parts differ from their labels. The phase lag and magnitude measured at any one chosen test frequency can still differ from the nominal table.
The TLV9001's typical gain-bandwidth product is 1 MHz and its typical slew rate is 2 V/µs at 5 V under the specified test conditions. For scale, an 8 kHz sine at 0.6 V peak takes about 0.030 V/µs at its steepest. The selected circuit keeps the output well away from the rails. The feedback capacitor sees the resistive network on its other side. A capacitor wired directly from OUT to ground would place a different load on the amplifier. Gain-bandwidth, probe capacitance, parasitics and part tolerance all limit the ideal model.
Make a CSV copy for the analyzer. Keep the original simultaneous samples after removing instrument units and headings. The exact template header is time_s,input_v,output_v. Convert the time axis to seconds and the two channels to volts if needed. You may move the time origin by a single constant. Preserve the relative timestamps and contiguous raw samples. The file limit is 18,000 rows and 1.4 MB. Repeat with a suitable native memory depth if it is too large.
For each file the analyzer finds the actual frequency from input crossings and fits a constant plus a sine and cosine to each trace at that frequency. The ratio of the output and input complex amplitudes gives H. Its magnitude is the output peak divided by the input peak. Its angle is the output phase relative to the input. A negative angle indicates lag. Quiet, sufficiently long records help reject clipping, noise and wrong frequencies.
Write 1/H = a + jb at the actual middle test frequency f, where j is the imaginary unit and j² = −1. For the ideal denominator, a = 1 − x² and b = x/Q, where x = f/f0. The program uses x = √(1 − a) to estimate f0 = f/x and Q = x/b. Since the middle point supplies both estimates, it checks that the other two frequencies also fit the predicted complex response. The restored response must agree with the original. The three fitted natural frequencies must be within 7.5% of their average from minimum to maximum, and the original/restored Q must be clearly greater than the swapped Q. This checks a simple model with three discrete sine measurements. It leaves exact cutoff, broader stability and unmeasured response outside the experiment.
The table gives calculated nominal values from the synthetic files. The bench frequencies can differ slightly from the stated test frequencies. The actual fit uses the measured frequency in each file.
| f (Hz) | A gain (V/V) | A phase (°) | Swap gain (V/V) | Swap phase (°) |
|---|---|---|---|---|
| 100 | 1.0012 | −2.4 | 0.9834 | −11.1 |
| 2225 | 1.0838 | −90.0 | 0.2306 | −90.0 |
| 8000 | 0.0807 | −164.5 | 0.0509 | −127.4 |
A bad match at 8 kHz can come from low output resolution, unintended loading or a circuit response outside the simple model. Check the synchronized source and output first. Describe unresolved data as unresolved. The included waveforms are synthetic and the circuit has yet to be tested on a bench.
Use Python 3.9 or later and the standard library. Download the editor-ready diagram, analyzer, tests and nine constructed captures. Put your three files for each configuration in one folder, with names such as a-100.csv, swap-2225.csv and restore-8000.csv. Use the exact nominal frequency and stage labels in the filenames. Exit 0 means the fixture checks and the model test passed, 1 means the comparison is unresolved, and 2 indicates invalid input or syntax.
python3 sallen_swap.py my-captures
python3 sallen_swap.py synthetic
python3 -m unittest -v test_sallen_swap
"""Estimate natural frequency and damping from paired sine-wave captures."""
import argparse
import cmath
import csv
import hashlib
import math
import statistics
import struct
from dataclasses import dataclass
from pathlib import Path
HEADER = ("time_s", "input_v", "output_v")
FREQUENCIES = (100, 2225, 8000)
STAGES = ("a", "swap", "restore")
MAX_BYTES, MAX_ROWS = 1_400_000, 18_000
ROUNDING = 1e-10
class BadInput(ValueError):
pass
class Unresolved(ValueError):
pass
@dataclass(frozen=True)
class Point:
frequency: float
response: complex
def check(value, low, high, label):
if not low - ROUNDING <= value <= high + ROUNDING:
raise Unresolved(f"{label} is {value:.6g}, expected {low:g}–{high:g}")
return value
def read_csv(path):
try:
if path.stat().st_size > MAX_BYTES:
raise BadInput("CSV exceeds byte limit")
with path.open(newline="", encoding="utf-8-sig") as file:
reader = csv.reader(file, strict=True)
if tuple(next(reader, ())) != HEADER:
raise BadInput("expected header " + ",".join(HEADER))
rows, digest = [], hashlib.sha256()
for line, row in enumerate(reader, 2):
if line > MAX_ROWS + 1:
raise BadInput("CSV exceeds row limit")
if len(row) != 3:
raise BadInput(f"row {line}: expected three columns")
try:
values = tuple(float(token) for token in row)
except ValueError as error:
raise BadInput(f"row {line}: expected numbers") from error
if not all(map(math.isfinite, values)):
raise BadInput(f"row {line}: expected finite numbers")
if rows and values[0] <= rows[-1][0]:
raise BadInput(f"row {line}: time must be strictly increasing")
rows.append(values)
digest.update(struct.pack(">3d", *(value if value else 0 for value in values)))
except (OSError, csv.Error, UnicodeError) as error:
raise BadInput(str(error)) from error
if len(rows) < 80:
raise Unresolved("insufficient samples for several periods")
return rows, digest.hexdigest()
def crossings(time, signal):
threshold = .5 * (max(signal) + min(signal))
return [
t0 + (t1 - t0) * (threshold - y0) / (y1 - y0)
for t0, t1, y0, y1 in zip(time, time[1:], signal, signal[1:])
if y0 < threshold <= y1
]
def solve_3(matrix, right):
augmented = [list(row) + [value] for row, value in zip(matrix, right)]
for index in range(3):
pivot = max(range(index, 3), key=lambda row: abs(augmented[row][index]))
if abs(augmented[pivot][index]) < 1e-8:
raise Unresolved("samples do not determine a sine fit")
augmented[pivot], augmented[index] = augmented[index], augmented[pivot]
pivot_row = augmented[index]
scale = pivot_row[index]
augmented[index] = [value / scale for value in pivot_row]
for row in range(3):
if row != index:
factor = augmented[row][index]
augmented[row] = [a - factor * b for a, b in zip(augmented[row], augmented[index])]
return tuple(row[-1] for row in augmented)
def sine_fit(basis, values):
matrix = [[sum(a * b for a, b in zip(col1, col2)) for col1 in basis] for col2 in basis]
right = [sum(a * v for a, v in zip(col, values)) for col in basis]
dc, c, s = solve_3(matrix, right)
residual = math.sqrt(sum(
(value - dc - c * cosine - s * sine) ** 2
for value, cosine, sine in zip(values, basis[1], basis[2])
) / len(values))
return dc, complex(c, -s), residual
def measure(rows, nominal):
original_time, vin, vout = zip(*rows)
if any(abs(t) > 1 for t in original_time):
raise Unresolved("translate time origin by a single constant to within ±1 s")
time = [t - original_time[0] for t in original_time]
check(time[-1] * nominal, 6, 18, "captured input periods")
check(max(y - x for x, y in zip(time, time[1:])) * nominal, 0, .020, "sample gap in input periods")
for channel, name in ((vin, "input"), (vout, "output")):
check(min(channel), 1.4, 3.6, name + " minimum raw voltage")
check(max(channel), 1.4, 3.6, name + " maximum raw voltage")
edges = crossings(time, vin)
if len(edges) < 7:
raise Unresolved("need seven rising input crossings and six complete periods")
periods = [b - a for a, b in zip(edges, edges[1:])]
typical = statistics.median(periods)
check(1 / typical, .98 * nominal, 1.02 * nominal, "input frequency (Hz)")
check((max(periods) - min(periods)) / typical, 0, .012, "input period variation")
frequency = (len(edges) - 3) / (edges[-2] - edges[1])
keep = [i for i, t in enumerate(time) if edges[1] <= t <= edges[-2]]
angles = [2 * math.pi * frequency * (time[i] - edges[1]) for i in keep]
basis = [[1.0] * len(keep), [math.cos(value) for value in angles],
[math.sin(value) for value in angles]]
vin_dc, vin_fit, rin = sine_fit(basis, [vin[i] for i in keep])
out_dc, out_fit, rout = sine_fit(basis, [vout[i] for i in keep])
check(vin_dc, 2.44, 2.56, "input DC center (V)")
check(out_dc - vin_dc, -.055, .055, "output versus input DC center (V)")
check(abs(vin_fit), .455, .545, "input sine peak (V)")
check(abs(out_fit), .015, .90, "output sine peak (V)")
check(rin / abs(vin_fit), 0, .018, "input sine residual relative to peak")
check(rout / abs(out_fit), 0, .045, "output sine residual relative to peak")
return Point(frequency, out_fit / vin_fit)
def param(point):
inverse = 1 / point.response
if inverse.real >= 1 or inverse.imag <= 0:
raise Unresolved("near-center complex gain cannot represent a unity low-pass")
x = math.sqrt(1 - inverse.real)
return point.frequency / x, x / inverse.imag
def ideal(frequency, f0, q):
x = frequency / f0
return 1 / complex(1 - x*x, x/q)
def verify(stages):
for a, r in zip(stages["a"], stages["restore"]):
if abs(a.response - r.response) > max(.008, .055*abs(a.response)) + ROUNDING:
raise Unresolved("restore does not reproduce original complex response")
estimates = {name: param(points[1]) for name, points in stages.items()}
for name, (f0, q) in estimates.items():
check(f0, 1950, 2550, name + " natural frequency (Hz)")
q_bounds = (.175, .32) if name == "swap" else (.84, 1.36)
check(q, *q_bounds, name.replace("swap", "swapped") + " Q")
for point in stages[name]:
expected = ideal(point.frequency, f0, q)
error = abs(point.response - expected)
if error > max(.006, .12 * abs(expected)) + ROUNDING:
raise Unresolved(f"{name}: {point.frequency:.2f} Hz misses the second-order response")
f0s = [f0 for f0, _ in estimates.values()]
check((max(f0s) - min(f0s)) / statistics.mean(f0s), 0, .075, "natural frequency spread")
qa, qs, qr = (estimates[name][1] for name in STAGES)
check(abs(qa - qr) / qa, 0, .095, "restore Q difference")
check(min(qa, qr) / qs, 3.4, 6.2, "Q contrast (original/swapped)")
return estimates
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("folder", type=Path, help="folder with a, swap, and restore CSV sets")
args = parser.parse_args()
try:
stages, parsed = {}, set()
for name in STAGES:
points = []
for nominal in FREQUENCIES:
path = args.folder / f"{name}-{nominal}.csv"
try:
rows, digest = read_csv(path)
if digest in parsed:
raise BadInput("duplicate parsed capture")
parsed.add(digest)
points.append(measure(rows, nominal))
except (BadInput, Unresolved) as error:
raise type(error)(f"{path.name}: {error}") from error
stages[name] = points
estimates = verify(stages)
except BadInput as error:
parser.exit(2, f"INPUT: {error}\n")
except Unresolved as error:
parser.exit(1, f"UNRESOLVED: {error}\n")
for name, (f0, q) in estimates.items():
print(f"{name:7} | f0 {f0:.1f} Hz | Q {q:.3f}")
for point in stages[name]:
print(f" {point.frequency:8.2f} Hz | {abs(point.response):.4f} V/V | "
f"{math.degrees(cmath.phase(point.response)):+.1f} deg")
print("PASS: same natural-frequency band, reduced Q after swapping; original response restored.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
At the middle frequency, the fitted output phase is approximately −90° in both layouts. Does this mean the two layouts have the same gain there?
At the natural frequency the magnitude is Q. The original produces about 1.08 V/V there and the swapped one about 0.23 V/V, even with the same −90° phase. Phase and gain answer separate questions.