MATLAB: TCP/IP server to connect to S7 1200

plcs7tcpip

I am trying to control my Simulink model through an S7 1200 PLC. The idea is to send the process value from the model to the PLC and send a corresposding control variable from PLC to the simulink model.
The TIA Portal only has TCP/IP client block, and the instrument Control Toolbox of Matlab also has TCP client send/receive blocks. So I decided to write my own function to make a TCPIP server on Matlab. The code is quite simple but the problem is that the connection gets destroyed once the fucntion block is executed. This makes my simulation run very slow (1 second is simulated in 8 seconds).
t = tcpip('0.0.0.0', 2000, 'NetworkRole', 'server');
fopen(t);
Is there a way to make the connection to the PLC once and then reuse that connection throughout the simulation?
I have spent a lot of time trying to find a solution but no success yet. The Modbus object won't even run inside the custom function. UDP also needs to connect every time so I am out of options here. Is there anyone that can help me please.

Best Answer

  • I managed to indirectly find a very simple solution from some OPC tutorial. I used an Interpreted Matlab Fcn block and inside the block I wrote a function which creates a connection and sends data to PLC over TCP/IP. In order to reuse the old connection instead of making a new one every time I defined my TCPIP object as a consistent variable (details here). This way the variable is stored in Matlab memory when the block is not executing.
    function [x] = dataWriteandReadTCPIP(b)
    persistent init_Server;
    persistent tcpClient;
    persistent testVal;
    persistent bytesAvailable;
    if (isempty(init_Server))
    testVal = 0;
    %bytesAvailable = 0;
    init_Server = 0;
    end
    if init_Server == 0
    init_Server = 1;
    tcpClient = tcpip('0.0.0.0', 2000, 'NetworkRole', 'server');
    tcpClient.InputBufferSize=4;
    fopen(tcpClient);
    end
    A = single(b);
    B = typecast(A,'uint8');
    C = fliplr(B);
    fwrite(tcpClient, C);
    newBytesAvailable = get(tcpClient,'BytesAvailable');
    if newBytesAvailable > 0
    data_Temp = fread(tcpClient, 4);
    data_Temp = flipud(data_Temp);
    data_Temp = uint8(data_Temp);
    testVal = typecast(data_Temp,'single');
    bytesAvailable = newBytesAvailable;
    end
    x=double(testVal);
    end
  • Related Question