Writing and Reading Data

Before Performing Read/Write Operations

Communicating with your instrument involves writing and reading data. For example, you might write a text command to a function generator that queries its peak-to-peak voltage, and then read back the voltage value as a double-precision array.

Before performing a write or read operation, you should consider these three questions:

  • What is the process by which data flows from the MATLAB® workspace to the instrument, and from the instrument to the MATLAB workspace?

    The Instrument Control Toolbox™ automatically manages the data transferred between the MATLAB workspace and the instrument. For many common applications, you can ignore the buffering and data flow process. However, if you are transferring a large number of values, executing an asynchronous read or write operation, or debugging your application, you might need to be aware of how this process works.

  • Is the data to be transferred binary (numerical) or text (ASCII)?

    For many instruments, writing text data means writing string commands that change instrument settings, prepare the instrument to return data or status information, and so on. Writing binary data means writing numerical values to the instrument such as calibration or waveform data.

  • Will the write or read function block access to the MATLAB Command Window?

    You control access to the MATLAB Command Window by specifying whether a read or write operation is synchronous or asynchronous. A synchronous operation blocks access to the command line until the read or write function completes execution. An asynchronous operation does not block access to the command line, and you can issue additional commands while the read or write function executes in the background.

There are other issues to consider when you read and write data, like the conditions under which a read or write operation completes. These issues vary depending upon the supported interface and are described in the respective interface-specific chapters.

Writing Data

Functions Associated with Writing Data

Function Name

Description

binblockwrite

Write binblock data to the instrument.

fprintf

Write text to the instrument.

fwrite

Write binary data to the instrument.

stopasync

Stop asynchronous read and write operations.

Properties Associated with Writing Data

Property Name

Description

BytesToOutput

Indicate the number of bytes currently in the output buffer.

OutputBufferSize

Specify the size of the output buffer in bytes.

Timeout

Specify the waiting time to complete a read or write operation.

TransferStatus

Indicate if an asynchronous read or write operation is in progress.

ValuesSent

Indicate the total number of values written to the instrument.

Output Buffer and Data Flow

The output buffer is computer memory allocated by the instrument object to store data that is to be written to the instrument. The flow of data from the MATLAB workspace to your instrument follows these steps:

  1. The data specified by the write function is sent to the output buffer.

  2. The data in the output buffer is sent to the instrument.

The OutputBufferSize property specifies the maximum number of bytes that you can store in the output buffer. The BytesToOutput property indicates the number of bytes currently in the output buffer. The default values for these properties are:

g = gpib('ni',0,1);
g.OutputBufferSize

ans =

   512
g.BytesToOutput

ans =

     0

If you attempt to write more data than can fit in the output buffer, an error is returned and no data is written.

Note

When writing data, you might need to specify a value, which can consist of one or more bytes. This is because some write functions allow you to control the number of bits written for each value and the interpretation of those bits as character, integer or floating-point values. For example, if you write one value from an instrument using the int32 format, then that value consists of four bytes.

For example, suppose you write the string command *IDN? to an instrument using the fprintf function. As shown below, the string is first written to the output buffer as six values.

The *IDN? command consists of six values because the End-Of-String character is written to the instrument, as specified by the EOSMode and EOSCharCode properties. Moreover, the default data format for the fprintf function specifies that one value corresponds to one byte.

As shown below, after the string is stored in the output buffer, it is then written to the instrument.

Writing Text Data Versus Writing Binary Data

For many instruments, writing text data means writing string commands that change instrument settings, prepare the instrument to return data or status information, and so on. Writing binary data means writing numerical values to the instrument such as calibration or waveform data.

You can write text data with the fprintf function. By default, fprintf uses the %s\n format, which formats the data as a string and includes the terminator. You can write binary data with the fwrite function. By default, fwrite writes data using the uchar precision, which translates the data as unsigned 8-bit characters. Both of these functions support many other formats and precisions, as described in their reference pages.

The following example illustrates writing text data and binary data to a Tektronix® TDS 210 oscilloscope. The text data consists of string commands, while the binary data is a waveform that is to be downloaded to the scope and stored in its memory:

  1. Create an instrument object — Create the GPIB object g associated with a National Instruments® GPIB controller with board index 0, and an instrument with primary address 1. The size of the output buffer is increased to accommodate the waveform data. You must configure the OutputBufferSize property while the GPIB object is disconnected from the instrument.

    g = gpib('ni',0,1);
    g.OutputBufferSize = 3000;
  2. Connect to the instrument — Connect g to the instrument.

    fopen(g)
  3. Write and read data — Write string commands that configure the scope to store binary waveform data in memory location A.

    fprintf(g,'DATA:DESTINATION REFA');
    fprintf(g,'DATA:ENCDG SRPbinary');
    fprintf(g,'DATA:WIDTH 1');
    fprintf(g,'DATA:START 1');

    Create the waveform data.

    t = linspace(0,25,2500);
    data = round(sin(t)*90 + 127);

    Write the binary waveform data to the scope.

    cmd = double('CURVE #42500');
    fwrite(g,[cmd data]);

    The ValuesSent property indicates the total number of values that were written to the instrument.

    g.ValuesSent
    ans =
            2577
  4. Disconnect and clean up — When you no longer need g, you should disconnect it from the instrument, remove it from memory, and remove it from the MATLAB workspace.

    fclose(g)
    delete(g)
    clear g

Synchronous Versus Asynchronous Write Operations

By default, all write functions operate synchronously and block the MATLAB Command Window until the operation completes. To perform an asynchronous write operation, you supply the async input argument to the fprintf or fwrite function.

For example, you use the following syntax to modify the fprintf commands used in the preceding example to write text data asynchronously.

fprintf(g,'DATA:DESTINATION REFA','async');

