MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS Guide de l'utilisateur

Naviguer en ligne ou télécharger Guide de l'utilisateur pour Logiciel MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS. MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS User`s guide Manuel d'utilisatio

  • Télécharger
  • Ajouter à mon manuel
  • Imprimer
  • Page
    / 210
  • Table des matières
  • MARQUE LIVRES
  • Noté. / 5. Basé sur avis des utilisateurs

Résumé du contenu

Page 1 - Writing S-Functions

ModelingSimulationImplementationWriting S-FunctionsVersion 3

Page 2 - How to Contact The MathWorks:

1 Overview of S-Functions1-4When to Use an S-FunctionThe most common use of S-functions i s to create custom Simulink blocks. Youcan use S -functions

Page 3 - Contents

3 Writing S-Functions As C-MEX files3-56Examples of C MEX-File S-Function BlocksMost S-Function blocks require the handling of states, continuous or d

Page 4

Examples of C MEX-File S-Function Blocks3-57during which it calls mdlOutputs and mdlDerivatives. Each of these pairs ofcallsisreferredtoasanintegratio

Page 5

3 Writing S-Functions As C-MEX files3-58matlabroot/simulink/src/csfunc.c/* File : csfunc.c * Abstract: * * Example C-MEX S-function for defi

Page 6

Examples of C MEX-File S-Function Blocks3-59 return; /* Parameter mismatch will be reported by Simulink. */ } ssSetNumContStates(S, 2);

Page 7 - S-Functions

3 Writing S-Functions As C-MEX files3-60static void mdlOutputs(SimStruct *S, int_T tid){ real_T *y = ssGetOutputPortRealSignal(S,0);

Page 8

Examples of C MEX-File S-Function Blocks3-61Example - Discrete State S-FunctionThe matlabroot/simulink/src/dsfunc.c example shows how to model adiscre

Page 9

3 Writing S-Functions As C-MEX files3-62matlabroot/simulink/src/dsfunc.c/* File : dsfunc.c * Abstract: * * Example C MEX S-function for defi

Page 10 - 1 Overview of S-Functions

Examples of C MEX-File S-Function Blocks3-63 return; /* Parameter mismatch will be reported by Simulink */ } ssSetNumContStates(S, 0);

Page 11 - Introduction

