VectorStar™ MS4640A SeriesMicrowave Vector Network Analyzer : Appendix D — Programming Basics with Legacy Software : VISA and C# Programming Examples
 
VISA and C# Programming Examples
This section includes a few simple Console-based programs to demonstrate the use of the NI-VISA driver for controlling the MS4640A Series VNA.
Create a New Console Application Project
New Project in Visual Studio
Add references for National Instruments Common and National Instruments VisaNS. The following shows the .NET 3.5 versions of these DLLs.
Adding a Reference
For simple programs (like all the examples below), only these three references are required.
Solution Explorer
If the references are set up correctly, copy and paste the code into the Program.cs file.
Build the Solution
Build Solution
Run the Code (Start Debugging).
Example Debug Menu
Each of the following examples include the complete program code.
Example 1 – Opening a Session and Sending the *IDN? Command
using System;
using NationalInstruments.VisaNS;
namespace Example1
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
//response string
string responseString = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Send "*IDN?" command
mbSession.Write("*IDN?\n");
//Read the response
responseString = mbSession.ReadString();
//Write to Console
Console.WriteLine("Response to *IDN?:");
Console.WriteLine(responseString);
//Return to Local Control
mbSession.Write("RTL\n");
//Close the Session
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
Console.WriteLine();
}
keepConsoleUp();
}
private static void keepConsoleUp()
{
Console.WriteLine("");
Console.WriteLine("Enter to Continue");
Console.ReadLine();
}
}
}
Example 1 Discussion
Program Output
1. Examine the program output.
2. The console output should look something like the following if everything worked. The result is Manufacturer, Model, Serial Number, and Firmware Version.
Program Output
 
Address String
3. Check the Address String.
4. If the example did not work, check that the Address string matches your setup. The following error results if the address is wrong or the connection string is no good:
Error Result
5. The first thing to observe is the VISA connection string. Here are some possible strings:
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.194::INSTR";
//GPIB Connection string
string sAddress = "GPIB0::6::INSTR";
//USB Connection string (vendor::product::serial_number)
string sAddress = "USB0::0x0B5B::0xFFD0::MS4647A-12345::INSTR";
6. When using VISA, the only thing that needs to be changed for any of these possible communication protocols is the connection string. The rest of the code should be exactly the same (except for SOCKETS). VXI-11 should be used for TCP/IP since it implements the IEEE 488.2 standard and all status checking.
7. The connection string for a TCP/IP socket connection is:
//TCP/IP Sockets Connection string
string sAddress = "TCPIP0::10.0.1.194::5001::SOCKET";
8. Opening the communication session:
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
9. Write to VNA and Read from VNA:
//Send "*IDN?" command
mbSession.Write("*IDN?\n");
//Read the response
responseString = mbSession.ReadString();
Notice that the mbSession.Write() commands are terminated with a “/n”. This is the newline character.
Session Parameters
10. The next example discusses session parameters. Some of the other examples will get into reading binary data and arbitrary block data.
Exception Handling
11. The VISA driver catches certain types of errors like time-outs and .NET catches the rest.
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
Console.WriteLine();
}
The VisaException function catches a time-out on a ReadString().
Error Catching
 
Close the Session
12. Close the session using Dispose():
//Close the Session
mbSession.Dispose();
Example 2 – Session Parameters and Status Checking
using System;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example2
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Now set some Session Parameters
//Timeout to 1 second (1000 ms)
mbSession.Timeout = 1000;
//use newline (\n or 0x0a) as termination character
mbSession.TerminationCharacter = 0x0a;
//terminate reads if the termination character is spotted
mbSession.TerminationCharacterEnabled = false;
//Assert an END during the transfer of the last byte of data
mbSession.SendEndEnabled = true;

