TCP/IP UDP/IP communication with MATLAB
- 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!