TCP/IP UDP/IP communication with MATLAB

One of the things that makes MATLAB so powerful is the ability to interface it with different data sources, in fact, what’s the point having extended calculation capabilities without a proper interface to the data to be processed?
If sometimes, like me, you had the need to evaluate data flows through the ethernet port, here’s how to do it:
  • Tcp-ip communication between two instances of Matlab on the same machine:

% Create a server interface on port 1200 and open it, accept a connection
% from any machine.
socket = tcpip(‘0.0.0.0’, 1200, ‘NetworkRole’, ‘server’);

  • Tcp-ip communication between two instances of Matlab on different machines or between a PC running MATLAB and a custom hardware like microcontroller, FPGA or DSP.

% Create a server interface on port 1207 and open it, accept a connection
% from 192.168.1.200:1200
% socket = tcpip(‘192.168.1.200’, 1200, ‘LocalPort’, 1207);

set(socket, ‘InputBufferSize’, 3000000);  % Set size of rx buffer.
set(socket, ‘OutputBufferSize’, 3000000); % Set size of tx buffer.
fopen(socket); % Open a connection.
fwrite(socket, data_out); % Write data_out to socket
data_in = fread(socket, N, ‘double’); % Read N double to from socket

For UDP communication use socket=udp(); instead.

Below you can find an exaustive example with comments of both server and client script, with signal generation, trasmission, echo from client host and plots of data sent.

Enjoy and comment!

Advertisements

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: