Writing and Reading Data

Asynchronous Write and Read Operations

These functions are associated with reading and writing text asynchronously:

FunctionPurpose
fprintfWrite text to an instrument.
readasyncAsynchronously read bytes from an instrument.
stopasyncStop an asynchronous read or write operation.

These properties are associated with reading and writing text asynchronously:

PropertyPurpose
BytesAvailableIndicates the number of bytes available in the input buffer.
TransferStatusIndicates what type of asynchronous operation is in progress.
ReadAsyncModeIndicates whether data is read continuously in the background or whether you must call the readasync function to read data asynchronously.

Additionally, you can use all the callback properties during asynchronous read and write operations.

Asynchronous write and read operations do not block access to the MATLAB® Command Window. Additionally, while an asynchronous operation is in progress you can

  • Execute a read (write) operation while an asynchronous write (read) operation is in progress. This is because serial ports have separate pins for reading and writing.

  • Make use of all supported callback properties. Refer to Events and Callbacks for more information about the callback properties supported by serial port objects.

The process of writing data asynchronously is given in Synchronous Versus Asynchronous Write Operations.

For a general overview about writing and reading data, as well as a list of all associated functions and properties, refer to Communicating with Your Instrument.

Asynchronous Read Operations

For serial port objects, you specify whether read operations are synchronous or asynchronous with the ReadAsyncMode property. You can configure ReadAsyncMode to continuous or manual.

If ReadAsyncMode is continuous (the default value), the serial port object continuously queries the instrument to determine if data is available to be read. If data is available, it is asynchronously stored in the input buffer. To transfer the data from the input buffer to the MATLAB workspace, you use one of the synchronous (blocking) read functions such as fgetl, fgets, fscanf, or fread. If data is available in the input buffer, these functions will return quickly.

    Note:   This example is Windows® specific.

s = serial('COM1');
fopen(s)
s.ReadAsyncMode = 'continuous';
fprintf(s,'*IDN?')
s.BytesAvailable
ans =
    56
out = fscanf(s);

If ReadAsyncMode is manual, the serial port object does not continuously query the instrument to determine if data is available to be read. To read data asynchronously, you use the readasync function. You then use one of the synchronous read functions to transfer data from the input buffer to the MATLAB workspace.

s.ReadAsyncMode = 'manual';
fprintf(s,'*IDN?')
s.BytesAvailable
ans =
    0
readasync(s)
s.BytesAvailable
ans =
    56
out = fscanf(s);

Writing and Reading Asynchronous Data

This example explores asynchronous read and write operations using a serial port object. The instrument used was a Tektronix(R) TDS 210 oscilloscope.

To begin, create a serial port object associated with the COM1 port. The oscilloscope is configured to a baud rate of 9600, 1 stop bit, a line feed terminator, no parity, and no flow control.

s = serial('COM1');
s.Baudrate=9600;
s.StopBits=1;
s.Terminator='LF';
s.Parity='none';
s.FlowControl='none';

Before you can perform a read or write operation, you must connect the serial port object to the instrument with the fopen function.

fopen(s);

If the object was successfully connected, its Status property is automatically configured to open.

s.Status
ans = 
    open

To begin, read data continuously.

s.ReadAsyncMode='continuous';

Now, query the instrument for the peak-to-peak value of the signal on channel 1.

fprintf(s, 'Measurement:Meas1:Source CH1');
fprintf(s, 'Measurement:Meas1:Type Pk2Pk');
fprintf(s, 'Measurement:Meas1:Value?');

Allow time for a response. In a typical application this is where you could do other tasks.

pause(0.5);

Since the ReadAsyncMode property is set to continuous, the object is continuously asking the instrument if any data is available. Once the last fprintf function completes, the instrument begins sending data; the data is read from the instrument and is stored in the input buffer.

s.BytesAvailable
ans =
    14

You can bring the data from the object's input buffer into the MATLAB workspace with fscanf.

data = fscanf(s)
data =
    5.99999987E-2

Next, read the data manually.

s.ReadAsyncMode='manual';

Now, query the instrument for the frequency of the signal on channel 1.

fprintf(s, 'Measurement:Meas2:Source CH1');
fprintf(s, 'Measurement:Meas2:Type Freq');
fprintf(s, 'Measurement:Meas2:Value?');

