使用 VB.NET 进行仪器编程
本知识库文章介绍了使用 VB.NET 编程语言对 Magna-Power 可编程电源产品进行编程。VB.NET 是一种集成到 Microsoft .NET Framework 中的多功能语言,以其在开发 Windows 应用程序时的简单性和易用性而闻名。其强大的功能使其成为创建程序以控制、进行测量,甚至为可编程仪器创建图的绝佳选择。此外,Magna-Power 对可编程仪器标准命令 (SCPI) 的广泛支持意味着该公司的产品可以通过简单、直观的命令轻松 VB.NET 控制。
Magna-Power 的产品支持多种通信接口,包括 RS-232、TCP/IP 以太网、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 以太网连接
对于 TCP/IP 以太网连接,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 以太网连接发送和接收命令的后续作如下:
writer.WriteLine("*IDN?")
Dim response As String = reader.ReadLine()
Console.WriteLine(response)
IEEE-488 GPIB 连接
对于 IEEE-488 GPIB 连接,您可以使用 GPIB 硬件制造商提供的库,例如 National Instruments 的 NI-488.2 或是德科技的 IO 库套件。在 VB.NET 中,您可以使用 VISA.NET 库与GPIB仪器连接。
使用 VISA.NET 的示例:
首先,确保已安装 VISA.NET 库并在项目中添加引用。Ivi.Visa
Imports Ivi.VisaDim 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 程序。在 VB.NET 中对非 xGen MagnaDC 可编程直流电源进行编程几乎相同,只是对相应产品系列的用户手册中记录的 SCPI 命令进行了细微更改。
示例 1:基本 TCP/IP 以太网控制
此基本示例创建 TCP/IP 以太网连接,发送一些初始化命令,启用直流输出,将电流电平提高到 5 A,等待 20 秒,然后关闭。
Imports System.Net.Sockets
Imports System.IO
Imports System.ThreadingModule ProgramSub Main()' Create a TCP/IP client and connect to the instrumentDim 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 itselfwriter.WriteLine("*IDN?")' Receive the product's response and display it in the consoleDim response As String = reader.ReadLine()Console.WriteLine(response)' Configure the MagnaDC for local controlwriter.WriteLine("CONF:SOUR 0")' Set the DC output current to 0 A before enabling DC outputwriter.WriteLine("CURR 0")' Enable the MagnaDC power supply outputwriter.WriteLine("OUTP:START")' Set the DC output current to 5 Awriter.WriteLine("CURR 5")' Wait 20 secondsThread.Sleep(20000)' Disable the DC outputwriter.WriteLine("OUTP:STOP")' Close the communication channel to the productwriter.Close()reader.Close()client.Close()End Sub
End Module
示例 2:与当前设定点的串行连接
此示例创建与产品的串行连接,确定它是什么产品,然后发送一系列当前命令,每个当前级别之间间隔 20 秒。这种类型的程序也可以扩展为循环显示电压、功率和电阻值。
Imports System.IO.Ports
Imports System.ThreadingModule ProgramSub Main()' Create a serial connection object with default baud rate for MagnaLOADsDim conn As New SerialPort("COM4", 115200)conn.Open()' Send SCPI command requesting the product to identify itselfconn.WriteLine("*IDN?")' Receive the product's response and display it in the consoleDim response As String = conn.ReadLine()Console.WriteLine(response)' Create an array of current set pointsDim currSetPoints() As Integer = {50, 100, 150, 250}' Configure the MagnaDC power supply for local controlconn.WriteLine("CONF:SOUR 0")' Enable the MagnaDC power supply outputconn.WriteLine("OUTP:START")' Loop through each current set pointFor Each currSetpoint In currSetPointsConsole.WriteLine($"Setting Current to {currSetpoint} A")conn.WriteLine($"CURR {currSetpoint}")Thread.Sleep(20000) ' Wait 20 secondsNext' Disable the MagnaDC power supply outputconn.WriteLine("OUTP:STOP")' Close the communication channel to the productconn.Close()End Sub
End Module
示例 3:电池放电并绘制数据
在本例中,xGen MagnaDC 电源被编程为使用从逗号分隔值 (.csv) 文件中读取的设定点和时间对电池进行放电,使用产品的高精度测量命令测量直流输入,然后提供测量数据与时间的关系图。该程序可以进一步扩展以生成 PDF 测试报告,集成测量数据、绘图以及来自其他仪器的信息。
要处理 CSV 文件和 VB.NET 绘图,您可以使用内置类和命名空间进行图表绘制。System.Windows.Forms.DataVisualization.Charting
步骤:
- 创建 Windows 窗体应用程序。
- 从“工具箱”向窗体添加控件。
Chart
- 在窗体的代码隐藏中使用以下代码。
Imports System.IO.Ports
Imports System.Threading
Imports System.IO
Imports System.Windows.Forms.DataVisualization.ChartingPublic Class Form1Private conn As SerialPortPrivate 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 productsconn = New SerialPort("COM8", 115200)conn.Open()' Configure the MagnaDC for local controlconn.WriteLine("CONF:SOUR 0")' Enable the MagnaDC power supply outputconn.WriteLine("OUTP:START")' Read the CSV file containing current set points and durationsDim inputSamples As List(Of InputSample) = ReadCsvFile("example_profile.csv")' Record the start timeDim testStartTime As DateTime = DateTime.Now' Loop through each input sampleFor Each sample In inputSamples' Set the current set pointconn.WriteLine($"CURR {sample.CurrentSetPoint}")' Calculate the stop timeDim stopTime As DateTime = DateTime.Now.AddSeconds(sample.Duration)' Collect measurements until the stop timeWhile DateTime.Now < stopTime' Request measurements from the deviceconn.WriteLine("MEAS:ALL?")' Read the responseDim response As String = conn.ReadLine()Dim measurements() As String = response.Split(","c)' Parse and store the measurementsIf measurements.Length >= 3 ThenDim curr As Double = Double.Parse(measurements(0))Dim volt As Double = Double.Parse(measurements(1))Dim timeElapsed As Double = (DateTime.Now - testStartTime).TotalSecondsoutputSamples.Add(New OutputSample With {.Current = curr,.Voltage = volt,.Time = timeElapsed})End IfThread.Sleep(500) ' Wait for 0.5 secondsEnd WhileNext' Disable the MagnaDC power supply outputconn.WriteLine("OUTP:STOP")' Close the communication channel to the productconn.Close()' Plot the dataPlotData()End SubPrivate 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 linereader.ReadLine()While Not reader.EndOfStreamDim line As String = reader.ReadLine()Dim values() As String = line.Split(","c)If values.Length >= 2 Thensamples.Add(New InputSample With {.CurrentSetPoint = Double.Parse(values(0)),.Duration = Double.Parse(values(1))})End IfEnd WhileEnd UsingReturn samplesEnd FunctionPrivate Sub PlotData()' Configure the chart controlChart1.Series.Clear()Chart1.ChartAreas.Clear()Chart1.ChartAreas.Add(New ChartArea("MainArea"))' Create series for current and voltageDim currentSeries As New Series("Current")currentSeries.ChartType = SeriesChartType.LinecurrentSeries.XValueType = ChartValueType.DoublecurrentSeries.YValueType = ChartValueType.DoubleDim voltageSeries As New Series("Voltage")voltageSeries.ChartType = SeriesChartType.LinevoltageSeries.XValueType = ChartValueType.DoublevoltageSeries.YValueType = ChartValueType.Double' Add data points to the seriesFor Each sample In outputSamplescurrentSeries.Points.AddXY(sample.Time, sample.Current)voltageSeries.Points.AddXY(sample.Time, sample.Voltage)Next' Add series to the chartChart1.Series.Add(currentSeries)Chart1.Series.Add(voltageSeries)' Set chart titles and labelsChart1.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-axisvoltageSeries.YAxisType = AxisType.SecondaryEnd Sub' Classes to hold input and output samplesPrivate Class InputSamplePublic Property CurrentSetPoint As DoublePublic Property Duration As DoubleEnd ClassPrivate Class OutputSamplePublic Property Current As DoublePublic Property Voltage As DoublePublic Property Time As DoubleEnd 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可编程电源产品提供了强大且用户友好的环境。VB.NET 内置串行和TCP/IP通信类,并通过制造商库支持GPIB,简化了自动化测试、收集数据和可视化结果的过程。通过利用 SCPI 命令和 VB.NET 的功能,用户可以开发适合其特定应用程序的复杂控制程序。