MATLAB: How to send strings to an external software via TCP/IP in Simulink

asciicontrolechotcpipinstrumentInstrument Control Toolboxsimulinktcp/ip

How can I send strings (ASCII arrays) to an external software via TCP/IP with the Instrument Control Toolbox in Simulink?

Best Answer

The TCP/IP Send block from Instrument Control Toolbox does not support strings inputs directly. However you can send string information using one of the following methods:
1) You can use the "String to ASCII" block from the "Strings" library to convert strings to numeric ASCII arrays and then send the ASCII array to the TCP/IP Send block. You can also use the "Compose String" block to insure your formatting is consistent with your requirements (for instance "%3.5f\n"). See the example model "String2ASCII_TCP.slx" which converts a double to a string using the "Compose String" block then converts the string to an ASCII array with the "String to ASCII" block before sending via TCP through an echo server. Note that before running this example you must execute the following command:
>> echotcpip('on', 50000);
2) The other alternative is to use the MATLAB function block, and use MATLAB code for communication in this block extrinsically. When one uses MATLAB code in a MATLAB function block, Simulink actually compiles the whole model, so the code needs to be supported for code generation. Alternatively, if standalone code generation is not needed, functions can be declared extrinsically. This allows all MATLAB functions to be called inside a MATLAB function block (but they cannot be utilized for standalone code generation). Please see the attached model "tcpip_matlabfcnblock.slx" for an example. In order to test this model on a computer, one would need to start a local tcpip server using the following command:
>> echotcpip('on',4012);
After using ether example, please close the TCP echo server with the following command:
>> echotcpip('off')