Allow time for a response. In a typical application this is where you could do other tasks.

pause(0.5);

Once the last fprintf function completes, the instrument begins sending data. However, since ReadAsyncMode is set to manual, the object is not reading the data being sent from the instrument. Therefore, no data is being read and placed in the input buffer.

s.BytesAvailable
ans =
     0

Read the data.

readasync(s);

Allow time for a response.

pause(0.5);

It is important to remember that when the serial port object is in manual mode (the ReadAsyncMode property is configured to manual), data that is sent from the instrument to the computer is not automatically stored in the input buffer of the connected serial port object. Data is not stored until readasync or one of the blocking read functions is called.

Manual mode should be used when a stream of data is being sent from your instrument and you only want to capture portions of the data.

Defining an Asynchronous Read Callback

Continuing the example from the previous section, configure the serial object to notify you when a terminator has been read.

s.ReadAsyncMode='continuous';
s.BytesAvailableFcn={'dispcallback'};

Note, the default value for the BytesAvailableFcnMode property indicates that the callback function defined by the BytesAvailableFcn property will be executed when the terminator has been read.

s.BytesAvailableFcnMode
ans =
    terminator

The dispcallback function displays a message containing the type of the event, the name of the object that caused the event to occur, and the time the event occurred.

 callbackTime = datestr(datenum(event.Data.AbsTime));
 fprintf(['A ' event.Type ' event occurred for ' obj.Name ' at ' 
     callbackTime '.\n']);

Query the instrument for the period of the signal on channel 1. Once the terminator is read from the instrument and placed in the input buffer, dispcallback is executed and a message is posted to the MATLAB command window indicating that a BytesAvailable event occurred.

fprintf(s, 'Measurement:Meas3:Source CH1')
fprintf(s, 'Measurement:Meas3:Type Period')
fprintf(s, 'Measurement:Meas3:Value?')

Allow time for a response.

pause(0.5);
A BytesAvailable event occurred for Serial-COM1 at <date and time>.
s.BytesAvailable
ans =
    7
data = fscanf(s, '%c', 10)
data =

    2.0E-6

Note that the last value read is the line feed (10).

Now suppose that halfway through the asynchronous read operation, you realize that the signal displayed on the oscilloscope was incorrect. Rather than waiting for the asynchronous operation to complete, you can use the stopasync function to stop the asynchronous read. Note that if an asynchronous write was in progress, the asynchronous write operation would also be stopped.

s.BytesAvailableFcn='';
fprintf(s, 'Curve?');
pause(0.25);
S.BytesAvailable

ans =
    126

stopasync(s);
s.BytesAvailable

ans =
    262

The data that has been read from the instrument remains in the input buffer. You can use one of the synchronous read functions to bring this data into the MATLAB workspace. However, since this data represents the wrong signal, the flushinput function is called to remove all data from the input buffer.

flushinput(s);
s.BytesAvailable

ans =
    0

You can perform an asynchronous write with the fprintf or fwrite functions by passing 'async' as the last input argument.

fprintf(s, 'Measurement:Meas3:Value?', 'async')

If you are finished with the serial port object, disconnect it from the instrument, remove it from memory, and remove it from the workspace.

fclose(s);
delete(s);
clear s

Rules for Completing Write and Read Operations

The rules for completing synchronous and asynchronous read and write operations are described below.

Completing Write Operations

A write operation using fprintf or fwrite completes when one of these conditions is satisfied:

  • The specified data is written.

  • The time specified by the Timeout property passes.

In addition to these rules, you can stop an asynchronous write operation at any time with the stopasync function.

A text command is processed by the instrument only when it receives the required terminator. For serial port objects, each occurrence of \n in the ASCII command is replaced with the Terminator property value. Because the default format for fprintf is %s\n, all commands written to the instrument will end with the Terminator value. The default value of Terminator is the line feed character. The terminator required by your instrument will be described in its documentation.

Completing Read Operations

A read operation with fgetl, fgets, fscanf, or readasync completes when one of these conditions is satisfied:

  • The terminator specified by the Terminator property is read.

  • The time specified by the Timeout property passes.

  • The input buffer is filled.

  • The specified number of values is read (fscanf and readasync only).

A read operation with fread completes when one of these conditions is satisfied:

  • The time specified by the Timeout property passes.

  • The specified number of values is read.

    Note:   Set the terminator property to '' (null), if appropriate, to ensure efficient throughput of binary data.

