Imparare Base di conoscenza
Instrumentation Programming with VB.NET
This knowledge base article introduces programming a Magna-Power programmable power product using the VB.NET programming language. VB.NET is a versatile language integrated into the Microsoft .NET Framework, known for its simplicity and ease of use in developing Windows applications. Its robust features make it an excellent choice for creating programs to control, take measurements, and even create plots for programmable instrumentation. Furthermore, Magna-Power's extensive support for Standard Commands for Programmable Instrumentation (SCPI) means the company's products can be easily controlled in VB.NET with simple, intuitive commands.
Magna-Power's products support a variety of communication interfaces, including RS-232, TCP/IP Ethernet, USB, RS-485, and IEEE-488 GPIB. Despite these different interfaces, the SCPI commands are identical for a particular product series. The SCPI commands are documented in the respective product series' user manual. When creating a VB.NET program, the only difference between interfaces will be the settings for the device connection.
Communication Interfaces
USB, Serial, or RS-485 Connection
For USB, Serial, or RS-485 connections, VB.NET uses the System.IO.Ports.SerialPort
class to create a serial connection to the instrument:
Dim conn As New IO.Ports.SerialPort("COM4", 115200)
conn.Open()
The serial baud rate for xGen products is 115200, while the serial baud rate for non-xGen products is 19200. The port name is defined by your operating system. In Windows, this port can be found in the Device Manager.
Subsequent sending and receiving of commands over the serial connection will be as follows:
conn.WriteLine("*IDN?")
Dim response As String = conn.ReadLine()
Console.WriteLine(response)
TCP/IP Ethernet Connection
For TCP/IP Ethernet connections, VB.NET uses the System.Net.Sockets.TcpClient
class:
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
Subsequent sending and receiving of commands over the TCP/IP Ethernet connection will be as follows:
writer.WriteLine("*IDN?")
Dim response As String = reader.ReadLine()
Console.WriteLine(response)
IEEE-488 GPIB Connection
For IEEE-488 GPIB connections, you can use libraries provided by your GPIB hardware manufacturer, such as National Instruments' NI-488.2 or Keysight's IO Libraries Suite. In VB.NET, you can use the VISA.NET library to interface with GPIB instruments.
Example using VISA.NET:
First, ensure you have the VISA.NET library installed and add a reference to Ivi.Visa
in your project.
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)
In-Depth Examples
The following examples provide more detailed VB.NET programs using an xGen MagnaDC power supply. Programming a non-xGen MagnaDC programmable DC power supply in VB.NET will be almost identical, with subtle changes to the SCPI commands as documented in the respective product series' user manual.
Example 1: Basic TCP/IP Ethernet Control
This basic example creates a TCP/IP Ethernet connection, sends some initialization commands, enables the DC output, raises the current level to 5 A, waits 20 seconds, then shuts down.
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
Example 2: Serial Connection with Current Set Points
This example creates a serial connection to the product, determines what product it is, and then sends a sequence of current commands with 20 seconds between each current level. This type of program can be expanded to cycle through voltage, power, and resistance values as well.
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
Example 3: Discharging a Battery and Plotting Data
In this example, an xGen MagnaDC power supply is programmed to discharge a battery using set points and times read from a comma-separated values (.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.
To handle CSV files and plotting in VB.NET, you can use built-in classes and the System.Windows.Forms.DataVisualization.Charting
namespace for charting.
Steps:
- Create a Windows Forms Application.
- Add a
Chart
control to your form from the Toolbox. - Use the following code in your form's code-behind.
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
Notes:
- Replace
"COM8"
with the appropriate serial port on your system. - Ensure that the CSV file
example_profile.csv
is properly formatted and located in the application's directory. - The CSV file should have two columns:
CurrentSetPoint
andDuration
, with a header row.
Example example_profile.csv
:
CurrentSetPoint,Duration
50,10
100,15
150,20
200,25
Conclusion
VB.NET provides a powerful and user-friendly environment for controlling Magna-Power programmable power products. With built-in classes for serial and TCP/IP communication, as well as support for GPIB via manufacturer libraries, VB.NET simplifies the process of automating tests, collecting data, and visualizing results. By leveraging SCPI commands and VB.NET's features, users can develop sophisticated control programs tailored to their specific applications.
For detailed SCPI command sets and further customization, refer to the user manual of the specific Magna-Power product series you are using.
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.