Knowledge Base

Python을 이용한 계측기 프로그래밍

이 기술 자료에서는 Python 프로그래밍 언어를 사용하여 Magna-Power 프로그래머블 전원 제품을 프로그래밍하는 방법을 소개합니다. Python은 간결성, 코드 가독성, 별도의 컴파일이 필요 없는 점으로 널리 알려진 인기 있는 프로그래밍 언어입니다. Python의 사용 편의성과 빠른 학습 곡선은 프로그래머블 계측기의 제어, 측정, 그래프 생성을 위한 프로그램 작성에 매우 적합한 언어입니다. 또한, Magna-Power의 SCPI(Standard Commands for Programmable Instrumentation)에 대한 광범위한 지원으로 자사 제품을 Python에서 간단하고 직관적인 명령으로 쉽게 제어할 수 있습니다.

Magna-Power 제품은 RS-232, TCP/IP Ethernet, USB, RS-485, IEEE-488 GPIB 등 다양한 통신 인터페이스를 지원합니다. 이러한 다양한 인터페이스에도 불구하고 특정 제품 시리즈에 대한 SCPI 명령은 동일합니다. SCPI 명령은 해당 제품 시리즈의 사용자 매뉴얼에 문서화되어 있습니다. Python 프로그램을 작성할 때 인터페이스 간의 유일한 차이점은 장치 연결 설정뿐입니다.

USB, 시리얼 또는 RS-485의 경우, pySerial을 사용하여 계측기에 대한 시리얼 연결을 생성합니다:

import serial
conn = serial.Serial(port='COM4', baudrate=115200)

The serial baud rate for MagnaLOAD products is 115200, while the serial baud rate for MagnaDC products is 19200. The port location is defined by your operating system. In Windows, this port can be found in the Device Manager.

Subsequent sending and receiving of commands over serial connection will be as follows:

conn.write('*IDN?\n'.encode())
print(conn.readline())

TCP/IP Ethernet 연결 설정은 다음과 같습니다:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.0.86', 50505))

TCP/IP Ethernet 연결을 통한 후속 명령 송수신은 다음과 같습니다:

s.sendall('*IDN?\n'.encode())
print(s.recv(4096))

IEEE-488 GPIB 연결에는 PyVISA가 필요하며, 연결 방법은 다음과 같습니다:

import visa
rm = visa.ResourceManager()
inst = rm.open_resource('GPIB0::12::INSTR')

IEEE-488 GPIB 연결을 통한 후속 명령 송수신은 다음과 같습니다:

print(inst.query("*IDN?"))

The following examples provide more in-depth example Python programs using a MagnaLOAD DC electronic load. Programming a MagnaDC programmable DC power supply in Python will be almost identical, with subtle changes to the SCPI commands as documented in the respective product series’ user manual.

The following basic example creates a TCP/IP Ethernet connection, sends some initialization commands, enables the DC input, raises the current level to 5 Adc, waits 20 seconds, then shuts down.

# Import time: Time access and conversions to allow for pausing
# Import socket: Low-level networking interface to allow for socket programming
import time, socket
# Create socket object s with (host, port)
# Define host as hostname in Internet domain
# Define socket type as stream, allowing a port number to be defined
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to product's IP address address at default 50505 socket
s.connect(('192.168.0.86', 50505))
# Send SCPI command requesting the product to identify itself
s.sendall('*IDN?\n'.encode())
# Receive the product's response and display it in the terminal
print(s.recv(4096))
# Send SCPI command to configure the MagnaDC for local control
s.sendall('CONF:SOUR 0\n'.encode())
# Send SCPI command to set the DC output current to 0 Adc before enabling DC input
s.sendall('CURR 0\n'.encode())
# Send SCPI command to enable the MagnaDC power supply output
s.sendall('OUTP:START\n'.encode())
# Send SCPI command to set the DC input current to 5 Adc
s.sendall('CURR 5\n'.encode())
# Wait 20 seconds
time.sleep(20)
# Send SCPI command to disable the DC output
s.sendall('OUTP:STOP\n'.encode())
# Close the communication channel to the product
s.close()

다음 예제는 제품에 대한 시리얼 연결을 생성하고, 제품 정보를 확인한 후, 각 전류 레벨 사이에 20초 간격으로 일련의 전류 명령을 전송합니다. 이러한 유형의 프로그램은 전압, 전력, 저항 값의 순환으로도 확장할 수 있습니다.