In addition to these rules, you can stop an asynchronous read operation at any time with the stopasync function.

Writing and Reading Text Data

This example illustrates how to communicate with a serial port instrument by writing and reading text data.

The instrument is a Tektronix® TDS 210 two-channel oscilloscope connected to the serial port COM1. Therefore, many of the commands given below are specific to this instrument. A sine wave is input into channel 2 of the oscilloscope, and your job is to measure the peak-to-peak voltage of the input signal.

These functions are used when reading and writing text:

FunctionPurpose
fprintfWrite text to an instrument.
fscanfRead data from an instrument and format as text.

These properties are associated with reading and writing text:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the instrument.
ValuesSentSpecifies the total number of values sent to the instrument.
InputBufferSizeSpecifies the total number of bytes that can be queued in the input buffer at one time.
OutputBufferSizeSpecifies the total number of bytes that can be queued in the output buffer at one time.
TerminatorCharacter used to terminate commands sent to the instrument.

    Note:   This example is Windows specific.

  1. Create a serial port object — Create the serial port object s associated with serial port COM1.

    s = serial('COM1');
  2. Connect to the instrument — Connect s to the oscilloscope. Because the default value for the ReadAsyncMode property is continuous, data is asynchronously returned to the input buffer as soon as it is available from the instrument.

    fopen(s)
  3. Write and read data — Write the *IDN? command to the instrument using fprintf, and then read back the result of the command using fscanf.

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

    You need to determine the measurement source. Possible measurement sources include channel 1 and channel 2 of the oscilloscope.

    fprintf(s,'MEASUREMENT:IMMED:SOURCE?')
    source = fscanf(s)
    source =
    CH1

    The scope is configured to return a measurement from channel 1. Because the input signal is connected to channel 2, you must configure the instrument to return a measurement from this channel.

    fprintf(s,'MEASUREMENT:IMMED:SOURCE CH2')
    fprintf(s,'MEASUREMENT:IMMED:SOURCE?')
    source = fscanf(s)
    source =
    CH2

    You can now configure the scope to return the peak-to-peak voltage, and then request the value of this measurement.

    fprintf(s,'MEASUREMENT:MEAS1:TYPE PK2PK')
    fprintf(s,'MEASUREMENT:MEAS1:VALUE?')

    Transfer data from the input buffer to the MATLAB workspace using fscanf.

    ptop = fscanf(s)
    ptop =
    2.0199999809E0
  4. Disconnect and clean up — When you no longer need s, you should disconnect it from the instrument, and remove it from memory and from the MATLAB workspace.

    fclose(s)
    delete(s)
    clear s

Usage Notes for Writing ASCII Data

By default, the fprintf function operates in a synchronous mode. This means that fprintf blocks the MATLAB command line until one of the following occurs:

  • All the data is written

  • A timeout occurs as specified by the Timeout property

By default the fprintf function writes ASCII data using the %s\n format. All occurrences of \n in the command being written to the instrument are replaced with the Terminator property value. When using the default format, %s\n, all commands written to the instrument will end with the Terminator character.

For the previous command, the linefeed (LF) is sent after 'Hello World 123' is written to the instrument, thereby indicating the end of the command.

You can also specify the format of the command written by providing a third input argument to fprintf. The accepted format conversion characters include: d, i, o, u, x, X, f, e, E, g, G, c, and s.

ASCII Write Properties

The OutputBufferSize property specifies the maximum number of bytes that can be written to the instrument at once. By default, OutputBufferSize is 512.

s.OutputBufferSize
ans = 
    512

The ValuesSent property indicates the total number of values written to the instrument since the object was connected to the instrument.

s.ValuesSent
ans = 
    40

Usage Notes for Reading ASCII Data

By default, the fscanf function reads data using the '%c' format and blocks the MATLAB command line until one of the following occurs:

  • The terminator is received as specified by the Terminator property

  • A timeout occurs as specified by the Timeout property

  • The input buffer is filled

  • The specified number of values is read

You can also specify the format of the data read by providing a second input argument to fscanf. The accepted format conversion characters include: d, i, o, u, x, X, f, e, E, g, G, c, and s.

ASCII Read Properties

The InputBufferSize property specifies the maximum number of bytes you can read from the instrument. By default, InputBufferSize is 512.

