Automated Test: SCPI and Python Instrument Control
Measuring a resistor's – curve by hand takes ten minutes, gives five points and a page of transcription errors. A twenty-line script takes the same five points in two seconds, or five hundred points overnight, logs the instrument identities and settings with every number, and can be run again next month to give a comparable result. That repeatability, more than speed, is why measurement procedures are automated. This lesson covers the command language almost every bench instrument understands (SCPI), the software layer that carries it (VISA), how a Python script drives instruments with PyVISA, and the habits that make automated results trustworthy.
The stack
- Physical interface: GPIB (IEEE 488, the classic parallel bus), USB with the USBTMC class, LAN (raw socket on port 5025, VXI-11 or HiSLIP), RS-232. Instruments that follow the LXI standard expose LAN control and a web page.
- VISA (Virtual Instrument Software Architecture): a library that hides the interface behind a resource string such as
USB0::0x1234::0x5678::SN123::INSTRorTCPIP0::192.168.1.50::inst0::INSTR, and offerswrite,readandquery. PyVISA is the Python binding; it can use a vendor's VISA library or the pure-Pythonpyvisa-pybackend. - IEEE 488.2 defines message syntax, status registers and common commands starting with
*:*IDN?(identify),*RST(reset to a known state),*CLS(clear status),*OPC?(returns 1 when pending operations are complete),*ESR?(event status),*TST?(self-test). - SCPI (Standard Commands for Programmable Instruments) builds on it with a hierarchical, readable command tree:
MEASure:VOLTage:DC?,CONFigure:CURRent:DC 0.1,SOURce:VOLTage 5.0,OUTPut ON,SYSTem:ERRor?. Upper-case letters are the required short form (MEAS:VOLT:DC?); a?makes a query; arguments follow a space. Commands differ in detail between manufacturers, so the programming manual is always the reference.
A PyVISA script (illustrative)
The program below shows the structure of a real script for a bench supply and a DMM. It is illustrative: it cannot run here, because the site runs in your browser with no access to instruments, and the resource strings and some commands depend on your instruments.
# Illustrative only: needs PyVISA, a VISA backend and real instruments.
import csv, time
import pyvisa
rm = pyvisa.ResourceManager()
print(rm.list_resources()) # find your instruments
psu = rm.open_resource("USB0::0x1234::0x0001::PSU123::INSTR", timeout=5000)
dmm = rm.open_resource("TCPIP0::192.168.1.50::inst0::INSTR", timeout=5000)
for inst in (psu, dmm):
inst.write("*RST; *CLS")
print(inst.query("*IDN?").strip()) # log make, model, serial, firmware
psu.write("CURR 0.020") # current limit before the output goes on
psu.write("VOLT 0")
psu.write("OUTP ON")
dmm.write("CONF:VOLT:DC 10") # fixed range: no autorange jumps in a sweep
dmm.write("VOLT:DC:NPLC 10")
with open("sweep.csv", "w", newline="") as f:
log = csv.writer(f)
log.writerow(["v_set", "v_meas", "time"])
for v in [1, 2, 3, 4, 5]:
psu.write(f"VOLT {v}")
psu.query("*OPC?") # wait for the supply
time.sleep(0.2) # settling of the circuit itself
log.writerow([v, float(dmm.query("READ?")), time.time()])
psu.write("OUTP OFF")
for inst in (psu, dmm):
err = inst.query("SYST:ERR?") # always check the error queue
assert err.startswith("+0") or err.startswith("0"), errThe same logic, simulated
To run the logic here, a small class stands in for the instruments: it parses a handful of SCPI commands, keeps an error queue, and "measures" a resistor (secretly high) with a little noise. The sweep, the *OPC? handshake, the error-queue check and the fit are the same as in the real script:
import numpy as np
class SimulatedBench:
"""A tiny SCPI parser standing in for a bench supply and a DMM (no hardware, no network)."""
def __init__(self, seed=0):
self.rng = np.random.default_rng(seed)
self.v_set, self.i_lim, self.output = 0.0, 0.1, False
self.function, self.errors = "VOLT:DC", []
self.R_load = 470.0 * 1.004 # the "unknown": a 470 ohm resistor, 0.4 % high
def write(self, cmd):
head, *args = cmd.strip().split(" ", 1)
head = head.upper()
if head in ("*RST",):
self.__init__(seed=0)
elif head in ("VOLT", "SOUR:VOLT"):
self.v_set = float(args[0])
elif head in ("CURR", "SOUR:CURR"):
self.i_lim = float(args[0])
elif head in ("OUTP", "OUTPUT"):
self.output = args[0].upper() in ("ON", "1")
elif head in ("CONF:VOLT:DC", "CONF:CURR:DC"):
self.function = head[5:]
else:
self.errors.append(f'-113,"Undefined header;{head}"')
def query(self, cmd):
cmd = cmd.strip().upper()
if cmd == "*IDN?":
return "Simulated,BENCH-1,0001,1.0"
if cmd in ("SYST:ERR?", "SYSTEM:ERROR?"):
return self.errors.pop(0) if self.errors else '+0,"No error"'
if cmd == "*OPC?":
return "1"
if cmd in ("READ?", "MEAS?"):
v = min(self.v_set, self.i_lim * self.R_load) if self.output else 0.0
if self.function == "VOLT:DC":
return f"{v * (1 + 20e-6 * self.rng.standard_normal()):+.6E}"
return f"{v / self.R_load * (1 + 50e-6 * self.rng.standard_normal()):+.6E}"
self.errors.append(f'-113,"Undefined header;{cmd}"')
return ""
bench = SimulatedBench()
print(bench.query("*IDN?"))
bench.write("*RST")
bench.write("CURR 0.02") # current limit first
bench.write("OUTP ON")
rows = []
for v in np.arange(1.0, 5.5, 1.0):
bench.write(f"VOLT {v:.3f}")
bench.query("*OPC?") # wait until the setting has been applied
bench.write("CONF:VOLT:DC"); V = float(bench.query("READ?"))
bench.write("CONF:CURR:DC"); I = float(bench.query("READ?"))
rows.append((V, I))
bench.write("OUTP OFF")
bench.write("VOLT:PROT 6") # a typo-like command the simulator does not know
print("error queue:", bench.query("SYST:ERR?"), "|", bench.query("SYST:ERR?"))
V, I = np.array(rows).T
slope, intercept = np.polyfit(I, V, 1)
print(" V (V) I (mA)")
for v, i in rows:
print(f"{v:9.5f} {1e3 * i:10.5f}")
print(f"fitted R = {slope:.2f} ohm, intercept {1e3 * intercept:+.3f} mV")Simulated,BENCH-1,0001,1.0
error queue: -113,"Undefined header;VOLT:PROT" | +0,"No error"
V (V) I (mA)
1.00000 2.11917
2.00003 4.23839
2.99997 6.35766
4.00010 8.47713
4.99993 10.59524
fitted R = 471.90 ohm, intercept -0.093 mV
The error queue caught a command the "instrument" did not understand; on real hardware such a mistake is silent unless you ask. The fitted resistance, , matches the hidden to within the simulated noise.
Worked example: how long will a sweep take?
Given: a 6½-digit DMM at NPLC on mains, auto-zero on (which roughly doubles the time per reading), a supply that settles in , of circuit settling, and of communication per command round trip; 2 readings (V and I) per point, 200 points.
Find: the sweep time.
Solve: one reading takes ; a point needs about , so
Check: the DMM's integration time dominates. Dropping to NPLC cuts the sweep to about at the cost of noise (Inside the DMM); switching functions between V and I costs relay time too, so two DMMs (one per quantity) are often faster than one.
Habits that make automated results trustworthy
- Start from a known state (
*RST, then explicit settings); never rely on what the front panel was left at. - Set protections first: current limit and voltage limit before
OUTP ON; turn outputs off in afinallyblock so a crash leaves the circuit safe. - Fix ranges in sweeps; autorange changes input impedance and settling between points.
- Synchronise:
*OPC?, explicit settle delays, or hardware triggers; don't read before the source has settled. - Check errors (
SYST:ERR?) after configuration and at the end. - Log metadata:
*IDN?strings (serial numbers tie readings to calibration certificates), settings, date, temperature, script version (a Git commit). - Simulate first: a fake instrument class like the one above lets you test the logic without hardware, and documents what the script expects.
Guided lab: automate a V-I characteristic
Hand calculation. A resistor at to takes to ; a fitted slope within the resistor's tolerance and an intercept near zero are the expected result (EE Foundations did this by hand).
Simulation. Run the simulated bench; change R_load and the noise, or add a command the class does not know and watch the error queue.
What you would measure. With a SCPI-capable supply and DMM (USB or LAN), adapt the illustrative script: current limit , voltage to in steps, the DMM on a fixed range at NPLC, the supply's own current readback (or a second DMM) for . Expect a straight line with residuals of a few counts, a slope within of , and a CSV file plus a log of *IDN? strings. Run it twice: the two results should agree within their uncertainties, which is the point of automation.
Hazards and safe setup. and current limit; the resistor dissipates at most . Scripts must switch outputs off on any exception. No instrument control of mains-powered loads.
Pitfalls
- Reading too soon after a setting change (no settling, no
*OPC?). - Leaving autorange on in a sweep.
- Ignoring the error queue, so a mistyped command silently does nothing.
- Logging numbers without instrument identities and settings: the data can no longer be traced to a calibration.
Practice
- Write the SCPI query for a DC voltage reading with the short form, and the command to turn a supply's output off.
- Why should a script send
CURR 0.02beforeOUTP ON?
Answer
MEAS:VOLT:DC?(orCONF:VOLT:DCthenREAD?);OUTP OFF.- So the current limit protects the circuit from the first instant the output is live; the previous user's limit could be much higher.
Test yourself
*IDN? returns
- the measured value
- the instrument's manufacturer, model, serial number and firmware
- the error queue
- the IP address only
VISA's job is to
- define SCPI commands
- provide one programming interface to instruments over GPIB, USB, LAN or serial
- calibrate instruments
- plot data
*OPC? is used to
- reset the instrument
- wait until pending operations have completed
- read the error queue
- turn the output on
Why fix the DMM's range during an automated sweep?
- autorange is less accurate at all times
- range changes alter input impedance and add settling delays between points
- SCPI cannot autorange
- to save power