//Send a *CLS
testClear(mbSession);
//Now try a few commands - first *IDN?
//Note that the \n is not included in these strings
mbSession.Write("LANG NATIVE");
mbSession.Write("*IDN?");
Console.WriteLine("Response to *IDN?:");
testStatus_Read(mbSession);
//OID returns an instrument ID string
mbSession.Write("OID");
Console.WriteLine("Response to OID:");
testStatus_Read(mbSession);
//*OPT? returns the installed instrument options
mbSession.Write("*OPT?");
Console.WriteLine("Response to *OPT?:");
testStatus_Read(mbSession);
//This command doesn't exist,check that we catch it
mbSession.Write("ABC");
Console.WriteLine("Test ABC:");
testStatus(mbSession);
//this command is OK, no response is expected
mbSession.Write("CH3");
Console.WriteLine("Test CH3:");
testStatus(mbSession);
//Return to Local Control
mbSession.Write("RTL\n");
//Close the Session
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
keepConsoleUp();
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
//This function tests the Service Request Status Register
//and does a read if MAV is set.
//It prints an error message if any error is reported.
private static void testStatus_Read(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();
string responseString = null;
while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
responseString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + responseString);
}
else if (((int)sb & b4) != 0)
{
responseString = mbSession.ReadString();
Console.WriteLine(responseString);
}
mbSession.Write("*CLS\n");
}
//This function tests the Service Request Status Register.
//It prints an error message if any error is reported.
private static void testStatus(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4; //Error Queue is not empty
//Read the Status Byte of Service Request Status Register
//wait 50 ms
Thread.Sleep(50);
//then check status
StatusByteFlags sb = mbSession.ReadStatusByte();
string responseString = null;
if (((int)sb & b2) != 0)
{
responseString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + responseString);
}
else
{
Console.WriteLine("OK");
}
mbSession.Write("*CLS\n");
}
private static void keepConsoleUp()
{
Console.WriteLine("");
Console.WriteLine("Enter to Continue");
Console.ReadLine();
}
}
}
Example 2 Discussion
Status Byte Checks
1. This example checks the Status Byte prior to reading the response. The Status Byte is the Service Request Status Register and is discussed in Status Group Reporting. LANG is set to NATIVE to use the MS4640A Series VNA Status Register Configuration. In general, a Message Available (MAV) response is expected when data is available to read. Otherwise, something else is expected to be in the Error Queue (ERRQ). Notice when the code sends an unknown command “ABC”, the testStatus() function catches it and outputs the message in the Error Queue.
2. The response is slightly changed from Native to Lightning. If LANG LIGHT is set, then the Lightning configuration of the Status Register is used.
The Service Request Status Register
Expected Output
Error message after sending the “ABC” command
Example 3 – Sending Data to a File with the LIST Command
using System;
using System.IO;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example3
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
string responseString = null;
string[] split = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Timeout to 1 second (1000 ms)
mbSession.Timeout = 1000;
mbSession.TerminationCharacter = 0x0a;
mbSession.TerminationCharacterEnabled = false;
mbSession.SendEndEnabled = true;
//We're expected a lot of response data to the LIST command
mbSession.DefaultBufferSize = 50000;
testClear(mbSession);
//Set the Language to NATIVE and send the LIST command
mbSession.Write("LANG NATIVE\n");
mbSession.Write("LIST\n");
responseString = testStatus_Read(mbSession);
//the results are delimited by a newline (\n)
split = responseString.Split('\n');
//Send results to a file
StreamWriter output = new StreamWriter("List.txt");
foreach (string s in split)
output.WriteLine(s);
output.Close();
mbSession.Write("RTL\n");
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
keepConsoleUp();
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
private static void keepConsoleUp()
{
Console.WriteLine("");
Console.WriteLine("Enter to Continue");
Console.ReadLine();
}
//This function tests the Service Request Status Register
//and does a read if MAV is set.
//It prints an error message if any error is reported.
private static string testStatus_Read(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();
string responseString = null;
string errorString = null;
while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
errorString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + errorString);
}
else if (((int)sb & b4) != 0)
{
responseString = mbSession.ReadString();
}
mbSession.Write("*CLS\n");
return responseString;
}
}
}
 
 
Example 3 Discussion
1. This example and the next few examples do not write anything to the Console unless there is an error. Output is sent to a file in the same directory of the running program (\Example3\Bin\Debug\List.txt):
List of all commands supported by the MS4640A Series VNA
 
Use of LANG LIGHT
2. Use LANG LIGHT – Lightning has the same command, but is comma delimited:
//Set the Language to LIGHTNING and send the LIST command
mbSession.Write("LANG LIGHT\n");
mbSession.Write("LIST\n");
responseString = testStatus_Read(mbSession);
//the results are delimited by a comma
split = responseString.Split(',');
Anritsu GPIB, USB, VXI-11 Exerciser
3. Use the Anritsu GPIB, USB, VXI-11 Exerciser to get more help on any command. Help will tell you what type of command (Native, Lightning, HP8510) and provides syntax.
Anritsu GPIB, USB, VXI-11 Exerciser
 