s.InputBufferSize
ans = 
    512

The ValuesReceived property indicates the total number of values read from the instrument, including the terminator.

s.ValuesReceived
ans = 
    6

Writing and Reading Binary Data

This example explores binary read and write operations with a serial port object. The instrument used was a Tektronix® TDS 210 oscilloscope.

Functions and Properties

These functions are used when reading and writing binary data:

FunctionPurpose
freadRead binary data from the instrument.
fwriteWrite binary data to the instrument.

These properties are associated with reading and writing binary data:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the instrument.
ValuesSentSpecifies the total number of values sent to the instrument.
InputBufferSizeSpecifies the total number of bytes that can be queued in the input buffer at one time.
OutputBufferSizeSpecifies the total number of bytes that can be queued in the output buffer at one time.

Configuring and Connecting to the Serial Object

You need to create a serial object. In this example, create a serial port object associated with the COM1 port.

s = serial('COM1');

Before you can perform a read or write operation, you must connect the serial port object to the instrument with the fopen function.

fopen(s)

If the object was successfully connected, its Status property is automatically configured to open.

s.Status
ans = 
    open

Writing Binary Data

You use the fwrite function to write binary data to the instrument. By default, the fwrite function operates in a synchronous mode. This means that fwrite blocks the MATLAB command line until one of the following occurs:

  • All the data is written

  • A timeout occurs as specified by the Timeout property

By default the fwrite function writes binary data using the uchar precision. However, other precisions can also be used. For a list of supported precisions, see the function reference page for fwrite.

    Note:   When performing a write operation, you should think of the transmitted data in terms of values rather than bytes. A value consists of one or more bytes. For example, one uint32 value consists of four bytes.

Binary Write Properties

The OutputBufferSize property specifies the maximum number of bytes that can be written to the instrument at once. By default, OutputBufferSize is 512.

s.OutputBufferSize
ans = 
    512

If the command specified in fwrite contains more than 512 bytes, an error is returned and no data is written to the instrument.

Configure the object's output buffer size to 3000. Note, the OutputBufferSize can be configured only when the object is not connected to the instrument.

fclose(s);
s.OutputBufferSize = 3000;
fopen(s);

The ValuesSent property indicates the total number of values written to the instrument since the object was connected to the instrument.

s.ValuesSent
ans = 
    581

Writing Int16 Binary Data

Write a waveform as an int16 array.

fwrite(s, 'Data:Destination RefB');
fwrite(s, 'Data:Encdg SRPbinary');
fwrite(s, 'Data:Width 2');
fwrite(s, 'Data:Start 1');

t = (0:499) .* 8 * pi / 500;
data = round(sin(t) * 90 + 127);
fwrite(s, 'CURVE #3500');

Note that one int16 value consists of two bytes. Therefore, the following command will write 1000 bytes.

fwrite(s, data, 'int16')

Reading Binary Data

You use the fread function to read binary data from the instrument.

The fread function blocks the MATLAB command line until one of the following occurs:

  • A timeout occurs as specified by the Timeout property

  • The specified number of values is read

  • The input buffer is filled

By default the fread function reads binary data using the uchar precision. However, other precisions can also be used. For a list of supported precisions, see the function reference page for fread.

    Note:   When performing a read operation, you should think of the received data in terms of values rather than bytes. A value consists of one or more bytes. For example, one uint32 value consists of four bytes.

Binary Read Properties

The InputBufferSize property specifies the maximum number of bytes that can be read from the instrument at once. By default, InputBufferSize is 512.

s.InputBufferSize
ans = 
    512

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

s.ValuesReceived
ans = 
    256

Reading int16 Binary Data

Read the same waveform on channel 1 as an int16 array.

fread(s, 'Data:Source CH1');
fread(s, 'Data:Encdg SRPbinary');
fread(s, 'Data:Width 2');
fread(s, 'Data:Start 1');
fread(s, 'Data:Stop 2500');
fread(s, 'Curve?')

Note that one int16 value consists of two bytes. Therefore, the following command will read 512 bytes.

data = fread(s, 256, 'int16'):

Cleanup

If you are finished with the serial port object, disconnect it from the instrument, remove it from memory, and remove it from the workspace.

fclose(s)
delete(s)
clear s
Was this topic helpful?