Similarly, you use the following syntax to modify the fwrite command used in the preceding example to write binary data asynchronously.

fwrite(g,[cmd data],'async');

You can monitor the status of the asynchronous write operation with the TransferStatus property. A value of idle indicates that no asynchronous operations are in progress.

g.TransferStatus
ans =
write

You can use the BytesToOutput property to indicate the numbers of bytes that exist in the output buffer waiting to be written to the instrument.

g.BytesToOutput
ans =
        2512

Reading Data

Functions Associated with Reading Data

Function Name

Description

binblockread

Read binblock data from the instrument.

fgetl

Read one line of text from the instrument and discard the terminator.

fgets

Read one line of text from the instrument and include the terminator.

fread

Read binary data from the instrument.

fscanf

Read data from the instrument, and format as text.

readasync

Read data asynchronously from the instrument.

scanstr

Read data from the instrument, format as text, and parse

stopasync

Stop asynchronous read and write operations.

Properties Associated with Reading Data

Property Name

Description

BytesAvailable

Indicate the number of bytes available in the input buffer.

InputBufferSize

Specify the size of the input buffer in bytes.

ReadAsyncMode

Specify whether an asynchronous read is continuous or manual (serial port, TCPIP, UDP, and VISA-serial objects only).

Timeout

Specify the waiting time to complete a read or write operation.

TransferStatus

Indicate if an asynchronous read or write operation is in progress.

ValuesReceived

Indicate the total number of values read from the instrument.

Input Buffer and Data Flow

The input buffer is computer memory allocated by the instrument object to store data that is to be read from the instrument. The flow of data from your instrument to the MATLAB workspace follows these steps:

  1. The data read from the instrument is stored in the input buffer.

  2. The data in the input buffer is returned to the MATLAB variable specified by a read function.

The InputBufferSize property specifies the maximum number of bytes that you can store in the input buffer. The BytesAvailable property indicates the number of bytes currently available to be read from the input buffer. The default values for these properties are:

g = gpib('ni',0,1);
g.InputBufferSize

ans =

   512
g.BytesAvailable

ans =

     0

If you attempt to read more data than can fit in the input buffer, an error is returned and no data is read.

For example, suppose you use the fscanf function to read the text-based response of the *IDN? command previously written to the instrument. The data is first read into the input buffer.

Note that for a given read operation, you might not know the number of bytes returned by the instrument. Therefore, you might need to preset the InputBufferSize property to a sufficiently large value before connecting the instrument object.

As shown below, after the data is stored in the input buffer, it is then transferred to the output variable specified by fscanf.

Reading Text Data Versus Reading Binary Data

For many instruments, reading text data means reading string data that reflect instrument settings, status information, and so on. Reading binary data means reading numerical values from the instrument.

You can read text data with the fgetl, fgets, and fscanf functions. By default, these functions return data using the %c format. You can read binary data with the fread function. By default, fread returns numerical values as double-precision arrays. Both the fscanf and fread functions support many other formats and precisions, as described in their reference pages.

The following example illustrates reading text data and binary data from a Tektronix TDS 210 oscilloscope, which is displaying a periodic input signal with a nominal frequency of 1.0 kHz.

  1. Create an instrument object — Create the GPIB object g associated with a National Instruments GPIB controller with board index 0, and an instrument with primary address 1.

    g = gpib('ni',0,1);
  2. Connect to the instrument — Connect g to the instrument.

    fopen(g)
  3. Write and read data — Write the *IDN? command to the scope, and read back the identification information as text.

    fprintf(g,'*IDN?')
    idn = fscanf(g)
    idn =
    TEKTRONIX,TDS 210,0,CF:91.1CT FV:v1.16 TDS2CM:CMV:v1.04

    Configure the scope to return the period of the input signal, and then read the period as a binary value. The output display format is configured to use short exponential notation for doubles.

    fprintf(g,'MEASUREMENT:MEAS1:TYPE PERIOD')
    fprintf(g,'MEASUREMENT:MEAS1:VALUE?')
    format short e
    period = fread(g,9)'
    period =
        49    46    48    48    54    69    45    51    10

    period consists of positive integers representing character codes, where 10 is a line feed. To convert the period value to a string, use the char function.

    char(period)
    ans =
    1.006E-3

    The ValuesReceived property indicates the total number of values that were read from the instrument.

    g.ValuesReceived
    ans =
         65
  4. Disconnect and clean up — When you no longer need g, you should disconnect it from the instrument, remove it from memory, and remove it from the MATLAB workspace.

    fclose(g)
    delete(g)
    clear g

Synchronous Versus Asynchronous Read Operations

The fgetl, fgets, fscanf, and fread functions operate synchronously and block the MATLAB Command Window until the operation completes. To perform an asynchronous read operation, you use the readasync function. readasync asynchronously reads data from the instrument and stores it in the input buffer. To transfer the data from the input buffer to a MATLAB variable, you use one of the synchronous read functions.

Note

For serial port, TCPIP, UDP, and VISA-serial objects, you can also perform an asynchronous read operation by configuring the ReadAsyncMode property to continuous.

For example, to modify the preceding example to asynchronously read the scope's identification information, you would issue the readasync function after the *IDN? command is written.

fprintf(g,'*IDN?')
readasync(g)

You can monitor the status of the asynchronous read operation with the TransferStatus property. A value of idle indicates that no asynchronous operations are in progress.

g.TransferStatus
ans =
read

You can use the BytesAvailable property to indicate the number of bytes that exist in the input buffer waiting to be transferred to the MATLAB workspace.

g.BytesAvailable
ans =
     56

When the read completes, you can transfer the data as text to a MATLAB variable using the fscanf function.

idn = fscanf(g);