Example 4 – Acquiring ASCII Data, Arbitrary Block
using System;
using System.Text;
using System.IO;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example4
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
string responseStringN = null;
string responseStringL = null;
string[] splitN = null;
string[] splitL = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Timeout to 1 second (1000 ms)
mbSession.Timeout = 1000;
mbSession.TerminationCharacter = 0x0a;
mbSession.TerminationCharacterEnabled = false;
mbSession.SendEndEnabled = true;
//We'll limit the number of data points to keep buffer small
mbSession.DefaultBufferSize = 5000;
testClear(mbSession);
//Set the Language to NATIVE
mbSession.Write("LANG NATIVE\n");
mbSession.Write(":SENSE:SWEEP:POINTS 5\n");
mbSession.Write("CH1;SMI;\n");
mbSession.Write("TRS;WFS;HLD\n");
mbSession.Write("FMA;OFD\n");
responseStringN = testStatus_ReadArb(mbSession);
//the results are delimited by a newline (\n)
splitN = responseStringN.Split('\n');
//Set the Language to LIGHTNING
mbSession.Write("LANG LIGHT\n");
mbSession.Write("FMA;OFD\n");
responseStringL = testStatus_ReadArb(mbSession);
//the results are delimited by a comma
splitL = responseStringL.Split(',');
//Send results to a file
StreamWriter output = new StreamWriter("OFD.txt");
output.WriteLine("Native Results");
foreach (string s in splitN)
output.WriteLine(s);

output.WriteLine("Lightning Results");
foreach (string s in splitL)
output.WriteLine(s);
output.Close();
mbSession.Write("RTL\n");
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
private static string testStatus_ReadArb(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
string responseString = null;
string replyString = null;
string errorString = null;
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();

while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
errorString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + errorString);
}
else if (((int)sb & b4) != 0)
{
responseString = mbSession.ReadString();
replyString = stripHeader(responseString);

}
mbSession.Write("*CLS\n");
return replyString;
}
private static string stripHeader(string responseString)
{
int i = 0;
string strReturn = null;
if (responseString[i++] == '#')
{
//Header is ASCII, get 2nd byte and convert to int
StringBuilder sCount = new StringBuilder(responseString, i++, 1, 1);
int count1 = int.Parse(sCount.ToString());
//now read the bytecount string and convert to int
StringBuilder sBytes = new StringBuilder(responseString,i,count1,count1);
int count2 = int.Parse(sBytes.ToString());
//set the index of the start of the data
i += count1;
//return the string with the header stripped off
strReturn = responseString.Substring(i);
}
return strReturn;
}
}
}
 
Example 4 Discussion
Output Results
1. Output result values are the same for Native mode and Lightning mode (since the unit is in HOLD), but the delimiters are different. Native mode uses a comma delimiters to separate the two values at each frequency and a newline (\n) to separate pairs of values. Lightning mode separates each value with a comma. The display was set for Smith Chart, impedance.
OFD Output File and Trace Display
 
OFD Command
2. The OFD command returns an arbitrary block containing either ASCII or Binary data depending on the currently selected format. This example selects ASCII using the FMA command. The Arbitrary block header is stripped off with the stripHeader(string responseString) function. The next example shows how to get binary data.
Example 5 – Acquiring Binary Data, Arbitrary Block
using System;
using System.Text;
using System.IO;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example5
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
double[] responseArray = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Timeout to 1 second (1000 ms)
mbSession.Timeout = 1000;
mbSession.TerminationCharacter = 0x0a;
mbSession.TerminationCharacterEnabled = false;
mbSession.SendEndEnabled = true;
//We'll limit the number of data points to keep buffer small
mbSession.DefaultBufferSize = 5000;
testClear(mbSession);
//Set the Language to NATIVE
mbSession.Write("LANG NATIVE\n");
mbSession.Write("CH2;MPH;\n");
mbSession.Write(":SENSE:SWEEP:POINTS 8\n");
mbSession.Write("TRS;WFS;HLD\n");
mbSession.Write("LSB;FMB;OFD\n");
responseArray = testStatus_ReadArbBinaryDouble(mbSession);

