%% Verify Generated Code by Using Cosimulation
% Verify your generated code by using cosimulation. The generated code and testbench run on a Codesys software-based programable logic controller (soft PLC). The Simulink ™ model uses Open Platform Communication Unified Architecture (OPC UA) to communicate with and retrieve the cosimulated data from the soft PLC. The Simulink model verifies the generated code by comparing the model simulation results to the cosimulated soft PLC results.
%%
%
%% Prerequisites
% On your system, you must have installed:
% Codesys V3.5.SP16 + IDE or Codesys V3.5 SP16 Patch 1 + IDE
% OPC Toolbox ™
% Simulink PLC Coder ™
%
%% Model Description
% The simple_cosim model is made up of the SimpleSubsystem block and the MATLAB System (PLCCOSIM) block. During simulation, the model compares values from the SimpleSubsystem block to the values from the soft plc which are retrieved by using the MATLAB System (PLCCOSIM) block.
%
%
%  The SimpleSubsystem block contains a simple feedback loop.
%
%
% The MATLAB System block is set up to run the PLCCOSIM.m file. The file contains the code to set up OPC UA communications and retrieve the cosimulated data from the soft PLC.

type PLCCOSIM.m

%
%
%% Compile, and Simulate the Codesys Project
% The Codesys project file runs the generated code on the soft PLC. If you have the Codesys V3.5.SP16 + IDE, use the plc-cosim_v3sp16.project as the project file. If you have the Codesys V3.5.SP16 Patch 1+ IDE, use the plc-cosim_v3sp16patch1.project as the project file.
% In the Windows ® system tray, select CODESYS Control Win SysTray -x64, right-click, and select Start PLC.
% Open the project file based on the Codesys Target IDE version.
% Double-click CODESYS_Control_Win_V3_x64 and select Scan Network.
% In the Scan Network tab, select your device in the Select Device window. Click OK.
% Select Build > Build.
%
%
%         6.Select Online > Login.
%
%
%         7. Select Debug > Start.
%
%
%
% The soft PLC is now running the generated code.
%
%% Simulate the Model and Verify Generated Code
%  Simulate the Simulink ™ model and verify the generated code by comparing the simulation model results to the soft PLC results.The soft PLC results are retrieved by using the OPC UA connection.
% Open the simple_cosim.slx file for the Simulink model.

% open_system('simple_cosim')

%            2. Simulate the model. Verify the generated code by comparing the model simulation results to the soft PLC cosimulation results.
%
%
%% See Also
% Test Bench Verification
% External Mode Logging
%
%
% Copyright 2020 The MathWorks, Inc.