Friday, December 27, 2019

Generating code with reusable function

Recently, I needed to re-use Aerospace blockset's ISA atmosphere as a function in C code. When you just generate code, the atmosphere functionality will be embedded inside the simulation step() function. To generate a function that does not depend on simulation, you do the following (Matlab R2019a):

First, put the ISA atmosphere block inside a subsystem (so that it can be made atomic). Then right click on the subsytem:

Generated C code contains the names I set in Simulink model (with "rtu_" added for inputs and "rty_" added for outputs) and the code interface is simple. Contents of SamilsISAAtmosphere.h:

extern void SamilsISAAtmosphere(real_T rtu_hMSL_m, real_T *rty_Temperature_K, real_T *rty_speedOfSound_mps, real_T *rty_pressure_Pa, real_T *rty_airDensity_kgpm3);

Thursday, November 7, 2019

Input / output code generated from Simulink model

When you want to generate code from a Simulink model and drive that code from another C++ file, Simulink has a mechanism that can help you setting model inputs and getting model outputs.

For outputs, in Simulink you right click on the signal, give it a name and select storage class. For inputs that are normally read from Matlab workspace and have to be set from external C++ function, you configure them as inlined parameters:



When you define constants loaded from workspace in Simulink as Model Default/Simulink Global (Auto) or for signals Auto, and if you forget to define init structure in C++, you will get "LNK2001 unresolved external symbol _aa_P", which is a good thing because the compiler won't let you forget initialization.

If you define parameters as extern Global, Simulink sets initial values to the constants in Simulink and if you forget to provide your own initial conditions, C++ will happily run with embedded inits. Additionally, auto puts parameters into a structure while extern global makes them separate global variables which increases probability of naming conflicts.

Wednesday, July 31, 2019

Skills / Competencies

A software engineer tasked with generating code from an existing Simulink model must have these skills:
  1. A good understanding of C-Mex s-functions and calling frequencies of s-function methods like mdlUpdate().
  2. Profiling the Simulink model and improving speed by e.g. moving one time calculations to initialization instead of running it at every time step.
  3. Automation of code generation process with scripts (e.g. bat file).