# Import pySerial, which encapsulates the serial port access
# Import time: Time access and conversions to allow for pausing
import serial, time
# Create serial connection object with default baudrate for MagnaLOADs
conn = serial.Serial(port='COM4', baudrate=115200)
# Send SCPI command requesting the product to identify itself
conn.write('*IDN?\n'.encode())
# Receive the product's response and display it in the terminal
print conn.readline()
# Create array of current set points
currSetPoints = [50, 100, 150, 250]
# Send SCPI command to configure the MagnaDC power supply for local control
s.sendall('CONF:SOUR 0\n'.encode())
# Send SCPI command to enable the MagnaDC power supply
conn.write('OUTP:START\n'.encode())
# For each entry in currSetPoints array
# Print static text and current set point to the terminal
# Send the new set point to the MagnaDC power supply
# Wait 20 seconds
for currSetpoint in currSetPoints:
    print 'Setting Current to %s A' % currSetpoint
    conn.write('CURR {0}\n'.format(currSetpoint).encode())
    time.sleep(20)
# Send SCPI command to disable the MagnaDC power supply output
conn.write('OUTP:STOP\n'.encode())
# Close the communication channel to the product
conn.close()

In the final in-depth example, a MagnaLOAD is programmed to discharge a battery using set points and times read from a comma-separate value (.csv) file, measure the DC input using the product’s high accuracy measurement commands, and then provide a plot of the measured data versus time. This program could be further expanded to generate a PDF test report, integrating the measured data, plots, as well as information from other instruments.

# Import plotting library Matplotlib
# Import .csv parser
# Import pySerial, which encapsulates the access for the serial port
# Import time: Time access and conversions to allow for pausing
# Import numpy for mathemetical manipulation of arrays
import matplotlib.pyplot as plt
import csv, serial, time
import numpy as np

# Create serial connection object with default baudrate for xGen products
conn = serial.Serial(port='COM8', baudrate=115200)
# Create an empty numpy data array 999 rows, 4 columns
outputSamples = np.empty([999, 3])
iSample = 0

# Send SCPI command to configure the MagnaDC for local control
s.sendall('CONF:SOUR 0\n'.encode())
# Send SCPI command to enable the MagnaDC power supply output
conn.write('OUTP:START\n'.encode())

# Open data stream to .csv file. .csv has two columns:
# Column 1: Current set point in amperes
# Column 2: Time in seconds
# The first row is headers
with open('example_profile.csv', 'r') as csvfile:
	# Read the .csv file using comma (,) as the delimeter
    dataset = csv.reader(csvfile, delimiter=',')
	# Skip the header row
    next(dataset)
	# Split the dataset up to rows
    rows = list(dataset)
	# Create an empty array for measurements, the same length as .csv row numbers
    inputSamples = np.empty([len(rows), 2], dtype=float)
	# Record the time that the measurements began
    testStartTime = time.time()
	# Run for loop while there are still rows of data left
    for idx, data in enumerate(rows):
		# Store row data to array
        inputSamples[idx] = [data[0], data[1]]
		# Send SCPI command to MagnaDC power supply to current set point at present row
        conn.write('CURR {0}\n'.format(data[0]).encode())
		# Determine how long the MagnaDC power supply should stay at this current set point
        stopTime = testStartTime + int(data[1])
		# Run while loop while there is still time left
        while time.time() < stopTime:
			# Send SCPI command to MagnaDC Power supply to measure all DC output variables
            conn.write('MEAS:ALL?\n')
			# Get the MagnaDC power supply's response and split it up into its respective variables
            [curr, volt, pwr] = (conn.readline()).split(',')
			# Round measurements and store them to array, along with with time
            outputSamples[iSample] = ([round(float(curr), 2), round(float(volt), 2), round(time.time() - testStartTime, 2)])
            iSample += 1
            time.sleep(0.5)

# Send SCPI command to disable Magna DC power supply output 
conn.write('OUTP:STOP\n'.encode())

# Create a plot series of current vs. time
plt.subplot(2, 1, 1)
plt.plot(outputSamples[0:iSample, 2], outputSamples[0:iSample, 0], 'r--')
plt.ylabel('Output Current(A)')
plt.title('I-V Profile')

# Create a plot series of voltage vs. time
plt.subplot(2, 1, 2)
plt.plot(outputSamples[0:iSample, 2], outputSamples[0:iSample, 1], 'b--')
plt.xlabel('Time (s)')
plt.ylabel('Output Voltage(V)')

# Show the plot
plt.show()
Originally published 6월 20, 2018

Stay connected and informed.

Subscribe to receive emails—no more than once per month—with new technical articles, product releases and factory updates from Magna-Power.

Have any questions or feedback?
We'd love to hear from you.
Contact us