Hopsan
Exporting to Simulink

Hopsan models can be exported to Simulink as S-function libraries. This is done by using an automatically generated C++ file, that can be compiled into an S-function from Matlab and linked against the HopsanCore library.

Prerequisites

  • Matlab/Simulink 2010a or later
  • Visual C++ 2008 or Visual C++ 2010 compiler (express version works)

Step-by-step guide

1. Prepare the model

First of all we must have a model to export. In this example, we want to export the "position servo" model (found in Example Models directory) and create a closed-loop controller in Simulink. The only required modifications is that we must add interface components (found in Connectivity library) wherever we want interaction between Simulink and Hopsan. In this case we want a signal input to control the valve, and a signal output from the sensor. The controller is thus removed from the Hopsan model.

2. Export source files

Next step is to export the files. Click the "Export" button and select Simulink Source Files.

Export to S-function

A dialog appears, where you can choose version of Visual C++ and if you want 32-bit or 64-bit architecture. These settings should be chosen so that they match your version of Matlab. It is also possible to disable port graphics, for portability with older versions of Simulink. Use this setting only if Matlab gives an error message ending with "called mdlSetNumInputPorts more than once".

When this dialog is closed, a file dialog appears. Choose an empty directory. Source files, model files and binaries will be generated and copied to this directory.

3. Compile in Matlab

Open Matlab. First, make sure that the correct compiler is used. Write the following command in the console:

mex -setup

Now select the appropriate version of Visual C++. Then change Matlab working directory to the one created in the previous step. Run the compilation script file "HopsanSimulinkCompile.m". This will create the S-function library.

4. Open model in Simulink

Open Simulink and create a new model. Add an S-function block. Open the properties and choose HopsanSimulink (without file extension) as the library file. Now a Simulink block appears. The ports corresponds to the interface components in Hopsan. The DEBUG output port will give zero if everything is ok, or an error number greater than zero if something goes wrong.

Now let's add a PI-controller similar to the one we had originally in Hopsan. Also add scopes at the reference and output signals. Choose some reasonable values and check the results in the scopes.