3 Writing S-Functions As C-MEX files3-64/* Function: mdlOutputs ======================================================= * Abstract: * y = Cx + Du

Page 12

Examples of C MEX-File S-Function Blocks3-65Example - Hybrid System S-FunctionsThe S-function, matlabroot/simulink/src/mixedm.c,isanexampleofahybrid (

Page 13

Introduction1-5blocks with no states, x is an empty vector. In MEX-file S-functions, there aretwo separate state vectors for the continuous and discre

Page 14

3 Writing S-Functions As C-MEX files3-66matlabroot/simulink/src/mixedm.c/* File : mixedm.c * Abstract: * * An example C MEX S-function that

Page 15 - Dynamically Sized Inputs

Examples of C MEX-File S-Function Blocks3-67 /* Take care when specifying exception free code - see sfuntmpl.doc. */ ssSetOptions(S, SS_OPTION_E

Page 16

3 Writing S-Functions As C-MEX files3-68 real_T *xD = ssGetRealDiscStates(S); real_T *xC = ssGetContStates(S); /* xD=xC */ if (ssIsSampleH

Page 17 - that delays each

Examples of C MEX-File S-Function Blocks3-69during the simulation. In the transfer function used in this example, theparameters of the transfer functi

Page 18

3 Writing S-Functions As C-MEX files3-70matlabroot/simulink/src/vsfunc.c/* File : vsfunc.c * Abstract: * * Example C-file S-function for def

Page 19 - Sample S-Functions

Examples of C MEX-File S-Function Blocks3-71 ssSetNumSampleTimes(S, 1); ssSetNumRWork(S, 0); ssSetNumIWork(S, 0); ssSetNumPWork(S, 0);

Page 20

3 Writing S-Functions As C-MEX files3-72/* Function: mdlOutputs ======================================================= * Abstract: * y = x */sta

Page 21

Examples of C MEX-File S-Function Blocks3-73Example - Zero Crossing S-FunctionThe example S-function, sfun_zc_sat demonstrates how to implement asatur

Page 22

3 Writing S-Functions As C-MEX files3-74/*========================* * General Defines/macros * *========================*//* index to Upper Limit */#d

Page 23

Examples of C MEX-File S-Function Blocks3-75if ( ( numUpperLimit != 1 ) && ( numLowerLimit != 1 ) &&

Page 24

1 Overview of S-Functions1-6Figure 1-2: How Simulink Performs SimulationInitialize m odelAt termina tion perf ormany required tasks.Calculate time of

Page 25 - As M-Files

3 Writing S-Functions As C-MEX files3-76 /* * states */ ssSetNumContStates(S, 0); ssSetNumDiscStates(S, 0); /* * outputs *

Page 26

Examples of C MEX-File S-Function Blocks3-77/* * Modes and zero crossings: * If we have a variable step solver and this block has a continuous

Page 27

3 Writing S-Functions As C-MEX files3-78#define MDL_SET_WORK_WIDTHS#if defined(MDL_SET_WORK_WIDTHS) && defined(MATLAB_MEX_FILE)/* Function

Page 28

Examples of C MEX-File S-Function Blocks3-79 * and having a continuous sample time. Solvers work best on smooth problems. * In order for the solver

Page 29 - of theblock

3 Writing S-Functions As C-MEX files3-80 for (iOutput = 0; iOutput < numOutput; iOutput++) { if (*uPtrs[uIdx] >= *upperLimit)

Page 30

Examples of C MEX-File S-Function Blocks3-81 upperLimit += upperLimitInc; lowerLimit += lowerLimitInc; }

Page 31

3 Writing S-Functions As C-MEX files3-82#define MDL_ZERO_CROSSINGS#if defined(MDL_ZERO_CROSSINGS) && (defined(MATLAB_MEX_FILE) || defined(

Page 32

Examples of C MEX-File S-Function Blocks3-83static void mdlZeroCrossings(SimStruct *S){ int_T iOutput; int_T numOutput =

Page 33 - M-file S-function:

3 Writing S-Functions As C-MEX files3-84 }}#endif /* end mdlZeroCrossings *//* Function: mdlTerminate =============================================

Page 34

Examples of C MEX-File S-Function Blocks3-85matlabroot/simulink/src/stvctf.c/* * File : stvctf.c * Abstract: * Time Varying Continuous Transfer F

Page 35

Introduction1-7Simulink makes repeated calls to S-functions in your model. During thesecalls, Simulink calls S-function routines (also called methods)

Page 36

3 Writing S-Functions As C-MEX files3-86 */#define S_FUNCTION_NAME stvctf#define S_FUNCTION_LEVEL 2#include "simstruc.h"/* * Defines for ea

Page 37

Examples of C MEX-File S-Function Blocks3-87 "the numerator, nonempty and with first " &

Page 38

3 Writing S-Functions As C-MEX files3-88 * NumBank1Coeffs * DenBank1Co

Page 39

Examples of C MEX-File S-Function Blocks3-89 ssSetOffsetTime(S, 0, 0.0); /* * the second, discrete sample time, is user provided */ s

Page 40 - % End of mdlInitializeSizes

3 Writing S-Functions As C-MEX files3-90 } } /* * Normalize if this transfer function has direct feedthrough. */ for (i = 1; i

Page 41

Examples of C MEX-File S-Function Blocks3-91 /* * The continuous system is evaluated using a controllable state space * represe

Page 42

3 Writing S-Functions As C-MEX files3-92 if (den0 == 0.0) { den0 = mxGetPr(DEN(S))[0]; } /* * Grab the numerat

Page 43

Examples of C MEX-File S-Function Blocks3-93 * Normalize if this transfer function has direct feedthrough. */ num = ssGetRWork(

Page 44 - Passing Additional Parameters

3 Writing S-Functions As C-MEX files3-94 */ dx[0] = -den[1] * x[0] + *uPtrs[0]; for (i = 1; i < nContStates; i++) { dx[i] = x[i-1]

Page 45 - As C-MEX files

Function-Call Subsystems3-95Function-Call SubsystemsYou ca n create a triggered subsystem whose execution is determined by logicinternal to an S-funct

Page 46

1 Overview of S-Functions1-8calls the appropriate functions for each flag value. For a C MEX S-function,Simulink calls the S-function routines directl

Page 47

3 Writing S-Functions As C-MEX files3-96To configure an S-function to call a function-call subsystem:1 Specify which elements are to execute the funct

Page 48

The C MEX S-Function SimStruct3-97The C MEX S-Function SimStructThe file matlabroot/simulink/include/simstruc.h is a C language headerfile that define

Page 49

3 Writing S-Functions As C-MEX files3-98ssGetParentSS(S)This is typically not used in S-functions. It returns the parentSimStruct or NULL if the S is

Page 50

The C MEX S-Function SimStruct3-99ssSetOptions(S,options)Used in mdlInitializeSizes t o set any of the following options.These options must be joined

Page 51

3 Writing S-Functions As C-MEX files3-100ssSetOptions(S,options)(continued)SS_OPTION_ASYNCHRONOUS — This option applies onlyto S-functionsthat have 0

Page 52

The C MEX S-Function SimStruct3-101Table 3-6: Error Handling and Status SimStruct MacrosMacros DescriptionssSetErrorStatus(S,"string")For i

Page 53

3 Writing S-Functions As C-MEX files3-102Table 3-7: Input and Output Port Signal SimStruct MacrosMacro DescriptionssSetNumInputPorts(S,nInputPorts)Us

Page 54

The C MEX S-Function SimStruct3-103ssSetInputPortOffsetTime(S,inputPortIdx,offset)Used in mdlInitializeSizes (a fterssSetNumInputPorts)tospecifythesam

Page 55

3 Writing S-Functions As C-MEX files3-104ssSetInputPortReusable(S,inputPortIdx,value)Used in mdlInitializeSizes (afterssSetNumInputPorts) to specify w

Page 56

The C MEX S-Function SimStruct3-105ssSetInputPortReusable(S,inputPortIdx,value)(continued)Note that this is a suggestion and not a requirement forthe

Page 57 - Exception Free Code

Introduction1-9S-Function ConceptsUnderstanding these key concepts should enable you to build S-functionscorrectly:• Direct feedthrough• Dynamica lly

Page 58

3 Writing S-Functions As C-MEX files3-106ssSetOutputPortReusable(S,outputPortIdx,value)Used in mdlInitializeSizes (afterssSetNumOutputPorts) to specif

Page 59

The C MEX S-Function SimStruct3-107ssGetInputPortRealSignalPtrs(S,inputPortIdx)Canbeusedinanysimulationloop(seep.3-16)S-function routine to access an

Page 60

3 Writing S-Functions As C-MEX files3-108ssGetInputPortBufferDstPort(S,inputPortIdx)Can be used in any run-time (see p. 3-14) S-functionroutine to det

Page 61

The C MEX S-Function SimStruct3-109ssGetOutputPortOffsetTime(S,outputPortIdx)Canbeusedinanyroutine(exceptmdlInitializeSizes)to determine the offset ti

Page 62 - Edit menu

3 Writing S-Functions As C-MEX files3-110ssGetSFcnParam(S,index)Used in any routine to access a parameter entered by in theS-function block dialog box

Page 63 - Data View of S-Functions

The C MEX S-Function SimStruct3-111ssIsSampleHit(S,st_index,tid)Used in mdlOutputs or mdlUpdate when your S-function hasmultiple sample t imes to dete

Page 64

3 Writing S-Functions As C-MEX files3-112Table 3-10: State and Work Vector SimStruct MacrosMacro DescriptionssSetNumContStates(S,nContStates) Used in

Page 65 - *y++ = *u++; /* Incorrect */

The C MEX S-Function SimStruct3-113ssSetNumPWork(S,nPWork)Used in mdlInitializeSizes to specify the number of pointer(void *) work v ector elements as

Page 66

3 Writing S-Functions As C-MEX files3-114ssGetNumDiscStates(S)Canbeusedinanyroutine(exceptmdlInitializeSizes)todetermine the number of discrete states

Page 67 - Parameter Changes

The C MEX S-Function SimStruct3-115ssGetPWork(S)Can be used in the simulation loop, mdlInitializeConditions,ormdlStart routines to get the pointer (vo

Page 68

1 Overview of S-Functions1-10width can also be used to determine the number of continuous states, thenumber of discrete states, and the number of outp

Page 69

3 Writing S-Functions As C-MEX files3-116Table 3-11: Simulation Information SimStruct MacrosMacro DescriptionssGetT(S)Used in mdlOutputs and mdlUpdat

Page 70

The C MEX S-Function SimStruct3-117Table 3-12: Function-Call SimStruct MacrosMacro DescriptionssSetCallSystemOutput(S,index)Used in mdlInitializeSamp

Page 71

3 Writing S-Functions As C-MEX files3-118Converting Level 1 C MEX S-Functions to Level 2Level 2 S-functions were introduced with Simulink 2.2. Level 1

Page 72

Converting Level 1 C MEX S-Functions to Level 23-119• If your S -function has a nonempty mdlInitializeConditions, then updateit to the following form#

Page 73

3 Writing S-Functions As C-MEX files3-120• If your S-function has a nonempty mdlUpdate, then update it to this form:#define MDL_UPDATEstatic void mdlU

Page 74 - The synopsis is

Converting Level 1 C MEX S-Functions to Level 23-121Table 3-13: Obsolete SimStruct MacrosObsolete Macro Replace WithssGetU(S), ssGetUPtrs(S) ssGetInp

Page 75

3 Writing S-Functions As C-MEX files3-122ssGetNumOutputs ssGetNumOutputPorts(S) andssGetOutputPortWidth(S,port)ssSetNumOutputs ssSetNumOutputPorts(S,n

Page 76 - Masked Multiport S-Functions

4Guidelines for WritingC MEX S-FunctionsIntroduction ...4-2Classes of Problems Solved by S-Functions . . . . . . . . 4-2TypesofS-Func

Page 77

4 Guidelines for Writing C MEX S-Functions4-2IntroductionThis chapter describes how to create S-functions that work seamlessly withboth Simulink and t

Page 78

Introduction4-3environment with a great deal of flexibility. This flexibility cannot always bemaintained when you use S-functions with the Real-Time W

Page 79

Introduction1-11• Continuous sample time — For S -functions that have continuous states and/ornonsampled zerocrossings.Fort his typeof S-function,theo

Page 80 - Block-based Sample Times

4 Guidelines for Writing C MEX S-Functions4-4The MathWorks has a dopted terminology for these different requirements.Respectively, the situations desc

Page 81

Introduction4-5Fully Inlined S-FunctionsA fully inlined S-function builds your algorithm (block) into Simulink and theReal-Time Workshop in a manner t

Page 82

4 Guidelines for Writing C MEX S-Functions4-6files),it embedssomeo f thisoverhead code inthe generatedC code.Ifyou wantto optimize your real-time code

Page 83 - Port-based Sample Times

Noninlined S-Functions4-7Noninlined S-FunctionsNoninlined S-functions are identified by the absence of an sfunction.tlc fileforyourS-function(sfunctio

Page 84

4 Guidelines for Writing C MEX S-Functions4-8Writing Wrapper S-FunctionsThis section describes how to create S-functions that work seaml essly withSim

Page 85

Writing Wrapper S-Functions4-9Wrapper S-functions are useful when creating new algorithms that areprocedural in nature or when integrating legacy code

Page 86 - Multirate S-Function Blocks

4 Guidelines for Writing C MEX S-Functions4-10This figure i llustrates the wrapper S-function concept:Figure 4-1: How S-Functions Interface with Hand

Page 87 - Configuring Work Vectors

Writing Wrapper S-Functions4-11Using an S-function wrapper to import algorithms in your Simulink modelmeans that the S-function serves as an interface

Page 88

4 Guidelines for Writing C MEX S-Functions4-12/* * mdlInitializeSampleTimes - indicate that this S-function runs*at the rate of the source (driving bl

Page 89

Writing Wrapper S-Functions4-13The TLC S-Function WrapperThis section describes how to inline the call to my_alg in the MdlOutputssection of the gener

Page 90

1 Overview of S-Functions1-12S-functions can be either single or multirate; a multirate S-function hasmultiple sample times.Sample times are specified

Page 91 - Memory Allocation

4 Guidelines for Writing C MEX S-Functions4-14 /* Level2 S-Function Block: <Root>/S-Function (wrapsfcn) */ { SimStruct *rts = ssGetSFunction

Page 92 - S-Function Initialization

Writing Wrapper S-Functions4-15to your C algorithm (my_alg), you can elim inate bo th the SimStruct and theextra function call, thereby improving the

Page 93

4 Guidelines for Writing C MEX S-Functions4-16placing calls toyourS-function in the generatedcode. This is the wrapsfcn.tlcfile that inlines wrapsfcn.

Page 94

Writing Wrapper S-Functions4-17The final step is the actual inlining of the call to the function my_alg.Thisisdone by theOutputs function. In this fun

Page 95

4 Guidelines for Writing C MEX S-Functions4-18Fully Inlined S-FunctionsContinuing the example of the previous section, you could eliminate the ca ll t

Page 96

Fully Inlined S-Functions4-19thatcontains multiple ports.You may findthat lookingat this example willaidin the understanding of fully inlined TLC file

Page 97

4 Guidelines for Writing C MEX S-Functions4-20Fully Inlined S-Function with the mdlRTW RoutineYou can make a more fully inlined S-function that uses t

Page 98

Fully Inlined S-Function with the mdlRTW Routine4-21• How to use the mdlRTW routine to customize the Real-Time Workshopgenerated code to produce the o

Page 99

4 Guidelines for Writing C MEX S-Functions4-22The following graph illustrates how the parameters XData=[1:6],YData=[1,2,7,4,5,9] are handled. For exam

Page 100

Fully Inlined S-Function with the mdlRTW Routine4-23index in the XData for the current x input value when the XData is unevenlyspaced. TheGetDirectLoo

Page 101

Introduction1-13• A discrete S-function that changes at a specified ra te should register thediscrete sample time pair,[discrete_sample_time_period, o

Page 102

4 Guidelines for Writing C MEX S-Functions4-24mxGetPr MATLAB API function. This results in a slight increase inperformance.mdlRTW UsageThe Real-Time W

Page 103 - S, 0, 0.0);

Fully Inlined S-Function with the mdlRTW Routine4-25When creating this model, you need to specify the following for each S-functionblock:set_param(‘sf

Page 104

4 Guidelines for Writing C MEX S-Functions4-26 rtY.Out1 = rtb_buffer2; /* S-Function Block: <Root>/S-Function1 */ { real_T *xData = &r

Page 105

Fully Inlined S-Function with the mdlRTW Routine4-27matlabroot/simulink/src/sfun_directlook.c/* * File : sfun_directlook.c * Abstract: * * Di

Page 106

4 Guidelines for Writing C MEX S-Functions4-28/*==============* * misc defines * *==============*/#if !defined(TRUE)#define TRUE 1#endif#if !defined(

Page 107

Fully Inlined S-Function with the mdlRTW Routine4-29 } return(TRUE); } else { return(FALSE); }}/* end IsRealVect

Page 108

4 Guidelines for Writing C MEX S-Functions4-30 /* * Verify we have a valid XDataEvenlySpaced parameter. */ if (!mxIsNumeric(XDATAEVENLYS

Page 109

Fully Inlined S-Function with the mdlRTW Routine4-31 } else { /* XData is ‘unevenly-spaced’ */ for (i = 1; i < numEl; i++) {

Page 110

4 Guidelines for Writing C MEX S-Functions4-32 ssSetInputPortOverWritable(S, 0, TRUE); if (!ssSetNumOutputPorts(S, 1)) return; ssSetOutputPor

Page 111 - S, 1, 0.0);

Fully Inlined S-Function with the mdlRTW Routine4-33 cache->evenlySpaced = FALSE; }}#endif /* MDL_START *//* Function: mdlOutputs ======

Page 112

How to Contact The MathWorks:508-647-7000 Phone508-647-7001 FaxThe MathWorks, Inc. Mail24 Prime Park WayNatick, MA 01760-1500http://www.mathworks.com

Page 113

1 Overview of S-Functions1-14The simulink/blocks directory contains many M-file S-functions. Considerstarting off by looking at these files.Table 1-2:

Page 114

4 Guidelines for Writing C MEX S-Functions4-34} /* end mdlOutputs *//* Function: mdlTerminate ====================================================== *

Page 115

Fully Inlined S-Function with the mdlRTW Routine4-35 boolean_T even = (mxGetScalar(XDATAEVENLYSPACED(S)) != 0.0); if (!ssWriteRTWParamSe

Page 116

4 Guidelines for Writing C MEX S-Functions4-36matlabroot/simulink/src/lookup_index.c/* File : lookup_index.c * Abstract: * * Contains a routine

Page 117

Fully Inlined S-Function with the mdlRTW Routine4-37 */ for (;;) { idx = (bottom + top)/2; if (u < x[idx]) { top =

Page 118

4 Guidelines for Writing C MEX S-Functions4-38matlabroot/toolbox/simulink/blocks/sfun_directlook.tlc%% File : sfun_directlook.tlc%% Abstract: %%

Page 119

Fully Inlined S-Function with the mdlRTW Routine4-39%function Outputs(block, system) Output /* %<Type> Block: %<Name> */ { %assign

Page 120

4 Guidelines for Writing C MEX S-Functions4-40 %endif %endroll %endif }%endfunction%% EOF: sfun_directlook.tlc

Page 121 - S, 0, 0);

I-1IndexAadditional pa rameters for S-functions 2-20Bblock width 3-33block-based sample times 3-36CC MEX S-function routines 3-3C MEX S-functions 1-2,

Page 122

IndexI-2mdlSetOutputPortSampleTime 3-34, 3-41mdlSetOutputPortWidth function 3-35mdlSetWorkWidths 3-46mdlStart 3-48mdlUpdate 3-42, 3-51memory and work

Page 123

IndexI-3error handling and status 3-101function call 3-117general 3-97input a nd output port signal 3-102parameter 3-109sample time 3-110simulation in

Page 124

Introduction1-15The simulink/src directoryalsocontainsexamplesofCMEXS-functions,many of which have an M-file S-function counterpart. These C MEXS-func

Page 125

IndexI-4ssSetNumSampleTimes 3-110ssSetNumSFcnParams 3-109ssSetOffsetTime 3-110ssSetOptions 3-99ssSetOutputPortOffsetTime 3-105ssSetOutputPortReusable

Page 126

1 Overview of S-Functions1-16mixedmex.cImplements a hybrid dynamical system with asingle output and two inputs.quantize.cAn example MEX-file for a vec

Page 127

Introduction1-17simomex.cImplements a single output, two input state-spacedynamical system described by these state-spaceequationsdx/dt = Ax + Buy = C

Page 128 - Function

1 Overview of S-Functions1-18

Page 129

2Writing S-FunctionsAs M-FilesIntroduction ...2-2Defining S-Function Block Characteristics . . . . . . . . 2-3ASimpleM-FileS-Function

Page 130

2 Writing S-Functions As M-Files2-2IntroductionAn M-file that definesan S-Function blockmust provide informationabout themodel; Simulink needs this in

Page 131

Introduction2-3Building S-functions can be thought of as two separate tasks:• Initializingblockcharacteristics,includingnumber ofinputs,outputs,initia

Page 132

2 Writing S-Functions As M-Files2-4A Simple M-File S-Function ExampleThe easiest way to understand how S-functions work is to look at a simpleexample.

Page 133

Introduction2-5The first four input arguments, which Simul ink passes to the S-function,mustbe the variablest, x, u,andflag:• t, the time•x, the state

Page 134

iContents1Overview of S-F unctionsIntroduction ... 1-2WhatIsanS-Function?... 1-2Whe

Page 135

2 Writing S-Functions As M-Files2-6Below are the S-function subroutines that timestwo.m calls:%=======================================================

Page 136

Introduction2-7To test this S-function in Simulink, connect a sine wave generator t o the inputof an S-Function block. Connect the output of the S-Fun

Page 137

2 Writing S-Functions As M-Files2-8Examples of M-File S-FunctionsThe simple example discussed above (timestwo) has no states. MostS-Function blocks re

Page 138

Examples of M-File S-Functions2-9Example - Continuous State S-FunctionSimulink includes a function called csfunc.m, which is an example of acontinuous

Page 139 - Function-Call Subsystems

2 Writing S-Functions As M-Files2-10%==============================================================% mdlInitializeSizes% Return the sizes, initial con

Page 140 - * call on 1st element */

Examples of M-File S-Functions2-11% End of mdlDerivatives.%%==============================================================% mdlOutputs% Return the blo

Page 141

2 Writing S-Functions As M-Files2-12function [sys,x0,str,ts] = dsfunc(t,x,u,flag)% An example M-file S-function for defining a discrete system.% This

Page 142

Examples of M-File S-Functions2-13% Call simsizes for a sizes structure, fill it in, and convert it % to a sizes array.sizes = simsizes;sizes.NumContS

Page 143

2 Writing S-Functions As M-Files2-14Example - Hybrid System S-FunctionsSimulink includes a function called mixedm.m, which is an example of a hybridsy

Page 144

Examples of M-File S-Functions2-15Here is the code for the M-file S-function:function [sys,x0,str,ts] = mixedm(t,x,u,flag)% A hybrid system example th

Page 145

ii Contents3Writing S-Functions As C-MEX filesIntroduction ... 3-2Writing Basic C M EX S-Functions ...

Page 146

2 Writing S-Functions As M-Files2-16sizes.NumOutputs = 1;sizes.NumInputs = 1;sizes.DirFeedthrough = 0;sizes.NumSampleTimes = 2;sys = simsizes

Page 147 - (S,inputPortIdx,offset)

Examples of M-File S-Functions2-17% End of mdlUpdate.%%==============================================================% mdlOutputs% Return the output v

Page 148

2 Writing S-Functions As M-Files2-18function [sys,x0,str,ts] = vsfunc(t,x,u,flag)% This example S-function illustrates how to create a variable % step

Page 149 - (S,outputPortIdx,offset)

Examples of M-File S-Functions2-19sizes = simsizes;sizes.NumContStates = 0;sizes.NumDiscStates = 1;sizes.NumOutputs = 1;sizes.NumInputs = 2

Page 150

2 Writing S-Functions As M-Files2-20function sys = mdlOutputs(t,x,u)sys = x(1);% end mdlOutputs%%=====================================================

Page 151 - (S,inputPortIdx)

3Writing S-FunctionsAs C-MEX filesIntroduction ...3-2Writing Basic C MEX S-Functions ...3-4Creating More Comp lex C MEX S-Func

Page 152

3 Writing S-Functions As C-MEX files3-2IntroductionA C MEX-file that definesan S-Function block must provide information aboutthe model to Simulink du

Page 153 - time of an output port. This

Introduction3-3contents. After Simulink calls mdlInitializeSizes, i t t hen interacts with theS-function through various other routines (all starting

Page 154 - (S,st_index,value)

3 Writing S-Functions As C-MEX files3-4Writing Basic C MEX S-FunctionsThis secti on d iscusses bas ic C MEX S-f unctions, where basic means anS-functi

Page 155

Writing Basic C MEX S-Functions3-5To incorporate this S-function into Simulink, create a source f ile calledtimestwo.c and place the S-function routin

Page 156

iiiFunction-Call Subsystems ... 3-95The C MEX S-Function SimStruct ... 3-97Converting Level 1 C MEX S-Funct

Page 157

3 Writing S-Functions As C-MEX files3-6mdlOutputsCalculation of outputs. For our timestwoS-function, mdlOutputs takes the input,multiplies it by two,

Page 158

Writing Basic C MEX S-Functions3-7The contents of timestwo.c are shown below.#define S_FUNCTION_NAME timestwo#define S_FUNCTION_LEVEL 2#include “sims

Page 159

3 Writing S-Functions As C-MEX files3-8There is more information that the timestwo.c example requires:• Defines and includes — The example specifies t

Page 160

Writing Basic C MEX S-Functions3-9• mdlOutput:- The numerical calculation.mdlOutputs tells S imulink to multiply theinput signal by 2.0 and place the

Page 161

3 Writing S-Functions As C-MEX files3-10Creating More Complex C MEX S-FunctionsThere are numerous S-function routines available for use in C MEXS-func

Page 162

Creating More Complex C MEX S-Functions3-11The following headers are included by matlabroot/simulink/include/simstruc.hwhen compiling as a MEX-file.Wh

Page 163

3 Writing S-Functions As C-MEX files3-12• simulink.c is included if the file is being compiled int o a MEX-file.•cg_sfun.h is included if the file is

Page 164

Creating More Complex C MEX S-Functions3-13Note that the second argument to ssSetErrorStatus must be persistentmemory. It cannot be a local variable i

Page 165

3 Writing S-Functions As C-MEX files3-14your S-function generates an exception when this option is set, unpredictableresults will occur.Allmex* routin

Page 166

Overview of the C MEX S-Function Routines3-15Overview of the C MEX S-Function RoutinesThe following figure shows the calling structure, including opti

Page 168

3 Writing S-Functions As C-MEX files3-16Figure 3-1: The Calling Sequence for S-FunctionsInitializationmdlSetInputPortWidth/mdlSetOutputPortWidthmdlIn

Page 169 - Types of S-Functions

Overview of the C MEX S-Function Routines3-17The following sections discuss each of these routines and give an overview ofthemorecommonmacrosusedtoacc

Page 170 - Wrapper S-Functions

3 Writing S-Functions As C-MEX files3-18Alternate Calling Structure for External ModeWhen running Simulink in external mode, the calling sequence for

Page 171 - Fully Inlined S-Functions

Overview of the C MEX S-Function Routines3-19Data View of S-FunctionsS-function blocks have input and output signals, parameters, internal states,plus

Page 172

3 Writing S-Functions As C-MEX files3-20The length of the various signals and vectors is configured in themdlInitializeSizes routine. The signals as w

Page 173

Overview of the C MEX S-Function Routines3-21Accessing Input Signals of Individual PortsThis section describes how to access all input signals of a pa

Page 174 - Writing Wrapper S-Functions

3 Writing S-Functions As C-MEX files3-22entering your S-function. Then the driving source should be connected to eachinputportasshowninthisfigure:Chec

Page 175

Overview of the C MEX S-Function Routines3-23and NUM_OF_CHANNELS_PRM. The code uses #define statements to associateparticular input arguments with the

Page 176

3 Writing S-Functions As C-MEX files3-24Typically, it is safe to have an mdlCheckParameters in your S-function when itis used with the Real-Time Works

Page 177

Overview of the C MEX S-Function Routines3-25Note You cannot access the w ork, state, input, output, and other vectors inthis routine. Use this rou t

Page 178

1Overview ofS-FunctionsIntroduction ...1-2WhatIsanS-Function?...1-2WhentoUseanS-Function ...1-4HowS-Functions

Page 179 - The TLC S-Function Wrapper

3 Writing S-Functions As C-MEX files3-26mdlProcessParametersmdlProcessParameters is an optiona l routine that Simulink calls aftermdlCheckParameters c

Page 180 - How to Inline

Overview of the C MEX S-Function Routines3-27Example: mdlProcessParameters. This example processes a string parameter thatmdlCheckParameters has verif

Page 181

3 Writing S-Functions As C-MEX files3-28mdlInitializeSizes function. Supplied ma cros set values for the structurefields. If a value is not specified,

Page 182

Overview of the C MEX S-Function Routines3-29simulation(or theReal-TimeWorkshopexternalmode)ifan attempt ismadeto change the parameter.• If your S- fu

Page 183 - The Inlined Code

3 Writing S-Functions As C-MEX files3-30The synopsis is/* Function: mdlInitializeSizes ===============================================* Abstract:*

Page 184

Overview of the C MEX S-Function Routines3-31 * of the output port which can be DYNAMICALLY_SIZE or greater than zero. */ if (!ssSetNumOutp

Page 185

3 Writing S-Functions As C-MEX files3-32 * the size specified by the port which is usually referred to as * the block width. * * S

Page 186

Overview of the C MEX S-Function Routines3-33either 1 or N.YoucanusessGetInputPortWidth in the routines called duringthe simulation loop to determine

Page 187

3 Writing S-Functions As C-MEX files3-34When inherited port based sample times are specified, the sample time will beone of the following:• continuous

Page 188

Overview of the C MEX S-Function Routines3-35This is the code synopsis for mdSetOutputPortSampleTime:#if defined(MDL_SET_OUTPUT_PORT_SAMPLE_TIME) &

Page 189 - User Data Caching

1 Overview of S-Functions1-2IntroductionS-functions (system-functions) provide a powerful mechanism for extendingthecapabilitiesofSimulink®.Theintrodu

Page 190 - Example Model

3 Writing S-Functions As C-MEX files3-36Setting Sample Times for C MEX S-FunctionsSimulink supports blocks that execute at different rates. There are

Page 191

Overview of the C MEX S-Function Routines3-37Specifying the Number of Sample Times in mdlInitializeSizes. To configure yourS-function block for block-

Page 192 - S-function block i n the

3 Writing S-Functions As C-MEX files3-38Alternatively, you can specify that the sample time is in herited from thedriving block in which case the S-fu

Page 193

Overview of the C MEX S-Function Routines3-39To check for a sample hit during execution (in mdlOutputs or mdlUpdate), usethessIsSampleHit or ssIsConti

Page 194

3 Writing S-Functions As C-MEX files3-40Specifying the Number of Sample Times in mdlInitializeSizes. To specify port-basedsample times, usessSetNumSam

Page 195

Overview of the C MEX S-Function Routines3-41Constant, triggered, and variable step sample times will not be propagated toS-functions with port based

Page 196

3 Writing S-Functions As C-MEX files3-42Multirate S-Function BlocksIna multirate S-Function block, you canencapsulate the code that defines eachbehavi

Page 197

Overview of the C MEX S-Function Routines3-43Example - Defining a Sample Time for a Hybrid Block. This examp le defines sampletimes for a hybrid S-Fun

Page 198

3 Writing S-Functions As C-MEX files3-44Work vectors have several advantages:• Instance specific storage for block variables• Integer, real, pointer,

Page 199

Overview of the C MEX S-Function Routines3-45Specify vector widths in mdlInitializeSizes. There are three choices:• 0 (the default). This indicates th

Page 200

Introduction1-3Figure 1-1: The Relationship Between an S-Function Block, Its Dialog Box,and the Source File That Defines the Block’s BehaviorIn this

Page 201

3 Writing S-Functions As C-MEX files3-46the mdlZeroCrossings routine to return the nonsampled zero crossings. Seematlabroot/simulink/src/sfun_zc.c for

Page 202

Overview of the C MEX S-Function Routines3-47This code retrieves the FILE pointer from the pointer-work vector and passes ittofclose to close the file

Page 203

3 Writing S-Functions As C-MEX files3-48routines. In mdlStart allocate and initialize the memory and place the pointerto it either in pointer-work vec

Page 204

Overview of the C MEX S-Function Routines3-49Simulink will call this routine in two places:• At the start of simulation• If it is present in an enable

Page 205

3 Writing S-Functions As C-MEX files3-50S-Function Routines Called During SimulationConceptually, the way Simulink performs a simulation is that it ex

Page 206

Overview of the C MEX S-Function Routines3-51For an example of an mdlOutputs routine that works with mult iple input andoutput ports, seematlabroot/si

Page 207

3 Writing S-Functions As C-MEX files3-52last call to this routine. The memory allocated to the derivative vector changesduring execution.The synopsis

Page 208

Overview of the C MEX S-Function Routines3-53mdlTerminateIn the mdlTerminate routine, perform any actions that are necessary at thetermination of a si

Page 209

3 Writing S-Functions As C-MEX files3-54The parameter can also be a variable as inmodules = 'sfun_module1 sfun_module2'set_param(sfun_block,

Page 210

Overview of the C MEX S-Function Routines3-55routineoryourS-functionhas a“simulationmode”and a “real-timemode”suchas a hardware I/O S-function that si

Commentaires sur ces manuels

Pas de commentaire