Documentation Center

  • Trial Software
  • Product Updates

Writing and Reading Data

Rules for Completing Write and Read Operations

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

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.

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 TCP/IP and UDP 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. For UDP objects, DatagramTerminateMode must be off.

  • The time specified by the Timeout property passes.

  • The input buffer is filled.

  • The specified number of values is read (fscanf and readasync only). For UDP objects, DatagramTerminateMode must be off.

  • A datagram is received (for UDP objects, only when DatagramTerminateMode is on).

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

  • The time specified by the Timeout property passes.

  • The input buffer is filled.

  • The specified number of values is read. For UDP objects, DatagramTerminateMode must be off.

  • A datagram is received (for UDP objects, only when DatagramTerminateMode is on).

    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.

Reading and Writing ASCII Data over TCP/IP

This section explores ASCII read and write operations with a TCP/IP object.

    Note:   Most bench-top instruments (oscilloscopes, function generators, etc.) that provide network connectivity do not use raw TCP socket communication for instrument command and control. Instead, it is supported through the VISA standard. For more information on using VISA to communicate with your instrument, see VISA Overview.

Functions and Properties

These functions are used when reading and writing text:

FunctionPurpose
fprintfWrite text to the server.
fscanfRead data from the server and format as text.

These properties are associated with reading and writing text:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the server.
ValuesSentSpecifies the total number of values sent to the server.
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 server.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the TCP/IP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echotcpip('on', 4000)

You need to create a TCP/IP object. In this example, create a TCP/IP object associated with the host 127.0.0.1 (your local machine), port 4000. In general, the host name or address and the host port will be defined by the device and your network configuration.

t = tcpip('127.0.0.1', 4000);

Before you can perform a read or write operation, you must connect the TCP/IP object to the server with the fopen function.

fopen(t)

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

get(t, 'Status')
ans = 
    open

Writing ASCII Data

You use the fprintf function to write ASCII data to the server.

fprintf(t, 'Hello World 123');

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 server are replaced with the Terminator property value. When using the default format, %s\n, all commands written to the server will end with the Terminator character.

For the previous command, the linefeed (LF) is sent after 'Hello World 123' is written to the server, 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.

For example, the data command previously shown can be written to the server using three calls to fprintf.

fprintf(t, '%s', 'Hello');
fprintf(t, '%s', ' World');
fprintf(t, '%s\n', ' 123');

The Terminator character indicates the end of the command and is sent after the last call to fprintf.

ASCII Write Properties

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

get(t, 'OutputBufferSize')
ans = 
    512

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

get(t, 'ValuesSent')
ans = 
    32

Reading ASCII Data

You use the fscanf function to read ASCII data from the server. For example, to read back the data returned from the echo server for our first fprintf command:

data = fscanf(t)
data = 
    Hello World 123

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.

The following commands return a numeric value as a double.

Clear anything still in the input buffer from the previous commands.

flushinput(t);

Send the data to the server.

fprintf(t, '0.8000');

Read the response.

data = fscanf(t, '%f')
data = 
    0.8000
isnumeric(data)
ans = 
    1

ASCII Read Properties

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

get(t, 'InputBufferSize')
ans = 
    512

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

get(t, 'ValuesReceived')
ans = 
    32

Cleanup

If you are finished with the TCP/IP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(t);
delete(t);
clear t
echotcpip('off');

Reading and Writing Binary Data over TCP/IP

This section explores binary read and write operations with a TCP/IP object.

    Note:   Most bench-top instruments (oscilloscopes, function generators, etc.) that provide network connectivity do not use raw TCP socket communication for instrument command and control. Instead, it is supported through the VISA standard. For more information on using VISA to communicate with your instrument, see VISA Overview.

Functions and Properties

These functions are used when reading and writing binary data:

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

These properties are associated with reading and writing binary data:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the server.
ValuesSentSpecifies the total number of values sent to the server.
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.
ByteOrder Specifies the byte order of the server.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the TCP/IP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echotcpip('on', 4000)

You need to create a TCP/IP object. In this example, create a TCP/IP object associated with the host 127.0.0.1 (your local machine), port 4000. In general, the host name or address and the host port will be defined by the device and your network configuration.

