2 Basic S-Functions and TLC Creating Custom Blocks for SimulinkSimulink has the notion of S-functions to create user defined blocksS-functions can be written in M, C, or FORTRANWe will focus on CEmbedded Coder cannot code generate an S-Function without the help of a TLC (Target Language Compiler)All MotoHawk Blocks are created using S-Functions, Masks, and TLC using interfaces defined by MathworksNo sneaky “special” functions or APIs are usedMotoHawk maintains a very thin interface to Simulink to simplify issues that can be caused during Matlab version changes
3 Help MaterialS-Functions are Described in the Simulink Help
4 Add a S-Function from the Simulink Browser S-Function PrimerAdd a S-Function from the Simulink BrowserSet the Name and add any parametersRecommend using company_sfun_xxx
5 S-Function Primer (con’t) Copy <MatlabInstall>\simulink\src\sfuntmpl_basic.c to your local project directoryRename to the same name you chose in the s-function block, in this case mototron_sfun_timesX.cEdit c file: > edit mototron_sfun_timesX.cThis must be changed to match filename
6 Editing the S-Function C File Set the number of Parameters in the function ssSetNumSFcnParams(S, 1);One ParameterOne Parameter
8 Input Port Direct FeedThrough What does Input Port Direct Feed Through mean?This tells the block sorter that this input port is used as part of the calculation of the output portsSetting it to Zero means that the ports are independent and the sorter does not need to make sure that blocks upstream are calculated first…This is NOT usually the case.Setting it to One means that this input must be calculated prior to the execution of the block. This is USUALLY the case.
9 Output Port Definition Set Output Port Attributes
11 How Do I Know What Options to Set? <MATLABDIR>\simulink\include\simstruc.h has the documentation
12 Setting the Sample Time Set to Inherited Sample Time
13 Creating the Simulation Behavior mdlOutputs contains code for simulationExample to multiply Input by Parameter Value
14 Note resultant file (may be mex32 on newer versions) Build DLLUse Matlab’s mex command to compile fileChoose LCC if askedNote resultant file (may be mex32 on newer versions)
15 Check Simulation Behavior Run in simulation to verify operation
16 Port Data TypesWe didn’t specify data types for the ports so they defaulted to double.To accommodate different datatypes requires deeper s-function knowledge
17 S-Function WrapupS-function describes the block with respect to the Simulation Engine (and the Diagram Checker)S-Function describes port data types, sizes, number of parameters, sample times, and memory allocationsS-Functions contain code that runs in the simulation but that code is not generated into a MotoHawk build, TLC will help us with thatS-Function Syntax and Help are contained in Matlab’s Help and simstruc.h
18 See Matlab Help regarding Mask Details MasksInteracting with the User is defined by a MaskSelect S-function block, right click->Mask SubsystemSee Matlab Help regarding Mask Details
19 Parameters are design time choices needed from the Application Builder Add a ParameterParameters are design time choices needed from the Application BuilderTunable means adjustable at run time (not available in MotoHawk)Evaluate as a MatLab expression
20 Document on Mask IconShow the designer’s choice on the block icon for documentation
21 Add some Help TextAdd Mask Help, Copyright Recommended
22 Masks present the custom block to the user Mask WrapupMasks present the custom block to the userMasks can pre-compute via scripts in the Initialization paneHeavy lifting of sorting, querying the model for information, rationalizing the designers choices, etc should be done here.Masks should show as much of the Parameter choices as possible on the icon.Don’t make readers look for data in dialogue boxesHelp text should not be overlooked.Too much help documentation is almost enoughGood block design should also make the functions and parameters obviousMasks don’t do any code generation but can pre-compute information used by the code generator
23 TLC Telling the Code Generator What to Do TLC (Target Language Compiler) is the language that drives the Real Time Workshop code generatorTLC can be thought of a as a Macro Expansion LanguageTLC has many computer language constructs like variables, loops, and functionsTLC directives use the % sign to indicate that this is a TLC statementAnything without a % sign is either dumped to the current source file or ignored if no file is being createdThe code generator makes essentially 4 passes over the model to collect code generation directives
24 TLC DocumentationTLC is descibed in Matlab’s Help under Real Time Workshop
25 Must match the s-function name and TLC file name TLC File ContentsTLC Files Must have an Implements directive and certain “Callback” functionsMust match the s-function name and TLC file nameRun once if at least one instance of the block is in the model.Typically we add header files here.Note “VOID” means no active output file during this passRun once for each instance of the block in the model. Note no output active. Usually we add blocks to lists here
26 TLC File ContentsTLC Files Must have an Implements directive and certain “Callback” functionsGenerate code destined for Startup functionGenerate code destined for triggered susbsystems.
27 TLC File ContentsAnything without a % directive is dumped to the output
28 Asking The Code Generator for Names LibBlockInputSignal() and LibBlockOutputSignal ask the code generator for signal names, Parameter gets parameter value%<var> expands the TLC variable var into the outputNote Constant value is expanded as the literal value.Output is actually a global variable.
29 First, we built the S-function DLL from a c file (language #1) Custom Blocks So FarFirst, we built the S-function DLL from a c file (language #1)Next, we masked the S-Function block to make it look good (language #2)Finally, we wrote a TLC file (language #3) to generated embedded C (language #4).Looking at the generated code, we see some issuesA global variable was created when obviously the expression could have been inlined costing no RAMThe S-Function C file is terribly complex (and we used the simple template)We can address these two issues by using a better template
30 A better ApproachThe MotoHawk Template s-function file contains all of the “Correct” settings for good code generationSimply fill out details at the top, add the simulation behavior and most everything else is taken care of (see motohawk_mex_template.c for the details)
31 Reuse Outputs and Use Expressions Fix S-Function Options to Re-use outputs (save memory) and Use Expressions if possibleOriginal required two global variables and a run time operationOriginal required two global variables and a run time operationBetter version uses stack variable and no run time operation.
32 Custom Blocks are Powerful Custom Block WrapupCustom Blocks are PowerfulOften times complex Simulink subsystems can be aggregated into a simple blockLower Block count = faster update and compile timesBuilding them requires mastery of 4 languagesTLC drives the code generatorTLC documentation is readily available in SimulinkLook at both MotoHawk and Simulink TLC files for lots of examplesWarning, using MotoHawk provided TLC functions may break in the future. We don’t publish that as a public API so we reserve the right to change without notice.