//Send results to a file
StreamWriter output = new StreamWriter("OFD.txt");
output.WriteLine("Native Results (Mag-Phase)");
foreach (double d in responseArray)
output.WriteLine(d);
output.Close();
mbSession.Write("RTL\n");
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
}
private static double[] testStatus_ReadArbBinaryDouble(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
byte[] responsebytes = null;
double[] replybytes = null;
string errorString = null;
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();
while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
errorString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + errorString);
}
else if (((int)sb & b4) != 0)
{
responsebytes = mbSession.ReadByteArray();
replybytes = arbToDouble(responsebytes);
}
mbSession.Write("*CLS\n");
return replybytes;
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
//Here we convert Arb Block Binary Data to a double array
private static double[] arbToDouble(byte[] responseBytes)
{
int i = 0;
double[] dReturn = null;
//Arbitrary Block should start with a #
if (responseBytes[i++] == '#')
{
//Header is ASCII, get 2nd byte and convert to int
string sCount = ASCIIEncoding.ASCII.GetString(responseBytes, i++, 1);
int count1 = int.Parse(sCount);
//now read the bytecount string and convert to int
string sBytes = ASCIIEncoding.ASCII.GetString(responseBytes, i, count1);
int count2 = int.Parse(sBytes);
//the number of doubles is the #bytes/sizeof(double)
int dataCount = count2 / sizeof(double);
//resize the response array
dReturn = new double[dataCount];
//set the index of the start of the data
i += count1;
//There are many ways to convert a byte array to a double array
MemoryStream stream = new MemoryStream(responseBytes, i, count2);
//BinaryReader reads this data type in little-endian format
//So we must use the LSB mnemonic when acquiring the data
BinaryReader reader = new BinaryReader(stream);
for (int ii = 0; ii < dataCount; ii++)
{
dReturn[ii] = reader.ReadDouble();
}
}
return dReturn;
}
}
}
 