t = tcpip('127.0.0.1', 4000);

You may need to configure the OutputBufferSize of the TCP/IP object. The OutputBufferSize property specifies the maximum number of bytes that can be written to the server at once. By default, OutputBufferSize is 512.

get(t, '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 server. In this example 4000 bytes will be written to the server. Therefore, the OutputBufferSize is increased to 4000.

set(t, 'OutputBufferSize', 4000)
get(t, 'OutputBufferSize')
ans = 
    4000

You may need to configure the ByteOrder of the TCP/IP object. The ByteOrder property specifies the byte order of the server. By default ByteOrder is bigEndian.

get(t, 'ByteOrder')
ans = 
    bigEndian

If the server's byte order is little-endian, the ByteOrder property of the object can be configured to littleEndian:

set(t, 'ByteOrder', 'littleEndian')
get(t, 'ByteOrder')
ans = 
    littleEndian

Before you can perform a read or write operation, you must connect the TCP/IP object to the server with the fopen function.

fopen(t)

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

get(t, 'Status')
ans = 
    open

Writing Binary Data

You use the fwrite function to write binary data to the server. For example, the following command will send a sine wave to the server.

Construct the sine wave to be written to the server.

x = (0:999) .* 8 * pi / 1000;
data = sin(x);

Write the sine wave to the server.

fwrite(t, data, 'float32');

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 ValuesSent property indicates the total number of values written to the server since the object was connected to the server.

get(t, 'ValuesSent')
ans = 
    1000

Configuring InputBufferSize

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

get(t, 'InputBufferSize')
ans = 
    512

Next, the waveform stored in the function generator's memory will be read. The waveform contains 4000 bytes. Configure the InputBufferSize to hold 4000 bytes. Note, the InputBufferSize can be configured only when the object is not connected to the server.

fclose(t);
set(t, 'InputBufferSize', 4000);
get(t, 'InputBufferSize')
ans = 
    4000

Now that the property is configured correctly, you can reopen the connection to the server:

fopen(t);

Reading Binary Data

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

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 InputBufferSize number of values is read

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.

For reading float32 binary data, send the waveform again. Closing the object clears any available data from earlier writes.

fwrite(t, data, 'float32');

Now read the same waveform as a float32 array.

data = fread(t, 1000, 'float32');

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

get(t, 'ValuesReceived')
ans = 
    1000

Cleanup

If you are finished with the TCP/IP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(t);
delete(t);
clear t
echotcpip('off');

Asynchronous Read and Write Operations over TCP/IP

This section explores Asynchronous read and write operations with a TCP/IP object.

    Note:   Most bench-top instruments (oscilloscopes, function generators, etc.) that provide network connectivity do not use raw TCP socket communication for instrument command and control. Instead, it is supported through the VISA standard. For more information on using VISA to communicate with your instrument, see VISA Overview.

Functions and Properties

These functions are associated with reading and writing text asynchronously:

FunctionPurpose
fprintfWrite text to a server.
readasyncAsynchronously read bytes from a server.
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.

Synchronous Versus Asynchronous Operations

The object can operate in synchronous mode or in asynchronous mode. When the object is operating synchronously, the read and write routines block the MATLAB command line until the operation has completed or a timeout occurs. When the object is operating asynchronously, the read and write routines return control immediately to the MATLAB command line.

Additionally, you can use callback properties and callback functions to perform tasks as data is being written or read. For example, you can create a callback function that notifies you when the read or write operation has finished.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the TCP/IP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echotcpip('on', 4000)

You need to create a TCP/IP object. In this example, create a TCP/IP object associated with the host 127.0.0.1 (your local machine), port 4000. In general, the host name or address and the host port will be defined by the device and your network configuration.

t = tcpip('127.0.0.1', 4000);

Before you can perform a read or write operation, you must connect the TCP/IP object to the server with the fopen function.

fopen(t)

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

get(t, 'Status')
ans = 
    open

Reading Data Asynchronously

You can read data asynchronously with the TCP/IP object in one of these two ways:

  • Continuously, by setting ReadAsyncMode to continuous. In this mode, data is automatically stored in the input buffer as it becomes available from the server.

  • Manually, by setting ReadAsyncMode to manual. In this mode, you must call the readasync function to store data in the input buffer.

The fscanf, fread, fgetl and fgets functions are used to bring the data from the input buffer into MATLAB. These functions operate synchronously.

Reading Data Asynchronously – Continuous ReadAsyncMode

To begin, read data continuously.

set(t, 'ReadAsyncMode', 'continuous');

Now, send data to the server that will be returned for reading.

fprintf(t, 'Hello World 123');

Because the ReadAsyncMode property is set to continuous, the object is continuously checking whether any data is available. Once the last fprintf function completes, the server begins sending data, the data is read from the server and is stored in the input buffer.

get(t, 'BytesAvailable')
ans = 
    16

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

fscanf(t)
ans = 
    Hello World 123

Reading Data Asynchronously – Manual ReadAsyncMode

Next, read data manually.

set(t, 'ReadAsyncMode', 'manual');

Now, send data to the server that will be returned for reading.

fprintf(t, 'Hello World 456');

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

get(t, 'BytesAvailable')
ans = 
    0

The readasync function can asynchronously read the data from the server. The readasync function returns control to the MATLAB command line immediately.

The readasync function takes two input arguments. The first argument is the server object and the second argument is the size, the amount of data to be read from the server.

The readasync function without a size specified assumes size is given by the difference between the InputBufferSize property value and the BytesAvailable property value. The asynchronous read terminates when:

  • The terminator is read as specified by the Terminator property

  • The specified number of bytes have been read

  • A timeout occurs as specified by the Timeout property

  • The input buffer is filled

An error event will be generated if readasync terminates due to a timeout.

The object starts querying the server for data when the readasync function is called. Because all the data was sent before the readasync function call, no data will be stored in the input buffer and the data is lost.

When the TCP/IP object is in manual mode (the ReadAsyncMode property is configured to manual), data that is sent from the server to the computer is not automatically stored in the input buffer of the TCP/IP 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 server and you only want to capture portions of the data.

Defining an Asynchronous Read Callback

You can configure a TCP/IP object to notify you when a terminator has been read using the dispcallback function.

set(t, 'ReadAsyncMode', 'continuous');
set(t, '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.

The callback function dispcallback displays event information for the specified event. Using the syntax dispcallback(obj, event), it displays a message containing the type of 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']);

Using Callbacks During an Asynchronous Read

Once the terminator is read from the server 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(t, 'Hello World 789')
get(t, 'BytesAvailable')
ans = 
    16

data = fscanf(t, '%c', 18)
data = 
    Hello World 789

    Note:   If you need to stop an asynchronous read or write operation, you do not have to wait for the operation to complete. You can use the stopasync function to stop the asynchronous read or write.

Writing Data Asynchronously

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

In asynchronous mode, you can use callback properties and callback functions to perform tasks while data is being written. For example, configure the object to notify you when an asynchronous write operation completes.

set(t, 'OutputEmptyFcn', {'dispcallback'});
fprintf(t, 'Hello World 123', 'async')

    Note:   If you need to stop an asynchronous read or write operation, you do not have to wait for the operation to complete. You can use the stopasync function to stop the asynchronous read or write.

Cleanup

If you are finished with the TCP/IP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(t);
delete(t);
clear t
echotcpip('off');

Writing and Reading Data with a TCP/IP Object

This example illustrates how to use text and binary read and write operations with a TCP/IP object connected to a remote instrument. In this example, you create a vector of waveform data in the MATLAB workspace, upload the data to the instrument, and then read back the waveform.

The instrument is a Sony/Tektronix® AWG520 Arbitrary Waveform Generator (AWG). Its address is sonytekawg.yourdomain.com and its port is 4000. The AWG's host IP address is 192.168.1.10 and is user configurable in the instrument. The associated host name is given by your network administrator. The port number is fixed and is found in the instrument's documentation:

  1. Create an instrument object — Create a TCP/IP object associated with the AWG.

    t = tcpip('sonytekawg.yourdomain.com',4000);
  2. Connect to the instrument — Before establishing a connection, the OutputBufferSize must be large enough to hold the data being written. In this example, 2577 bytes are written to the instrument. Therefore, the OutputBufferSize is set to 3000.

    set(t,'OutputBufferSize',3000)

    You can now connect t to the instrument.

    fopen(t)
  3. Write and read data — Since the instrument's byte order is little-endian, configure the ByteOrder property to littleEndian.

    set(t,'ByteOrder','littleEndian')

    Create the sine wave data.

    x = (0:499).*8*pi/500;
    data = sin(x);
    marker = zeros(length(data),1);
    marker(1) = 3;

    Instruct the instrument to write the file sin.wfm with Waveform File format, a total length of 2544 bytes, and a combined data and marker length of 2500 bytes.

    fprintf(t,'%s',['MMEMORY:DATA "sin.wfm",#42544MAGIC 1000' 13 10])
    fprintf(t,'%s','#42500')

    Write the sine wave to the instrument.

    for (i = 1:length(data)),
    	fwrite(t,data(i),'float32');
    	fwrite(t,marker(i));
    end

    Instruct the instrument to use a clock frequency of 100 MS/s for the waveform.

    fprintf(t,'%s',['CLOCK 1.0000000000e+008' 13 10 10])

    Read the waveform stored in the function generator's hard drive. The waveform contains 2000 bytes plus markers, header, and clock information. To store this data, close the connection and configure the input buffer to hold 3000 bytes.

    fclose(t)
    set(t,'InputBufferSize',3000)

    Reopen the connection to the instrument.

    fopen(t)

    Read the file sin.wfm from the function generator.

    fprintf(t,'MMEMORY:DATA? "sin.wfm" ')
    data = fread(t,t.BytesAvailable);

    The next set of commands reads the same waveform as a float32 array. To begin, write the waveform to the AWG.

    fprintf(t,'MMEMORY:DATA? "sin.wfm" ')

    Read the file header as ASCII characters.

    header1 = fscanf(t)
    header1 =
    #42544MAGIC 1000

    Read the next six bytes, which specify the length of data.

    header2 = fscanf(t,'%s',6)
    header2 =
    #42500

    Read the waveform using float32 precision and read the markers using uint8 precision. Note that one float32 value consists of four bytes. Therefore, the following commands read 2500 bytes.

    data = zeros(500,1);
    marker = zeros(500,1);
    for i = 1:500,
    	data(i) = fread(t,1,'float32');
    	marker(i) = fread(t,1,'uint8');
    end

    Read the remaining data, which consists of clock information and termination characters.

    clock = fscanf(t);
    cleanup = fread(t,2);
  4. Disconnect and clean up — When you no longer need t, you should disconnect it from the host, and remove it from memory and from the MATLAB workspace.

    fclose(t)
    delete(t)
    clear t

Reading and Writing ASCII Data over UDP

This section explores ASCII read and write operations with a UDP object.

Functions and Properties

These functions are used when reading and writing text:

FunctionPurpose
fprintfWrite text to the server.
fscanfRead data from the server and format as text.

These properties are associated with reading and writing text:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the server.
ValuesSentSpecifies the total number of values sent to the server.
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 server.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the UDP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echoudp('on', 8000)

You need to create a UDP object. In this example, create a UDP object associated with the host 127.0.0.1 (your local machine), port 8000. In general, the host name or address and the host port will be defined by the device and your network configuration.

u = udp('127.0.0.1', 8000);

Before you can perform a read or write operation, you must connect the UDP object to the server with the fopen function.

fopen(u)

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

get(u, 'Status')
ans = 
    open

Writing ASCII Data

You use the fprintf function to write ASCII data to the server. For example, write a string to the echoserver.

fprintf(u, 'Request Time');

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 server are replaced with the Terminator property value. When using the default format, %s\n, all commands written to the server will end with the Terminator character.

For the previous command, the linefeed (LF) is sent after 'Request Time' is written to the server, 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.

For example, the data command previously shown can be written to the server using two calls to fprintf.

fprintf(u, '%s', 'Request');
fprintf(u, '%s'\n, 'Time');

The Terminator character indicates the end of the command and is sent after the last call to fprintf.

ASCII Write Properties

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

get(u, 'OutputBufferSize')
ans = 
    512

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

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

get(u, 'ValuesSent')
ans = 
    26

Remove any data that was returned from the echoserver and captured by the UDP object.

flushinput(u);

Reading ASCII Data

UDP sends and receives data in blocks that are called datagrams. Each time you write or read data with a UDP object, you are writing or reading a datagram. For example, a datagram with 13 bytes (12 ASCII bytes plus the LF terminator) is sent to the echoserver.

fprintf(u, 'Request Time');

The echo server will send back a datagram containing the same 13 bytes.

get(u, 'BytesAvailable')
ans = 
    13

You use the fscanf function to read ASCII data from the server.

data = fscanf(u)
data = 
    Request Time

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 (if DatagramTerminateMode is off)

  • A timeout occurs as specified by the Timeout property

  • The input buffer is filled

  • The specified number of values is read (if DatagramTerminateMode is off)

  • A datagram has been received (if DatagramTerminateMode is on)

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.

For example, the string'0.80' sent to the echoserver can be read into MATLAB as a double using the %f format string.

fprintf(u, '0.80');
data = fscanf(u, '%f')
data = 
    0.8000

isnumeric(data)
ans = 
    1

ASCII Read Properties

The DatagramTerminateMode property indicates whether a read operation should terminate when a datagram is received. By default DatagramTerminateMode is on, which means that a read operation terminates when a datagram is received. To read multiple datagrams at once, you can set DatagramTerminateMode to off. In this example, two datagrams are written. Note, only the second datagram sends the Terminator character.

fprintf(u, '%s', 'Request Time');
fprintf(u, '%s\n', 'Request Time'); 

Since DatagramTerminateMode is off, fscanf will read across datagram boundaries until the Terminator character is received.

set(u, 'DatagramTerminateMode', 'off');
data = fscanf(u)
data = 
    Request TimeRequest Time

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

get(u, 'InputBufferSize')
ans = 
    512

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

get(u, 'ValuesReceived')
ans = 
    43

Cleanup

If you are finished with the UDP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(u);
delete(u);
clear u
echoudp('off');

Reading and Writing Binary Data over UDP

This section explores binary read and write operations with a UDP object.

Functions and Properties

These functions are used when reading and writing binary data:

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

These properties are associated with reading and writing binary data:

PropertyPurpose
ValuesReceivedSpecifies the total number of values read from the instrument or server.
ValuesSentSpecifies the total number of values sent to the instrument or server.
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.
DatagramTerminateMode Defines how fread and fscanf read operations terminate.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the UDP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echoudp('on', 8000)

You need to create a UDP object. In this example, create a UDP object associated with the host 127.0.0.1 (your local machine), port 8000. In general, the host name or address and the host port will be defined by the device and your network configuration.

u = udp('127.0.0.1', 8000);

You may need to configure the OutputBufferSize of the UDP object. The OutputBufferSize property specifies the maximum number of bytes that can be written to the server at once. By default, OutputBufferSize is 512.

get(u, '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 server. In this example 1000 bytes will be written to the instrument. Therefore, the OutputBufferSize is increased to 1000.

set(u, 'OutputBufferSize', 1000)
get(u, 'OutputBufferSize')
ans = 
    1000

Before you can perform a read or write operation, you must connect the UDP object to the server with the fopen function.

fopen(u)

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

get(u, 'Status')
ans = 
    open

Writing Binary Data

You use the fwrite function to write binary data to the server or 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.

UDP sends and receives data in blocks that are called datagrams. Each time you write or read data with a UDP object, you are writing or reading a datagram. In the example below, a datagram with 1000 bytes, 4 bytes per integer number, will be sent to the echoserver.

fwrite(u, 1:250, 'int32');

    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.

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

get(u, 'ValuesSent')
ans = 
    250

Configuring InputBufferSize

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

get(u, 'InputBufferSize')
ans = 
    512

In the next example, 1000 bytes will be read from the server. Configure the InputBufferSize to hold 1000 bytes. Note, the InputBufferSize can be configured only when the object is not connected to the server or instrument.

fclose(u);
set(u, 'InputBufferSize', 1000);
get(u, 'InputBufferSize')
ans = 
    1000

Now that the property is configured correctly, you can reopen the connection to the server:

fopen(u);

Reading Binary Data

You use the fread function to read binary data from the server or 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 input buffer is filled

  • The specified number of values is read (if DatagramTerminateMode is off)

  • A datagram has been received (if DatagramTerminateMode is on)

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.

You can read int32 binary data. For example, read one datagram consisting of 250 integers from the instrument or server.

fwrite(u, 1:250, 'int32');
data = fread(u, 250, 'int32');

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

get(u, 'ValuesReceived')
ans = 
    500

The DatagramTerminateMode property indicates whether a read operation should terminate when a datagram is received. By default DatagramTerminateMode is on, which means that a read operation terminates when a datagram is received. To read multiple datagrams at once, you can set DatagramTerminateMode to off. In this example, two datagrams are written to the echoserver.

fwrite(u, 1:125, 'int32');
fwrite(u, 1:125, 'int32');

Because DatagramTerminateMode is off, fread will read across datagram boundaries until 250 integers have been received.

set(u, 'DatagramTerminateMode', 'off');
data = fread(u, 250, 'int32');
size(data)
ans = 
    250

Cleanup

If you are finished with the UDP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(u);
delete(u);
clear u
echoudp('off');

Asynchronous Read and Write Operations over UDP

This section explores asynchronous read and write operations with a UDP object.

Functions and Properties

These functions are associated with reading and writing text asynchronously:

FunctionPurpose
fprintfWrite text to a server.
readasyncAsynchronously read bytes from a server.
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.

Synchronous Versus Asynchronous Operations

The object can operate in synchronous mode or in asynchronous mode. When the object is operating synchronously, the read and write routines block the MATLAB command line until the operation has completed or a timeout occurs. When the object is operating asynchronously, the read and write routines return control immediately to the MATLAB command line.

Additionally, you can use callback properties and callback functions to perform tasks as data is being written or read. For example, you can create a callback function that notifies you when the read or write operation has finished.

Configuring and Connecting to the Server

For this example, we will use an echo server that is provided with the toolbox. The echo server allows you to experiment with the basic functionality of the UDP objects without connecting to an actual device. An echo server is a service that returns to the sender's address and port, the same bytes it receives from the sender.

echoudp('on', 8000);

You need to create a UDP object. In this example, create a UDP object associated with the host 127.0.0.1 (your local machine), port 8000. In general, the host name or address and the host port will be defined by the device and your network configuration.

u = udp('127.0.0.1', 8000);

Before you can perform a read or write operation, you must connect the UDP object to the server with the fopen function.

fopen(u)

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

get(u, 'Status')
ans = 
    open

Reading Data Asynchronously

You can read data asynchronously with the UDP object in one of these two ways:

  • Continuously, by setting ReadAsyncMode to continuous. In this mode, data is automatically stored in the input buffer as it becomes available from the server.

  • Manually, by setting ReadAsyncMode to manual. In this mode, you must call the readasync function to store data in the input buffer.

The fscanf, fread, fgetl and fgets functions are used to bring the data from the input buffer into MATLAB. These functions operate synchronously.

Reading Data Asynchronously Using Continuous ReadAsyncMode

To read data continuously:

set(u, 'ReadAsyncMode', 'continuous');

To send a string to the echoserver:

fprintf(u, 'Hello net.');

Because the ReadAsyncMode property is set to continuous, the object is continuously asking the server if any data is available. The echoserver sends data as soon as it receives data. The data is then read from the server and is stored in the object's input buffer.

get(u, 'BytesAvailable')
ans = 
    11

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

mystring = fscanf(u)
mystring = 
    Hello net.

Reading Data Asynchronously Using Manual ReadAsyncMode

You can also read data manually.

set(u, 'ReadAsyncMode', 'manual');

Now, send a string to the echoserver.

fprintf(u, 'Hello net.');

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

get(u, 'BytesAvailable')
ans = 
    0

The readasync function can asynchronously read the data from the server. The readasync function returns control to the MATLAB command line immediately.

The readasync function takes two input arguments. The first argument is the server object and the second argument is the size, the amount of data to be read from the server.

The readasync function without a size specified assumes size is given by the difference between the InputBufferSize property value and the BytesAvailable property value. The asynchronous read terminates when:

  • The terminator is read as specified by the Terminator property

  • The specified number of bytes have been read

  • A timeout occurs as specified by the Timeout property

  • The input buffer is filled

An error event will be generated if readasync terminates due to a timeout.

The object starts querying the server for data when the readasync function is called. Because all the data was sent before the readasync function call, no data will be stored in the input buffer and the data is lost.

When the UDP object is in manual mode (the ReadAsyncMode property is configured to manual), data that is sent from the server to the computer is not automatically stored in the input buffer of the UDP 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 server and you only want to capture portions of the data.

Defining an Asynchronous Read Callback

You can configure a UDP object to notify you when a terminator has been read using the dispcallback function.

set(u, 'ReadAsyncMode', 'continuous');
set(u, '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.

get(u, 'BytesAvailableFcnMode')
ans = 
    terminator

The callback function dispcallback displays event information for the specified event. Using the syntax dispcallback(obj, event), it displays a message containing the type of 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']);

Using Callbacks During an Asynchronous Read

Once the terminator is read from the server 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(u, 'Hello net.')
get(u, 'BytesAvailable')
ans = 
    11

data = fscanf(u)
data = 
    Hello net.

If you need to stop an asynchronous read or write operation, you do not have to wait for the operation to complete. You can use the stopasync function to stop the asynchronous read or write.

stopasync(u);

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

flushinput(u);

Writing Data Asynchronously

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

Configure the object to notify you when an asynchronous write operation completes.

set(u, 'OutputEmptyFcn', {'dispcallback'});
fprintf(u, 'Hello net.', 'async')

UDP sends and receives data in blocks that are called datagrams. Each time you write or read data with a UDP object, you are writing or reading a datagram. In the example below, a datagram with 11 bytes (10 ASCII bytes plus the LF terminator) will be sent to the echoserver. Then the echoserver will send back a datagram containing the same 11 bytes.

Configure the object to notify you when a datagram has been received.

set(u, 'DatagramReceivedFcn', {'dispcallback'});
fprintf(u, 'Hello net.', 'async')

    Note:   If you need to stop an asynchronous read or write operation, you do not have to wait for the operation to complete. You can use the stopasync function to stop the asynchronous read or write.

Cleanup

If you are finished with the UDP object, disconnect it from the server, remove it from memory, and remove it from the workspace. If you are using the echo server, turn it off.

fclose(u);
delete(u);
clear u
echoudp('off');

Writing and Reading Data with a UDP Object

This example illustrates how to use text read and write operations with a UDP object connected to a remote instrument.

The instrument used is an echo server on a Linux-based PC. An echo server is a service available from the operating system that returns (echoes) received data to the sender. The host name is daqlab11 and the port number is 7. The host name is assigned by your network administrator.

  1. Create an instrument object — Create a UDP object associated with daqlab11.

    u = udp('daqlab11',7);
  2. Connect to the instrument — Connect u to the echo server.

    fopen(u)
  3. Write and read data — You use the fprintf function to write text data to the instrument. For example, write the following string to the echo server.

    fprintf(u,'Request Time')

    UDP sends and receives data in blocks that are called datagrams. Each time you write or read data with a UDP object, you are writing or reading a datagram. For example, the string sent to the echo server constitutes a datagram with 13 bytes — 12 ASCII bytes plus the line feed terminator.

    You use the fscanf function to read text data from the echo server.

    fscanf(u)
    ans =
    Request Time

    The DatagramTerminateMode property indicates whether a read operation terminates when a datagram is received. By default, DatagramTerminateMode is on and a read operation terminates when a datagram is received. To return multiple datagrams in one read operation, set DatagramTerminateMode to off.

    The following commands write two datagrams. Note that only the second datagram sends the terminator character.

    fprintf(u,'%s','Request Time')
    fprintf(u,'%s\n','Request Time')

    Since DatagramTerminateMode is off, fscanf reads across datagram boundaries until the terminator character is received.

    set(u,'DatagramTerminateMode','off')
    data = fscanf(u)
    data =
    Request TimeRequest Time
  4. Disconnect and clean up — When you no longer need u, you should disconnect it from the host, and remove it from memory and from the MATLAB workspace.

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