SIMULINKDynamic System Simulation for MATLABModelingSimulationImplementationTarget Language Compiler Reference GuideVersion 1
1 Using the Target Language Compiler with Real-Time Workshop1-2Using the Target Language CompilerIntroductionThe Target Language Compiler™ is a tool t
3 Writing Target Language Files3-26LibBlockRWork(rworkRef, ucv, lcv, sigIdx)LibBlockIWork(iworkRef, ucv, lcv, sigIdx)LibBlockPWork(pworkRef, ucv, lcv,
The RTW TLC Function Library3-27LibRenameParameter(block, param, newName)Given a reference to a block, a reference to a block parameter, and the new n
3 Writing Target Language Files3-28Call LibRenameParameter(Block, Parameter[1], "Kp"), which renames P1 to Kp and creates a Kp identifier th
The RTW TLC Function Library3-29Note: By convention, start parameter names with a capital letter since the Name identifier of the Parameter record is
3 Writing Target Language Files3-30Built-In TLC FunctionsThe most common built-in TLC functions required to write a block target file are STRINGOF, EX
Inlining an S-Function3-31Inlining an S-FunctionWhen a Simulink model contains an S-function and a corresponding .tlc file, Real-Time Workshop inlines
3 Writing Target Language Files3-32In general, inlining an S-function is especially useful when:• The time required to execute the contents of the S-f
Inlining an S-Function3-33{ y[0] = u[0] * GAIN;}static voidmdlInitializeSampleTimes(SimStruct *S){}static voidmdlInitializeConditions(real_T *x0,SimS
3 Writing Target Language Files3-34voidMdlOutputs(tid){ /* S-Function block: foo */ { Simstruct *s = ssGetSFunction(S, 0); real_T *sfcnU = ssG
Inlining an S-Function3-35voidMdlDerivatives(){ /* S-Function block: foo */ { Simstruct *s = ssGetSFunction(S, 0); real_T *sfcnU = ssGetU(s);
Using the Target Language Compiler1-3For those familiar with HTML, Perl, and MATLAB®, you will find that the Target Language Compiler borrows ideas fr
3 Writing Target Language Files3-36 /* Register children S-Functions (s-funcs without TLC files) */ { static SimStruct childSFunctions[1]; sta
Inlining an S-Function3-37To avoid unnecessary calls to the S-function and to generate the minimum code required for the S-function, the following TLC
3 Writing Target Language Files3-38By including this simple target file for this S-function block, the code is generated as:voidMdlStart(){}voidMdlOut
Inlining an S-Function3-39Note 2 The input to foo is rtGROUND (an RTW global equal to 0.0) since foo is the only block in the model, and its input is
3 Writing Target Language Files3-40Configurable RTW VariablesThis table lists the configurable RTW variables.These variables can be changed at the com
Inlining an S-Function3-41Figure 3-3 shows the RTW dialog box with the change to modify the FileSizeThreshold.Figure 3-3: RTW Dialog BoxMatrix Parame
3 Writing Target Language Files3-42For example, given the 2-by-3 matrixmodel.h defines:typedef struct Parameters_tag = { struct { /* S-f
Inlining an S-Function3-43unless it is explicitly accessed by LibBlockParameter or LibBlockParameterAddr.
3 Writing Target Language Files3-44Loop RollingThe best way to explain loop rolling is by example. Figure 3-4 shows a Simulink model with a Gain block
Loop Rolling3-45The outputs function for the Gain block is:%% Function: Outputs ===========================================%% Abstract:%% Y = U *
1 Using the Target Language Compiler with Real-Time Workshop1-4Figure 1-1: The Target Language Compiler ProcessSimulink Model (sample.mdl)Real-Time W
3 Writing Target Language Files3-46For example, the Gain block in this example is defined in the RTW file as:Block {Type GainName "<Root>/K
Loop Rolling3-47The generated code for this example is:/* Gain Block: <Root>/Kp */ { int_T i1; real_T *u0 = &rtB.Constant1[0]; rea
3 Writing Target Language Files3-48with the %roll that works under both situations. Table 3-8 contains the valid variables assigned to rollVars.For ex
4Target Language Compiler Function Library ReferenceLibBlockFunctionExists . . . . . . . . 4-2LibBlockInputSignal . . . . .
LibBlockFunctionExists4-2LibBlockFunctionExistsPurposeDetermines if a given block function existsSyntax%<LibBlockFunctionExists(block, fcn)>Argu
LibBlockInputSignal4-3LibBlockInputSignalPurposeDetermines the input signal label based on the type of input signalSyntax%<LibBlockInputSignal(port
LibBlockIWork4-4LibBlockIWorkPurposeDetermines the appropriate iwork elementSyntax%<LibBlockIWork(iwork, ucv, lcv, idx)>ArgumentsiworkReference
LibBlockMatrixParameterAddr4-5LibBlockMatrixParameterAddrPurposeDetermines the address of a block’s matrix parameterSyntax%<LibBlockMatrixParameter
LibBlockMatrixParameter4-6LibBlockMatrixParameterPurposeDetermines the appropriate matrix parameter for a block given the row and column user control
LibBlockMode4-7LibBlockModePurposeDetermines the appropriate block modeSyntax%<LibBlockMode(ucv, lcv, modeIdx)>ArgumentsucvUser control variable
Using the Target Language Compiler1-5By modifying the target files (also referred to as TLC files, for example, basic.tlc), you can customize the outp
LibBlockOutportLocation4-8LibBlockOutportLocationPurposeDetermines the appropriate identifier for an outport blockSyntax%<LibBlockOutportLocation(u
LibBlockOutportLocation4-9Output location is B:Notes: The index is appropriately replaced with ucv or lcv when specified (ucv has higher precedence t
LibBlockOutputSignal4-10LibBlockOutputSignalPurposeDetermines the block’s output signal.Syntax%<LibBlockOutputSignal(portIdx, ucv, lcv, sigIdx)>
LibBlockParameter4-11LibBlockParameterPurposeDetermines a block’s parameter in the appropriate form depending on the state of loop rollingSyntax%<L
LibBlockParameter4-12Note: Case 4 maintains the parameter even though InlineParameters is selected.Do not use this function if you’re using the resul
LibBlockParameterAddr4-13LibBlockParameterAddrPurposeDetermines the address of a block parameter.Syntax%<LibBlockParameterAddr(param, ucv, lcv, idx
LibBlockPWork4-14LibBlockPWorkPurposeDetermines the appropriate pwork elementSyntax%<LibBlockPWork(pwork, ucv, lcv, idx)>ArgumentspworkReference
LibBlockRWork4-15LibBlockRWork PurposeDetermines the appropriate rwork elementSyntax%<LibBlockRWork(rwork, ucv, lcv, idx)>ArgumentsrworkReferenc
LibBlockSrcSignalIsDiscrete4-16LibBlockSrcSignalIsDiscretePurposeDetermines if the driving signal is discreteSyntax%<LibBlockSrcSignalIsDiscrete(po
LibCacheDefine4-17LibCacheDefinePurposeCall this function from inside BlockTypeSetup to cache a #define statement.Syntax%<LibCacheDefine(buffer)>
1 Using the Target Language Compiler with Real-Time Workshop1-6This file shows the structure of the small.rtw file.CompiledModel { Name "small&q
LibCacheFunctionPrototype4-18LibCacheFunctionPrototypePurposeCall this function from inside BlockTypeSetup to cache a function prototype.Syntax%<Li
LibCacheGlobalPrmData4-19LibCacheGlobalPrmDataPurposeCall this function from inside BlockInstanceSetup to cache global block parameter data.Syntax%<
LibCacheInclude4-20LibCacheIncludePurposeCall this function from inside BlockTypeSetup to cache a #include statement.Syntax%<LibCacheInclude(buffer
LibCacheNonFiniteAssignment4-21LibCacheNonFiniteAssignmentPurposeCall this function from inside BlockInstanceSetup to cache assignments that need to b
LibContinuousState4-22LibContinuousStatePurposeDetermines the block continuous state with optional scalar expansionSyntax%<LibContinuousState(ucv,
LibControlPortInputSignal4-23LibControlPortInputSignalPurposeDetermines the appropriate control port input signal depending on the source of the input
LibConvertZCDirection4-24LibConvertZCDirectionPurposeConverts Real-Time Workshop zero-crossing direction to a SimStruct representationSyntax%<LibCo
LibDataInputPortWidth4-25LibDataInputPortWidthPurposeDetermines the width of an input portSyntax%<LibDataInputPortWidth(portNum)>ArgumentsportNu
LibDataOutputPortWidth4-26LibDataOutputPortWidth PurposeDetermines the width of the block’s output portSyntax%<LibDataOutputPortWidth(portNum)>A
LibDataStoreMemory4-27LibDataStoreMemoryPurposeDetermines the appropriate data store memory valueSyntax%<LibDataStoreMemory(ucv, lcv, variableIdx)&
Using the Target Language Compiler1-7<Parameters omitted>}Block { Type Outport Name "<Root>/Out" Identifier Out
LibDeclareRollVariables4-28LibDeclareRollVariablesPurposeDeclares the necessary local variables required for loop rollingSyntax%<LibDeclareRollVari
LibDeclareRollVariables4-29For example, rollVars = ["U", "<param>/Gain"] declares all nonscalar block inputs and the specifi
LibDefineIWork4-30LibDefineIWorkPurposeCall this function from inside the block’s BlockInstanceSetup function to define the specified iwork in the blo
LibDefinePWork4-31LibDefinePWorkPurposeCall this function from inside the block’s BlockInstanceSetup function to define the specified pwork in the blo
LibDefineRWork4-32LibDefineRWorkPurposeCall this function from inside the block’s BlockInstanceSetup function to define the specified rwork definition
LibDiscreteState4-33LibDiscreteStatePurposeDetermines a block’s discrete state with optional scalar expansionSyntax%<LibDiscreteState(ucv, lcv, idx
LibExternalResetSignal4-34LibExternalResetSignalPurposeDetermines the appropriate reset signal into the reset port depending on the source of input si
LibHeaderFileCustomCode4-35LibHeaderFileCustomCodePurposePlaces code at the top or bottom of the model’s header fileSyntax%<LibHeaderFileCustomCode
LibIndexStruct4-36LibIndexStructPurposeReturns an optional index for a structure fieldSyntax%<LibIndexStruct(width, ucv, lcv, idx)>Argumentswidt
LibIsDiscrete4-37LibIsDiscretePurposeDetermines if a block is discrete based on its task identifier (TID)Syntax%<LibIsDiscrete(tid)>Argumentstid
1 Using the Target Language Compiler with Real-Time Workshop1-8To use the Target Language Compiler on small.rtw to generate all associated RTW code, e
LibIsEmpty4-38LibIsEmptyPurposeDetermines if input is an empty string, an empty vector, or an empty matrix arraySyntax%<LibIsEmpty(input)>Argume
LibIsEqual4-39LibIsEqualPurposeDetermines if expr1 equals expr2Syntax%<LibIsEqual(expr1, expr2)>Argumentsexpr1First expression.expr2Second expre
LibIsFinite4-40LibIsFinitePurposeDetermines if the number is finiteSyntax%<LibIsFinite(value)>ArgumentsvalueAny number including rtInf, rtMinusI
LibMapSignalSource4-41LibMapSignalSourcePurposeDetermines the appropriate source signal given the mapping source and mapping indexSyntax%<LibMapSig
LibMaxBlockIOWidth4-42LibMaxBlockIOWidthPurposeDetermines the maximum width of the input or output portsSyntax%<LibMaxBlockIOWidth()>Argumentsno
LibMaxDataInputPortWidth4-43LibMaxDataInputPortWidthPurposeDetermines the maximum width of all the input portsSyntax%<LibMaxDataInputPortWidth()>
LibMaxDataOutputPortWidth4-44LibMaxDataOutputPortWidthPurposeDetermines the maximum width of all the output ports.Syntax%<LibMaxDataOutputPortWidth
LibMdlRegCustomCode4-45LibMdlRegCustomCodePurposePlaces code at the top or bottom of the model’s registration functionSyntax%<LibMdlRegCustomCode(b
LibMdlStartCustomCode4-46LibMdlStartCustomCodePurposePlaces code at the top or bottom of the MdlStart functionSyntax%<LibMdlStartCustomCode(buffer,
LibMdlTerminateCustomCode4-47LibMdlTerminateCustomCodePurposePlaces code at the top or bottom of the MdlTerminate functionSyntax%<LibMdlTerminateFc
Using the Target Language Compiler1-9These files contain the fully documented C code that represents your Simulink model. At this point, you can use t
LibOptionalMatrixWidth4-48LibOptionalMatrixWidthPurposeDetermines the optional width of a matrixSyntax%<LibOptionalMatrixWidth(nRows, nCols)>Arg
LibOptionalVectorWidth4-49LibOptionalVectorWidthPurposeDetermines if length is greater than 1Syntax%<LibOptionalVectorWidth(length)>Argumentslen
LibPathName4-50LibPathNamePurposeDetermines the full path of a systemSyntax%<LibPathName(name)>ArgumentsnameString name of system (e.g., "&
LibPrevZCState4-51LibPrevZCStatePurposeDetermines the appropriate element for previous zero-crossing state based on ucv, lcv, and pzcIdx.Syntax%<Li
LibPrmFileCustomCode4-52LibPrmFileCustomCodePurposePlaces code at the top or bottom of the model’s parameter fileSyntax%<LibPrmFileCustomCode(buffe
LibRegFileCustomCode4-53LibRegFileCustomCodePurposePlaces code at the top or bottom of the model’s registration fileSyntax%<LibRegFileCustomCode(bu
LibRenameParameter4-54LibRenameParameterPurposeRenames the parameter and creates a new reference to the parameterSyntax%<LibRenameParameter(block,
LibSourceFileCustomCode4-55LibSourceFileCustomCode PurposePlaces code at the top of the model’s source fileSyntax%<LibSourceFileCustomCode(buffer,
LibSystemDerivativeCustomCode4-56LibSystemDerivativeCustomCodePurposePlaces code at the top or bottom of a system’s derivative functionSyntax%<LibS
LibSystemDisableCustomCode4-57LibSystemDisableCustomCodePurposePlaces code at the top or bottom of a system’s disable functionSyntax%<LibSystemDisa
1 Using the Target Language Compiler with Real-Time Workshop1-10FilesThe Target Language Compiler works with various sets of files to produce its resu
LibSystemEnableCustomCode4-58LibSystemEnableCustomCodePurposePlaces code at the top or bottom of a system’s enable functionSyntax%<LibSystemEnableC
LibSystemInitializeCustomCode4-59LibSystemInitializeCustomCodePurposePlaces code at the top or bottom of a system’s initialize functionSyntax%<LibS
LibSystemOutputCustomCode4-60LibSystemOutputCustomCodePurposePlaces code at the top or bottom of a system’s output functionSyntax%<LibSystemOutputC
LibSystemUpdateCustomCode4-61LibSystemUpdateCustomCodePurposePlaces code at the top or bottom of a system’s update functionSyntax%<LibSystemUpdateC
LibSystemUpdateCustomCode4-62
Amodel.rtwModel.rtw File Contents . . . . . . . . . . . . . . . . A-2Model.rtw File Contents — System Record . .
A model.rtwA-2Model.rtw File ContentsThis appendix describes the contents of the model.rtw file, which is created from your block diagram during the R
model.rtwA-3RelTolRelative tolerance.AbsTolAbsolute tolerance.RefineRefine factor.MaxStepMaximum step size.InitialStepInitial step size.MaxOrderMaximu
A model.rtwA-4DirectFeedthroughDoes model require its inputs in the MdlOutput function (yes/no)?NumContStatesTotal number of continuous states in the
model.rtwA-5NumIWorkLength of the model integer-work vector (iwork). Integer-work elements are used by blocks that need to keep track of “integer” var
Files1-11mdlwide.tlc, which contains all of the settings and parameter values that control generic C code generation.The set of system target files in
A model.rtwA-6PeriodAndOffsetPeriod and offset for this sample time.}RootSignals {Signal and block information in the root “window.”NumSignalsNumber o
model.rtwA-7SLNameUnmodified Simulink name. This is only written if it is not equal to Name.VirtualWhether or not the subsystem is virtual.NumSignalsN
A model.rtwA-8SLNameUnmodified Simulink name. This is only written if it is not equal to Name.MemoryNameName of the data store memory region.Identifie
model.rtwA-9IdentifierUnique variable name across all block outputs.SigSrc[systemIndex, blockIndex, outputPortIndex].SigIdx[blockIOVectorIndex, signal
A model.rtwA-10InMask noAlgebraicLoopId 0ContStates [0,0]DiscStates [0,0]RWork [0,0]IWork [0,0]PWork [0,0]ModeVector [0,0]NonsampledZCs [0,0]ZCEvents
model.rtwA-11Model.rtw File Contents — System RecordIn general, a model can consist of multiple systems. There is one system for the root and one for
A model.rtwA-12OutputUpdateFcnName of output/update function for trigger or enable_with_trigger systems.NumBlocksNumber of blocks in the system.Block
model.rtwA-13FundamentalTIDOnly written for multirate or hybrid enabled subsystems. This gives the sample time as the greatest common divisor of all s
A model.rtwA-14DirectionDirection of zero-crossing: Falling, Any, Rising.}ZCEventsSpecified as [N,I], where N is the number of zero-crossing events an
model.rtwA-15ControlPort {One record for control input port.TypeType of control port: enable, trigger, or function-call.WidthLength of the signal ente
How to Contact The MathWorks:508-647-7000 Phone508-647-7001 FaxThe MathWorks, Inc. Mail24 Prime Park WayNatick, MA 01760-1500http://www.mathworks.com
1 Using the Target Language Compiler with Real-Time Workshop1-12Where to Go from HereThe remainder of this book contains both explanatory and referenc
A model.rtwA-16StringTypeOne of:•"Computed" indicating the parameter is computed from values entered in the Simulink dialog box.•"Varia
model.rtwA-17Model.rtw File Contents — Block Specific RecordsThe following table describes the block specific records written for the Simulink blocks.
A model.rtwA-18Block Type: CombinatorialLogic (example of 8-by-2 table):Parameter {Name "TruthTable"Value Matrix(8,2)[[0, 0]; [0, 1]; [0, 1]
model.rtwA-19}Block Type: DataStoreWriteParamSettings {DataStoreRegion index into data stores list.}Block Type: Deadzone (example of a deadzone block
A model.rtwA-20Block Type: DerivativeThe Derivative block computes its derivative by using the approximation (input–prevInput)/deltaTTwo “banks” of hi
model.rtwA-21}Block Type: DigitalClockNo block specific records.Block Type: DiscreteFilterSee Model.rtw File Contents — Linear Block Specific Records
A model.rtwA-22Value [–0.25, 0, –0.75]String "[–.25 0 –.75]"StringType "Expression"}NumRWorkDefines0, 1, or 2.RworkDefine {Present
model.rtwA-23BlockType: DiscretePulseGenerator (shown below is a discrete pulse generator with an amplitude of 1, a period of 2 samples, a pulse width
A model.rtwA-24NumIWorkDefines1(There is one integer work for each output signal.)IWorkDefine {Name "ClockTicksCounter"Width 1}Block Type: D
model.rtwA-25Virtual. Not written to model.rtw file.Block Type: FromVirtual. Not written to model.rtw file.Block Type: FromFileParamSettings {NumPoint
2Working with theTarget LanguageWhy Use the Target Language Compiler? . . . . . . . 2-2The model.rtw File . . . . . . . .
A model.rtwA-26LHS {Op "SIN"LHS {Op "U"LHS {Op "NUM"Value 1}}}RHS {Op "NUM"Value 10}}Block Type: Gain (example
model.rtwA-27Block Type: GotoVirtual. Not written to model.rtw file.Block Type: GroundVirtual. Not written to model.rtw file.Block Type: HitCross (exa
A model.rtwA-28Block Type: InportVirtual. Not written to model.rtw file.Block Type: Integrator (shown below is a limited integrator configured with an
model.rtwA-29ParamSettings {ExternalResetnone, rising, falling, or eitherInitialConditionSourceinternal or externalLimitOutputon or offShowSaturationP
A model.rtwA-30Parameter {The output values, y, of the function y = f(x).Name "OutputValues"Value [0, 1, 2, 3, 4, 5]String " [0:5]"
model.rtwA-31Name "RowIndex"Value [1, 2]String "1:2"StringType "Expression"}Parameter {The “column” input values, y, to
A model.rtwA-32StringType "Computed"}ParamSettings {ColZeroTechniqueNormalInterp, AverageValue, or MiddleValueColZeroIndex0}Block Type: Math
model.rtwA-33Width 2}Block Type: MinMaxParamSettings {Functionmin or max.}Block Type: MultiPortSwitchNo block specific records.Block Type: MuxVirtual.
A model.rtwA-34ProbeSampleTimeon or off}Block Type: ProductNo block specific records.Block Type: Quantizer (example of a quantizer block with a quanti
model.rtwA-35StringType "Computed"}NumIWorkDefines 1IWorkDefine {Name "RandSeed"Width 1}NumRWorkDefines 1RWorkDefine {Name "N
2 Working with the Target Language2-2Why Use the Target Language Compiler?If you simply need to produce ANSI C code from a Simulink model, you do not
A model.rtwA-36String "–1"StringType "Expression"}ParamSettings {SignalLimit the rate of change of the output or input signal.}Num
model.rtwA-37Value [2.220446049250313e–16]String "eps"StringType "Variable"}Parameter {Name "OffSwitchValue"Value [2.220
A model.rtwA-38Block Type: ResetIntegratorNo support for the obsoleted Reset Integrator block.Block Type: RoundingParamSettings {Operatorfloor, ceil,
model.rtwA-39SaveToWorkspaceIf scope is configured to save its data, then yes, otherwise no.SaveNameName of variable used to save scope data.MaxRowsMa
A model.rtwA-40ParamSettings {FunctionNameName of S-function.FunctionTypeType of S-function: "M-File", "C-MEX", or "FORTRAN-M
model.rtwA-41Block Type: SignalGenerator (example of a signal generator with an amplitude of 1 and a frequency of 1).Parameter {Name "Amplitude&q
A model.rtwA-42Block Type: Sin (The following is an example for the Sine Wave block configured with a discrete sample time of 1 second):Parameter {Nam
model.rtwA-43Value [0.009999833334166664]String ""StringType "Computed"}Parameter {This is a discrete sine coefficient and is only
A model.rtwA-44}Block Type: StateSpaceSee Model.rtw File Contents — Linear Block Specific Records on page A-51.Block Type: SumParamSettings {InputsA v
model.rtwA-45StringType "Expression"}Block Type: ToFileThe following is an example of a ToFile block configured with a filename of untitled.
The model.rtw File2-3The model.rtw FileReal-Time Workshop generates a model.rtw file from your Simulink model. The model.rtw file is a hierarchical da
A model.rtwA-46}Block Type: ToWorkspaceParamSettings {VariableNameName of variable used to save scope data.BufferMaximum number of rows to save or 0 f
model.rtwA-47InitialInput [0]BufferSize [1024]}NumIWorkDefines 1IWorkDefine {Name "BufferIndices"Width 4}NumPWorkDefines 1PWorkDefine {Name
A model.rtwA-48Block Type: UniformRandomNumber (example of a uniform random number block with minimum of –1, maximum of 1, initial seed of 0).Paramete
model.rtwA-49}Block Type: UnitDelay (example of a unit delay with an initial condition of 0).Parameter {Name "X0"Value [0]String "0&quo
A model.rtwA-50Name "BufferIndices"Width 4}NumPWorkDefines 1PWorkDefine {Name "TUbuffer"Width 2}Block Type: WidthNo block specific
model.rtwA-51Model.rtw File Contents — Linear Block Specific RecordsThe following table describes the block specific records written for the Simulink
A model.rtwA-52Name "Dmatrix"ValueVector that could be of zero length.String""StringType "Computed"}Parameter {Initial c
model.rtwA-53ColIdxOfNonZeroDColumn index of the nonzero elements in the D matrix.}Table A-4: Model.rtw File Contents — Linear Block Specific Record
A model.rtwA-54
BTarget Language CompilerError Messages
2 Working with the Target Language2-4CompiledModel {Name "gain1"Version "1.85 (Oct, 30 1996)"...System {Type rootName &quo
B Target Language Compiler Error MessagesB-2This appendix lists and describes error messages generated by the Target Language Compiler. Use this refer
B-3%closefile or %selectfile argument must be a valid open fileWhen using %closefile or %selectfile, the argument must be a valid file variable opened
B Target Language Compiler Error MessagesB-4A language choice must be made using the %language directive prior to using GENERATE or GENERATE_TYPETo us
B-5Argument to identifier must be a stringThe following built-in functions expect a string and report this error if the argument passed is not a strin
B Target Language Compiler Error MessagesB-6Bad cast - unable to cast this expression to "type"The Target Language Compiler does not know ho
B-7is illegal, whereas:%<CompiledModel.System[Sysidx].Block[BlkIdx].Name + \"Hello">is correct.Extra arguments to the function-name bu
B Target Language Compiler Error MessagesB-8Function reached the end and did not return a valueFunctions that are not declared as void or Output must
B-9It is illegal to return functions or macros from a functionA function or macro value cannot be returned from a function call.Named value identifier
B Target Language Compiler Error MessagesB-10Output file identifier opened with %openfile was not closedOutput files opened with %openfile must be clo
B-11The %continue directive can only appear within a %foreach, %for, or %roll statementThe %continue directive can only be used in a %foreach, %for, o
The model.rtw File2-5This example shows several records and corresponding subrecords by use of arrows. Parameter (Scope 4) is a subrecord of Block (Sc
B Target Language Compiler Error MessagesB-12The %implements language does not match the language currently being generated (language)The language or
B-13identifier. When using array indexing on a scalar, the constant is automatically scalar expanded and the value of the scalar is returned. For exam
B Target Language Compiler Error MessagesB-14The error is reported on the line that opens the scope and has no matching end scope.Note: Nested scopes
B-15The final argument to %roll must be a valid block scopeWhen using %roll, the final argument (prior to extra user-specified arguments) must be a va
B Target Language Compiler Error MessagesB-16The language being implemented has changed from old-language to new-language (Warning)The language being
B-17The number of rows specified (specified-rows) did not match the actual number of rows seen in the matrix (actual-rows)When specifying a Target Lan
B Target Language Compiler Error MessagesB-18The specified index (index) was out of the range 0 to number-of-elements – 1This error occurs when indexi
B-19There was no type associated with the given block for GENERATEThe scope specified to GENERATE must include a Type parameter that indicates which t
B Target Language Compiler Error MessagesB-20Unable to open output file filenameUnable to open the specified output file; either an invalid filename w
B-21Unrecognized type "output-type" for functionThe function type modifier was not Output or void. For functions that do not produce output,
2 Working with the Target Language2-6Compiler DirectivesSyntaxA target language file consists of a series of statements of the form%keyword [argument1
B Target Language Compiler Error MessagesB-22Usage: tlc [options] fileA command line problem has occurred. The error message contains a list of all of
B-23When appending to a buffer stream, the variable must be a stringYou can specify the append option for a buffer stream only if the variable current
B Target Language Compiler Error MessagesB-24
CTarget Language CompilerLibrary Error Messagesblkiolib.tlc Error Messages . . . . . . . . . . . . . C-3blocklib.tlc Error
C Target Language Compiler Library Error MessagesC-2This appendix lists and describes error messages that may be generated when working with the Targe
blkiolib.tlc Error MessagesC-3blkiolib.tlc Error MessagesInvalid map source (mappingSource) specified for Type block: Name(LibMapSignalSource) Real-Ti
C Target Language Compiler Library Error MessagesC-4blocklib.tlc Error MessagesDon't know how to roll IWork for Type block: Name(LibBlockIWork) I
hookslib.tlc Error MessagesC-5hookslib.tlc Error MessagesAdd root initialization code with LibMdlStartCustomCode(LibSystemInitializeCustomCode) The ro
C Target Language Compiler Library Error MessagesC-6System system.Name does not have Disable function(LibSystemDisableCustomCode) The subsystems types
paramlib.tlc Error MessagesC-7paramlib.tlc Error MessagesLoop rolling not supported for param.Name in Type block Name(LibBlockMatrixParamter, LibBlock
Compiler Directives2-7Conditional inclusion%if constant-expression%else%elseif constant-expression%endif%switch constant-expression%case constant-expr
C Target Language Compiler Library Error MessagesC-8rolllib.tlc Error Messages1-- The inputs for Type block Name are not rollable, or do not exist(Lib
rolllib.tlc Error MessagesC-98-- Unable to declare roll variable p_name for Type block Name(LibDeclareRollVariables) The variable rollVars contains &l
C Target Language Compiler Library Error MessagesC-1016-- There are no previous zero-crossings to roll in Type block: Name(LibDeclareRollVariables) Th
utillib.tlc Error MessagesC-11utillib.tlc Error MessagesInvalid matrix size (nRows x nCols) for Type block: Name(LibOptionalMatrixWidth) Either nRows
C Target Language Compiler Library Error MessagesC-12
I-1IndexSymbols! 2-14% 2-6, 2-13... character 2-9.c file 1-3.h file 1-3.log 2-51.prm file 1-3.reg file 1-3.rtw file 1-3, 2-29structure 2-3.tlc files 1
IndexI-2customizingcode generation 1-10Simulink block 2-24Ddebugmessage 2-29mode 2-51%default 2-19%define 2-37Derivatives 3-19directive 1-10, 2-6objec
IndexI-3formatting 2-17Function 2-10%function 2-44functionbuilt-in TLC 3-30C MEX S-function 1-3call 2-14GENERATE 2-25GENERATE_TYPE 2-25global 1-11libr
IndexI-4LibConvertZCDirection 4-24LibDataInputPortWidth 3-22, 4-25LibDataOutputPortWidth 3-22, 4-26LibDataStoreMemory 3-26, 4-27LibDeclareRollVariable
IndexI-5MdlStartInitializeConditions 3-18Start 3-18MdlTerminateTerminate 3-19mdlTerminate (S-function) 3-31MdlUpdateUpdate 3-19mdlUpdate (S-function)
2 Working with the Target Language2-8CommentsYou can place comments anywhere within a target file. To include comments, use the /%...%/ or %% directiv
IndexI-6OUTPUT_LINES 2-32Outputs 3-18, 3-48Pparameterdefining 1-10inlining 3-40value pair 2-3Parameters 3-48pathspecifying absolute 2-28specifying rel
IndexI-7Simulinkand Real-Time Workshop 1-2block parameters 3-41generating code 1-3SIZE 2-33, 3-30Special 2-11STAND_ALONE 2-33Start 3-18STDOUT 2-33STRI
IndexI-8Vvalues 2-10variablesblock-scoped 2-41global 3-9local 3-9RTW 3-40Vector 2-12void modifier 2-45W%warning 2-29warning message 2-29WHITE_SPACE 2-
Compiler Directives2-9Use the /%...%/ construct to delimit comments within your code. Use the %% construct for line-based comments; all characters fro
iContents1Using the Target Language Compilerwith Real-Time WorkshopUsing the Target Language Compiler . . . . . . . . . . . . . . . . . . . 1-2Introd
2 Working with the Target Language2-10Target Language ValuesTable 2-2 shows the types of values you can use within the context of expressions in your
Compiler Directives2-11"Matrix" Matrix (3,2) [ [ 1, 2] [3 , 4] [ 5, 6] ]Matrices are simply lists of vectors. The individual elements of the
2 Working with the Target Language2-12"String" "Hello, World"ASCII character strings. In all contexts, two strings in a row are co
Compiler Directives2-13Target Language ExpressionsIn any place throughout a target file, you can include an expression of the form %<expression>
2 Working with the Target Language2-14This statement would cause an error if foo was undefined.Table 2-3: Target Language ExpressionsExpression Defin
Compiler Directives2-15–expr Unary minus negates the expression. The argument must be numeric.+expr No effect; the operand must be numeric.~expr Bitwi
2 Working with the Target Language2-16expr– expr Subtracts the two expressions; the operands must be numeric.expr<< expr Left shifts the left op
Compiler Directives2-17FormattingBy default, the Target Language Compiler outputs all floating-point numbers in exponential notation with 16 digits of
2 Working with the Target Language2-18Conditional InclusionThe conditional inclusion directives are%if constant-expression%else%elseif constant-expres
Compiler Directives2-19%switchThe %switch statement evaluates the constant expression and compares it to all expressions appearing on %case selectors.
ii ContentsMultiple Inclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19%foreach . . . . . . . . . . . . . . . . . .
2 Working with the Target Language2-20identifier variable. %break and %continue are optional directives that you can include in the %foreach directive
Compiler Directives2-21identifier2 specifies the identifier to be used for testing whether the loop was rolled within the body. For example,%for Index
2 Working with the Target Language2-22%rollThe syntax of the %roll multiple inclusion directive is:%roll ident1 = roll-vector-exp, ident2 = threshold-
Compiler Directives2-23LoopTrailer(block, Startidx, Niterations, Nrolled, …). This function is called once for each section that will roll after the b
2 Working with the Target Language2-24Extending the former example to a loop that rolls:%language "C"%assign ablock = BLOCK { Name "Hi&
Compiler Directives2-25appear prior to the first GENERATE or GENERATE_TYPE built-in function call. %language specifies the language as a string. For e
2 Working with the Target Language2-26appearing in an implementation file (from outside the specified file) only by using the GENERATE and GENERATE_TY
Compiler Directives2-27Output File ControlThe structure of the output file control construct is:%openfile string optional-equal-string optional-mode%c
2 Working with the Target Language2-28Input File ControlThe input file control directives are:%include string%addincludepath stringThe %include direct
Compiler Directives2-29Typically, %addincludepath directives should be specified in your system target file. Multiple %addincludepath directives will
iiiCoding Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-8Writing a Block Target File . . . . . . . . . . . . .
2 Working with the Target Language2-30defined in uppercase so that they are visually distinct from other parameters in the .rtw file, and by conventio
Compiler Directives2-31FORMAT(expr1, expr2)The first expression is a Real value to format. The second expression is either "EXPONENTIAL" or
2 Working with the Target Language2-32GENERATE_TYPE_FUNCTION_EXISTS(expr1, expr2, expr3)Same as GENERATE_FUNCTION_EXISTS except it overrides the Type
Compiler Directives2-33SIZE(expr[,expr])Calculates the size of the first expression and generates a two-element, row vector. If the second operand is
2 Working with the Target Language2-34STRINGOF(expr)Accepts a vector of ASCII values and returns a string that is constructed by treating each element
Compiler Directives2-35FEVAL FunctionThe FEVAL built-in function calls MATLAB M-file functions and MEX-functions. The structure is:%assign result = FE
2 Working with the Target Language2-36When calling MATLAB, these conversions are made:When values are returned from MATLAB, they are converted as foll
Compiler Directives2-37Macro DefinitionTo simplify complicated references, target files can define macros that are expanded when they appear in subseq
2 Working with the Target Language2-38Within the scope of a function, variable assignments always create new local variables unless you use the :: sco
Compiler Directives2-39Creating RecordsUse the %assign directive to create new records. For example, if you have a record called Rec1 that contains a
iv ContentsLibCacheNonFiniteAssignment . . . . . . . . . . . . . . . . . . . . . . 3-29Built-In TLC Functions . . . . . . . . . . . . . . . . . . .
2 Working with the Target Language2-40This produces:Figure 2-2: Creating Multiple RecordsAdding Parameters to an Existing RecordYou can use the %assi
Compiler Directives2-41adds a new parameter, N, at the end of an existing block with the name and current value of an existing variable as shown in Fi
2 Working with the Target Language2-42Variable ScopingThe Target Language Compiler uses a form of dynamic scoping to resolve references to variables.
Compiler Directives2-43The System[Sysidx] scope is added to the search list, and it is searched before anything else.Figure 2-5: Modifying the Search
2 Working with the Target Language2-44The scoping rules within functions behave differently. A function has its own scope, and that scope gets added t
Compiler Directives2-45A function optionally returns a value with the %return directive. The returned value can be any of the types defined in the Tar
2 Working with the Target Language2-46Variable Scoping Within FunctionsWithin a function, the left-hand member of any %assign statement defaults to cr
Compiler Directives2-47You can override this default behavior by using %assign with the :: operator. For example, %assign ::global = 3makes global a g
2 Working with the Target Language2-48is not searched. Also, if a %with is included within a function, its associated scope is carried with any nested
Compiler Directives2-49%returnThe %return statement closes all %with statements appearing within the current function. In this example, the %with stat
vLibDataOutputPortWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26LibDataStoreMemory . . . . . . . . . . . . . . . . . . . . . .
2 Working with the Target Language2-50Target Language CompilerCommand Line ArgumentsTo call the Target Language Compiler, use:tlc [switch1 expr1 switc
Target Language Compiler2-51As an example, the command linetlc –r Demo.rtw –v grt.tlcspecifies that Demo.rtw should be read and used to process grt.tl
2 Working with the Target Language2-52The output of the listing file includes the number of times each line is encountered followed by a colon.1: %% A
Target Language Compiler2-531: %assign y = LibBlockOutputSignal(0, "", lcv, sigIdx)1: %assign u = LibBlockInputSignal(0, ""
2 Working with the Target Language2-54
3Writing TargetLanguage FilesA Basic Example . . . . . . . . . . . . . . . . . . 3-2Process . . . . .
3 Writing Target Language Files3-2A Basic ExampleThis section presents an elementary example of creating a target language file that generates specifi
A Basic Example3-3Selecting Parameters from Simulink’s Simulation menu displays the dialog box shown in Figure 3-2.Figure 3-2: Simulation Parameters
3 Writing Target Language Files3-4Clicking the Build button generates the .rtw file, basic.rtw, and executes the system target file, basic.tlc with th
A Basic Example3-5The file, basic.tlc, is a TLC file that uses the .rtw code to generate text that contains the model’s name, generation date, and its
vi ContentsAmodel.rtwModel.rtw File Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2Model.rtw File Contents — System Record
3 Writing Target Language Files3-6Target Language Compiler ArchitectureSystem Target FilesTable 3-1 lists the system target files that generate the RT
Target Language Compiler Architecture3-7Program flow through the system target files avoids multiple passes through the RTW file. You should not chang
3 Writing Target Language Files3-8Coding ConventionsThe following guidelines help ensure that the programming style in each TLC file is consistent, an
Coding Conventions3-9of the Name identifier into the parent block scope is currently done for the Parameter, RWorkDefine, IWorkDefine, and PWorkDefine
3 Writing Target Language Files3-10inside the library file, it should start with Fcn and the function should be placed at the bottom of funclib.tlc.%%
Coding Conventions3-11Table 3-4: TLC Global Variables Specifying RTW Global VariablesDescription TLC Global Variable Default ValueBlock I/OtBlockIO r
3 Writing Target Language Files3-127This convention creates consistent variables throughout the TLC files. For example, the Gain block contains the fo
Coding Conventions3-13Notes about this TLC code:Note 1 The code section for each block begins with a comment specifying the block type and name.Note 2
3 Writing Target Language Files3-14Target Language Compiler function library, funclib.tlc, contains this TLC code to prevent multiple inclusion:%if EX
Writing a Block Target File3-15Writing a Block Target FileTo write a block target file, use these polymorphic block functions combined with the Target
1Using the Target Language Compiler with Real-Time WorkshopUsing the Target Language Compiler. . . . . . . . . 1-2Introduction . .
3 Writing Target Language Files3-16%function BlockInstanceSetup(block, system) void%% Rename S-function parameter so that the TLC and%% generated code
Writing a Block Target File3-17As an example, given S-function foo requiring a #define and two function declarations in the header file, you could def
3 Writing Target Language Files3-18Start(block, system)Include a Start function to place code into MdlStart. The code inside MdlStart executes once an
Writing a Block Target File3-19Update(block, system)Include an Update function if the block has code that needs to be updated each major time step. Co
3 Writing Target Language Files3-20The RTW TLC Function LibraryThe file funclib.tlc contains the RTW TLC function library. This file contains the nece
The RTW TLC Function Library3-21LibDefineRWork(block, name, width)This call should be made from inside the block’s BlockInstanceSetup function, and ad
3 Writing Target Language Files3-22buffer. The prototypes are placed inside model.h among other generated function prototypes.LibCacheDefine(buffer)Li
The RTW TLC Function Library3-23they generate different results depending on whether RTW is in a loop-rolling state, or a non loop-rolling state, resp
3 Writing Target Language Files3-24For an example of this function, see gain.tlc.Note 1: Do not use this function to build the address of a parameter
The RTW TLC Function Library3-25columns of your matrix. This function will degenerate to a vector or scalar, if needed.Note: Do not use this function
Komentarze do niniejszej Instrukcji