Example 5 Discussion
Output File
1. Output file from this program should be in \Example5\bin\Debug\OFD.txt:
Binary Output, Arbitrary Block
Example 6 – Output S2P File
using System;
using System.Text;
using System.IO;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example7
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
string responseStringN = null;
string[] splitN = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Timeout to 3 second (1000 ms)
mbSession.Timeout = 3000;
mbSession.TerminationCharacter = 0x0a;
mbSession.TerminationCharacterEnabled = false;
mbSession.SendEndEnabled = true;
//We'll limit the number of data points to keep buffer small
mbSession.DefaultBufferSize = 5000;
testClear(mbSession);
//Set the Language to NATIVE
mbSession.Write("LANG NATIVE\n");
mbSession.Write(":SENSE:SWEEP:POINTS 25\n");
//set format to Hz and Re/Im
mbSession.Write(":FORM:SNP:FREQ HZ\n");
mbSession.Write(":FORM:SNP:PAR REIM\n");
//Output S2P file over GPIB
mbSession.Write("TRS;WFS;OS2P\n");
responseStringN = testStatus_ReadArb(mbSession);
//the results are delimited by a newline (\n)
splitN = responseStringN.Split('\n');
//Send results to a file
StreamWriter output = new StreamWriter("VS_S2P.s2p");
foreach (string s in splitN)
output.WriteLine(s);
output.Close();
mbSession.Write("RTL\n");
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
private static string testStatus_ReadArb(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
string responseString = null;
string replyString = null;
string errorString = null;
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();
while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
errorString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + errorString);
}
else if (((int)sb & b4) != 0)
{
responseString = mbSession.ReadString();
replyString = stripHeader(responseString);
}
mbSession.Write("*CLS\n");
return replyString;
}
private static string stripHeader(string responseString)
{
int i = 0;
string strReturn = null;
if (responseString[i++] == '#')
{
//Header is ASCII, get 2nd byte and convert to int
StringBuilder sCount = new StringBuilder(responseString, i++, 1, 1);
int count1 = int.Parse(sCount.ToString());
//now read the bytecount string and convert to int
StringBuilder sBytes = new StringBuilder(responseString, i, count1, count1);
int count2 = int.Parse(sBytes.ToString());
//set the index of the start of the data
i += count1;
//return the string with the header stripped off
strReturn = responseString.Substring(i);
}
return strReturn;
}
}
}
Example 6 Discussion
Expected output is in \Example7\Bin\Debug\VS_S2P.s2p
Transfer of an S2P file to the PC
Example 7 – Output a Bitmap
using System;
using System.Text;
using System.IO;
using NationalInstruments.VisaNS;
using System.Threading;
namespace Example6
{
class Program
{
static void Main(string[] args)
{
//VXI-11 Connection string
string sAddress = "TCPIP0::10.0.1.196::INSTR";
//The VNA uses a message based session
MessageBasedSession mbSession = null;
//But we'll just open a generic Session first
Session mySession = null;
byte[] responseArray = null;
try
{
//open a Session to the VNA
mySession = ResourceManager.GetLocalManager().Open(sAddress);
//cast this to a message based session
mbSession = (MessageBasedSession)mySession;
//Timeout to 3 seconds (3000 ms)
mbSession.Timeout = 3000;
mbSession.TerminationCharacter = 0x0a;
mbSession.TerminationCharacterEnabled = false;
mbSession.SendEndEnabled = true;
//We expect about 534k bytes
mbSession.DefaultBufferSize = 600000;
testClear(mbSession);
//Set the Language to LIGHT,
mbSession.Write("LANG LIGHT\n");
//set color on white and output bitmap over GPIB
mbSession.Write("BMPC;OBMP\n");
responseArray = testStatus_ReadArbBinaryByte(mbSession);
//Send results to a new Binary file
BinaryWriter output = new BinaryWriter(File.Open("VS.bmp", FileMode.Create));
output.Write(responseArray);
output.Close();
mbSession.Write("RTL\n");
mbSession.Dispose();
}
catch (VisaException v_exp)
{
Console.WriteLine("Visa caught an error!!");
Console.WriteLine(v_exp.Message);
}
catch (Exception exp)
{
Console.WriteLine("Something didn't work!!");
Console.WriteLine(exp.Message);
}
}
private static byte[] testStatus_ReadArbBinaryByte(MessageBasedSession mbSession)
{
//These are the bits to check
int b2 = 4, //Error Queue is not empty
b4 = 16; //MAV = Message Available
byte[] responsebytes = null;
byte[] replybytes = null;
string errorString = null;
//Read the Status Byte of Service Request Status Register
StatusByteFlags sb = mbSession.ReadStatusByte();
while (((int)sb & (b2 + b4)) == 0)
{
Thread.Sleep(10);
sb = mbSession.ReadStatusByte();
}
if (((int)sb & b2) != 0)
{
errorString = mbSession.Query("OGE\n");
Console.WriteLine("Error Queue: " + errorString);
}
else if (((int)sb & b4) != 0)
{
responsebytes = mbSession.ReadByteArray();
replybytes = arbToByte(responsebytes);
}
mbSession.Write("*CLS\n");
return replybytes;
}
private static void testClear(MessageBasedSession mbSession)
{
mbSession.Write("*CLS\n");
}
//Convert Arb Block Binary Data to Byte array
private static byte[] arbToByte(byte[] responseBytes)
{
int i = 0;
byte[] dReturn = null;
//Arbitrary Block should start with a #
if (responseBytes[i++] == '#')
{
//Header is ASCII, get 2nd byte and convert to int
string sCount = ASCIIEncoding.ASCII.GetString(responseBytes, i++, 1);
int count1 = int.Parse(sCount);
//now read the bytecount string and convert to int
string sBytes = ASCIIEncoding.ASCII.GetString(responseBytes, i, count1);
int count2 = int.Parse(sBytes);
//the number of doubles is the #bytes/sizeof(double)
int dataCount = count2 / sizeof(byte);
//resize the response array
dReturn = new byte[dataCount];
//set the index of the start of the data
i += count1;
MemoryStream stream = new MemoryStream(responseBytes, i, count2);
//BinaryReader reads this data type in little-endian format
//So we must use the LSB mnemonic when acquiring the data
BinaryReader reader = new BinaryReader(stream);
for (int ii = 0; ii < dataCount; ii++)
{
dReturn[ii] = reader.ReadByte();
}
}
return dReturn;
}
}
}
Example 7 Discussion
The output should be in \Example6\Bin\Debug\VS.bmp
Results from Example 6
 
Bitmap Properties