This example shows the basic workflow of 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.
Create an instrument object
— Create a UDP object associated with
u = udp('daqlab11',7);
Write and read data — You
fprintf function to write text data to the instrument. For
example, write the following string to the echo server.
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
fscanf(u) ans = Request Time
DatagramTerminateMode property indicates whether a read
operation terminates when a datagram is received. By default,
on and a read operation
terminates when a datagram is received. To return multiple datagrams in one read
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')
fscanf reads across datagram boundaries until the terminator
character is received.
u.DatagramTerminateMode = 'off' data = fscanf(u) data = Request TimeRequest Time
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
UDP ports can be shared by other applications to allow for multiple applications to
listen to the UDP datagrams on that port. This allows for the ability to listen to UDP
broadcasts on the same local port number in both MATLAB and other applications. You can enable and disable this capability with a new
property of the UDP object called
EnablePortSharing. See Enable Port Sharing over UDP.