VB .NET

Agilent VISA.NET

VB .NET

Now that you have referenced the header file in your project, you can begin development with the VISA functions it contains.  This sample demonstrates the simplest VISA transaction.

VB .NET

Private Sub RunSimple()    Dim resourceManager As Integer = 0, viError As Integer    Dim session As Integer = 0    viError = visa32.viOpenDefaultRM(resourceManager)    viError = visa32.viOpen(resourceManager, "GPIB0::22::INSTR", _                    visa32.VI_NO_LOCK, visa32.VI_TMO_IMMEDIATE, session)    viError = visa32.viPrintf(session, "*IDN?" & vbLf)    Dim idnString As System.Text.StringBuilder = _                    New System.Text.StringBuilder(1000)    viError = visa32.viScanf(session, "%1000s", idnString)    MsgBox(idnString.ToString())    visa32.viClose(session)    visa32.viClose(resourceManager) End Sub

C#

private void RunSimple() { int resourceManager = 0, viError; int session = 0; viError = visa32.viOpenDefaultRM(out resourceManager); viError = visa32.viOpen(resourceManager, "GPIB0::22::INSTR", visa32.VI_NO_LOCK, visa32.VI_TMO_IMMEDIATE, out session); viError = visa32.viPrintf(session, "*IDN?\n"); System.Text.StringBuilder idnString = new System.Text.StringBuilder(1000); viError = visa32.viScanf(session, "%1000s", idnString); System.Windows.Forms.MessageBox.Show(idnString.ToString()); visa32.viClose(session); visa32.viClose(resourceManager); }

This is the "IDN?" query in .NET.  You may have noticed the use of the StringBuilder class.  The System.String class in .NET is meant to have an immutable payload, meaning that once you define a string, it is either used or thrown away -- never modified.  Since the viScanf function modifies the contents of the parameter you pass it, the System.String class is illegal for this call.  The designers of .NET were aware of this, so they gave the StringBuilder class the ability to look like a string buffer when it is passed to C DLL functions.  

You need to allocate a sufficiently large buffer for the contents of the read operation, which is why the buffer is allocated 1000-long and why the format string passed to viScanf, "%1000s", tells it that there is room in the buffer for 1000 characters.  The MessageBox knows how much of the buffer to write because viScanf appends an ASCII code (0) when it is done reading, and the StringBuilder class interprets this as the end of the valid data when you call StringBuilder.ToString().

This solution works perfectly under normal conditions, but what about unexpected errors?  What if you're reading in arrays of data?  There are some more techniques to ease debugging and deployment issues with VISA in .NET, as well as some advanced formatted I/O techniques to review.

Next: Adding Error Handling to Your Project