TExcelTAD
Home › Electrical & Electronic Measurements › Automated Test: SCPI and Python Instrument Control

Automated Test: SCPI and Python Instrument Control

Measuring a resistor's VV–II 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

Python script sweep, log, fit PyVISA write, query VISA library resource strings interface GPIB, USB, LAN instruments SCPI parser, error queue, status registers SCPI text *RST; *IDN?; CURR 0.02; OUTP ON; MEAS:VOLT:DC?; SYST:ERR?
  • 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::INSTR or TCPIP0::192.168.1.50::inst0::INSTR, and offers write, read and query. PyVISA is the Python binding; it can use a vendor's VISA library or the pure-Python pyvisa-py backend.
  • 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.

python
# 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"), err

The 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 470 Ω470\ \Omega resistor (secretly 0.4 %0.4\,\% 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:

python · try it yourself
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, 471.9 Ω471.9\ \Omega, matches the hidden 471.88 Ω471.88\ \Omega to within the simulated noise.

Worked example: how long will a sweep take?

Given: a 6½-digit DMM at 1010 NPLC on 50 Hz50\ \text{Hz} mains, auto-zero on (which roughly doubles the time per reading), a supply that settles in 50 ms50\ \text{ms}, 100 ms100\ \text{ms} of circuit settling, and 10 ms10\ \text{ms} of communication per command round trip; 2 readings (V and I) per point, 200 points.

Find: the sweep time.

Solve: one reading takes 2×10×20 ms=400 ms2 \times 10 \times 20\ \text{ms} = 400\ \text{ms}; a point needs about 50+100+2×400+4×10=990 ms50 + 100 + 2 \times 400 + 4 \times 10 = 990\ \text{ms}, so

T≈200×0.99 s=198 s≈3.3 minT \approx 200 \times 0.99\ \text{s} = 198\ \text{s} \approx 3.3\ \text{min}

Check: the DMM's integration time dominates. Dropping to 11 NPLC cuts the sweep to about 1 min1\ \text{min} 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 a finally block 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 470 Ω470\ \Omega resistor at 11 to 5 V5\ \text{V} takes 2.132.13 to 10.64 mA10.64\ \text{mA}; 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 20 mA20\ \text{mA}, voltage 00 to 5 V5\ \text{V} in 0.5 V0.5\ \text{V} steps, the DMM on a fixed 10 V10\ \text{V} range at 11 NPLC, the supply's own current readback (or a second DMM) for II. Expect a straight line with residuals of a few counts, a slope within 1 %1\,\% of 470 Ω470\ \Omega, 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. 5 V5\ \text{V} and 20 mA20\ \text{mA} current limit; the resistor dissipates at most 53 mW53\ \text{mW}. 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

  1. Write the SCPI query for a DC voltage reading with the short form, and the command to turn a supply's output off.
  2. Why should a script send CURR 0.02 before OUTP ON?
Answer
  1. MEAS:VOLT:DC? (or CONF:VOLT:DC then READ?); OUTP OFF.
  2. 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

  1. the measured value
  2. the instrument's manufacturer, model, serial number and firmware
  3. the error queue
  4. the IP address only

VISA's job is to

  1. define SCPI commands
  2. provide one programming interface to instruments over GPIB, USB, LAN or serial
  3. calibrate instruments
  4. plot data

*OPC? is used to

  1. reset the instrument
  2. wait until pending operations have completed
  3. read the error queue
  4. turn the output on

Why fix the DMM's range during an automated sweep?

  1. autorange is less accurate at all times
  2. range changes alter input impedance and add settling delays between points
  3. SCPI cannot autorange
  4. to save power