VB.NET을 이용한 계측기 프로그래밍
이 기술 자료에서는 VB.NET 프로그래밍 언어를 사용하여 Magna-Power 프로그래머블 전원 제품을 프로그래밍하는 방법을 소개합니다. VB.NET은 Microsoft .NET Framework에 통합된 다목적 언어로, Windows 애플리케이션 개발에 있어 단순성과 사용 편의성으로 잘 알려져 있습니다. 강력한 기능을 갖추고 있어 프로그래머블 계측기의 제어, 측정, 플롯 생성 프로그램을 개발하는 데 탁월한 선택입니다. 또한 Magna-Power는 SCPI(Standard Commands for Programmable Instrumentation)를 광범위하게 지원하므로, 간단하고 직관적인 명령으로 VB.NET에서 자사 제품을 손쉽게 제어할 수 있습니다.
Magna-Power 제품은 RS-232, TCP/IP Ethernet, USB, RS-485, IEEE-488 GPIB 등 다양한 통신 인터페이스를 지원합니다. 이러한 인터페이스가 서로 다르더라도 특정 제품 시리즈에 대한 SCPI 명령은 동일합니다. SCPI 명령은 해당 제품 시리즈의 사용자 매뉴얼에 문서화되어 있습니다. VB.NET 프로그램을 작성할 때 인터페이스 간 유일한 차이점은 장치 연결 설정뿐입니다.
통신 인터페이스
USB, 시리얼 또는 RS-485 연결
USB, 시리얼 또는 RS-485 연결의 경우, VB.NET에서는 System.IO.Ports.SerialPort 클래스를 사용하여 계측기에 시리얼 연결을 생성합니다:
Dim conn As New IO.Ports.SerialPort("COM4", 115200)
conn.Open()
xGen 제품의 시리얼 보드레이트는 115200이며, xGen이 아닌 제품의 시리얼 보드레이트는 19200입니다. 포트 이름은 운영 체제에 의해 정의됩니다. Windows에서는 장치 관리자에서 해당 포트를 확인할 수 있습니다.
이후 시리얼 연결을 통한 명령 송수신은 다음과 같이 수행됩니다:
conn.WriteLine("*IDN?")
Dim response As String = conn.ReadLine()
Console.WriteLine(response)
TCP/IP Ethernet 연결
TCP/IP Ethernet 연결의 경우, VB.NET에서는 System.Net.Sockets.TcpClient 클래스를 사용합니다:
Dim client As New Net.Sockets.TcpClient("192.168.0.86", 50505)
Dim stream As Net.Sockets.NetworkStream = client.GetStream()
Dim writer As New IO.StreamWriter(stream)
Dim reader As New IO.StreamReader(stream)
writer.AutoFlush = True
이후 TCP/IP Ethernet 연결을 통한 명령 송수신은 다음과 같이 수행됩니다:
writer.WriteLine("*IDN?")
Dim response As String = reader.ReadLine()
Console.WriteLine(response)
IEEE-488 GPIB 연결
IEEE-488 GPIB 연결의 경우, National Instruments의 NI-488.2 또는 Keysight의 IO Libraries Suite와 같이 GPIB 하드웨어 제조사에서 제공하는 라이브러리를 사용할 수 있습니다. VB.NET에서는 VISA.NET 라이브러리를 사용하여 GPIB 계측기와 인터페이스할 수 있습니다.
VISA.NET 사용 예시:
먼저 VISA.NET 라이브러리가 설치되어 있는지 확인하고, 프로젝트에 Ivi.Visa 참조를 추가하십시오.
Imports Ivi.Visa
Dim rm As IResourceManager = GlobalResourceManager.Instance
Dim session As IMessageBasedSession = CType(rm.Open("GPIB0::12::INSTR"), IMessageBasedSession)
' Subsequent sending and receiving of commands over IEEE-488 GPIB connection:
session.FormattedIO.WriteLine("*IDN?")
Dim response As String = session.FormattedIO.ReadLine()
Console.WriteLine(response)
상세 예제
다음 예제에서는 xGen MagnaDC 전원 공급 장치를 사용한 보다 상세한 VB.NET 프로그램을 제공합니다. xGen이 아닌 MagnaDC 프로그래머블 DC 전원 공급 장치를 VB.NET으로 프로그래밍하는 것은 거의 동일하며, 해당 제품 시리즈의 사용자 매뉴얼에 문서화된 대로 SCPI 명령에 미세한 차이가 있을 수 있습니다.
예제 1: 기본 TCP/IP Ethernet 제어
이 기본 예제에서는 TCP/IP Ethernet 연결을 생성하고, 초기화 명령을 전송한 후, DC 출력을 활성화하고, 전류를 5 A로 올린 다음, 20초간 대기한 후 종료합니다.
Imports System.Net.Sockets
Imports System.IO
Imports System.Threading
Module Program
Sub Main()
' Create a TCP/IP client and connect to the instrument
Dim client As New TcpClient("192.168.0.86", 50505)
Dim stream As NetworkStream = client.GetStream()
Dim writer As New StreamWriter(stream)
Dim reader As New StreamReader(stream)
writer.AutoFlush = True
' Send SCPI command requesting the product to identify itself
writer.WriteLine("*IDN?")
' Receive the product's response and display it in the console
Dim response As String = reader.ReadLine()
Console.WriteLine(response)
' Configure the MagnaDC for local control
writer.WriteLine("CONF:SOUR 0")
' Set the DC output current to 0 A before enabling DC output
writer.WriteLine("CURR 0")
' Enable the MagnaDC power supply output
writer.WriteLine("OUTP:START")
' Set the DC output current to 5 A
writer.WriteLine("CURR 5")
' Wait 20 seconds
Thread.Sleep(20000)
' Disable the DC output
writer.WriteLine("OUTP:STOP")
' Close the communication channel to the product
writer.Close()
reader.Close()
client.Close()
End Sub
End Module
예제 2: 전류 설정값을 이용한 시리얼 연결
이 예제에서는 제품에 시리얼 연결을 생성하고, 연결된 제품의 종류를 확인한 다음, 각 전류 레벨 사이에 20초 간격을 두고 일련의 전류 명령을 전송합니다. 이 유형의 프로그램은 전압, 전력, 저항 값을 순환하도록 확장할 수 있습니다.
Imports System.IO.Ports
Imports System.Threading
Module Program
Sub Main()
' Create a serial connection object with default baud rate for MagnaLOADs
Dim conn As New SerialPort("COM4", 115200)
conn.Open()
' Send SCPI command requesting the product to identify itself
conn.WriteLine("*IDN?")
' Receive the product's response and display it in the console
Dim response As String = conn.ReadLine()
Console.WriteLine(response)
' Create an array of current set points
Dim currSetPoints() As Integer = {50, 100, 150, 250}
' Configure the MagnaDC power supply for local control
conn.WriteLine("CONF:SOUR 0")
' Enable the MagnaDC power supply output
conn.WriteLine("OUTP:START")
' Loop through each current set point
For Each currSetpoint In currSetPoints
Console.WriteLine($"Setting Current to {currSetpoint} A")
conn.WriteLine($"CURR {currSetpoint}")
Thread.Sleep(20000) ' Wait 20 seconds
Next
' Disable the MagnaDC power supply output
conn.WriteLine("OUTP:STOP")
' Close the communication channel to the product
conn.Close()
End Sub
End Module
예제 3: 배터리 방전 및 데이터 플로팅
이 예제에서는 xGen MagnaDC 전원 공급 장치를 프로그래밍하여 쉼표로 구분된 값(.csv) 파일에서 읽은 설정값과 시간을 사용하여 배터리를 방전하고, 제품의 고정밀 측정 명령을 사용하여 DC 입력을 측정한 다음, 측정 데이터 대 시간 플롯을 제공합니다. 이 프로그램은 측정 데이터, 플롯 및 기타 계측기의 정보를 통합하여 PDF 테스트 보고서를 생성하도록 추가 확장할 수 있습니다.
VB.NET에서 CSV 파일 처리 및 플로팅을 수행하려면 내장 클래스와 차트 작성을 위한 System.Windows.Forms.DataVisualization.Charting 네임스페이스를 사용할 수 있습니다.
단계:
- Windows Forms 애플리케이션을 생성합니다.
- 도구 상자에서 폼에
Chart컨트롤을 추가합니다. - 폼의 코드 비하인드에 다음 코드를 사용합니다.
Imports System.IO.Ports
Imports System.Threading
Imports System.IO
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private conn As SerialPort
Private outputSamples As New List(Of OutputSample)()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Initialize the serial connection with the default baud rate for xGen products
conn = New SerialPort("COM8", 115200)
conn.Open()
' Configure the MagnaDC for local control
conn.WriteLine("CONF:SOUR 0")
' Enable the MagnaDC power supply output
conn.WriteLine("OUTP:START")
' Read the CSV file containing current set points and durations
Dim inputSamples As List(Of InputSample) = ReadCsvFile("example_profile.csv")
' Record the start time
Dim testStartTime As DateTime = DateTime.Now
' Loop through each input sample
For Each sample In inputSamples
' Set the current set point
conn.WriteLine($"CURR {sample.CurrentSetPoint}")
' Calculate the stop time
Dim stopTime As DateTime = DateTime.Now.AddSeconds(sample.Duration)
' Collect measurements until the stop time
While DateTime.Now < stopTime
' Request measurements from the device
conn.WriteLine("MEAS:ALL?")
' Read the response
Dim response As String = conn.ReadLine()
Dim measurements() As String = response.Split(","c)
' Parse and store the measurements
If measurements.Length >= 3 Then
Dim curr As Double = Double.Parse(measurements(0))
Dim volt As Double = Double.Parse(measurements(1))
Dim timeElapsed As Double = (DateTime.Now - testStartTime).TotalSeconds
outputSamples.Add(New OutputSample With {
.Current = curr,
.Voltage = volt,
.Time = timeElapsed
})
End If
Thread.Sleep(500) ' Wait for 0.5 seconds
End While
Next
' Disable the MagnaDC power supply output
conn.WriteLine("OUTP:STOP")
' Close the communication channel to the product
conn.Close()
' Plot the data
PlotData()
End Sub
Private Function ReadCsvFile(filePath As String) As List(Of InputSample)
Dim samples As New List(Of InputSample)()
Using reader As New StreamReader(filePath)
' Skip the header line
reader.ReadLine()
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
Dim values() As String = line.Split(","c)
If values.Length >= 2 Then
samples.Add(New InputSample With {
.CurrentSetPoint = Double.Parse(values(0)),
.Duration = Double.Parse(values(1))
})
End If
End While
End Using
Return samples
End Function
Private Sub PlotData()
' Configure the chart control
Chart1.Series.Clear()
Chart1.ChartAreas.Clear()
Chart1.ChartAreas.Add(New ChartArea("MainArea"))
' Create series for current and voltage
Dim currentSeries As New Series("Current")
currentSeries.ChartType = SeriesChartType.Line
currentSeries.XValueType = ChartValueType.Double
currentSeries.YValueType = ChartValueType.Double
Dim voltageSeries As New Series("Voltage")
voltageSeries.ChartType = SeriesChartType.Line
voltageSeries.XValueType = ChartValueType.Double
voltageSeries.YValueType = ChartValueType.Double
' Add data points to the series
For Each sample In outputSamples
currentSeries.Points.AddXY(sample.Time, sample.Current)
voltageSeries.Points.AddXY(sample.Time, sample.Voltage)
Next
' Add series to the chart
Chart1.Series.Add(currentSeries)
Chart1.Series.Add(voltageSeries)
' Set chart titles and labels
Chart1.ChartAreas("MainArea").AxisX.Title = "Time (s)"
Chart1.ChartAreas("MainArea").AxisY.Title = "Current (A)"
Chart1.ChartAreas("MainArea").AxisY2.Title = "Voltage (V)"
Chart1.ChartAreas("MainArea").AxisY2.Enabled = AxisEnabled.True
' Associate voltage series with secondary Y-axis
voltageSeries.YAxisType = AxisType.Secondary
End Sub
' Classes to hold input and output samples
Private Class InputSample
Public Property CurrentSetPoint As Double
Public Property Duration As Double
End Class
Private Class OutputSample
Public Property Current As Double
Public Property Voltage As Double
Public Property Time As Double
End Class
End Class
참고 사항:
"COM8"을 시스템의 적절한 직렬 포트로 교체하십시오.- CSV 파일
example_profile.csv가 올바른 형식이며 애플리케이션 디렉터리에 위치하는지 확인하십시오. - CSV 파일에는 헤더 행과 함께
CurrentSetPoint및Duration두 개의 열이 있어야 합니다.
example_profile.csv 예시:
CurrentSetPoint,Duration
50,10
100,15
150,20
200,25
결론
VB.NET은 Magna-Power 프로그래머블 전력 제품을 제어하기 위한 강력하고 사용자 친화적인 환경을 제공합니다. 직렬 및 TCP/IP 통신을 위한 내장 클래스와 제조사 라이브러리를 통한 GPIB 지원을 통해 VB.NET은 테스트 자동화, 데이터 수집 및 결과 시각화 과정을 간소화합니다. SCPI 명령과 VB.NET의 기능을 활용하여 사용자는 특정 애플리케이션에 맞는 정교한 제어 프로그램을 개발할 수 있습니다.
상세한 SCPI 명령 세트 및 추가 사용자 정의에 대해서는 사용 중인 특정 Magna-Power 제품 시리즈의 사용자 매뉴얼을 참조하십시오.