MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS Betriebsanweisung

Stöbern Sie online oder laden Sie Betriebsanweisung nach Software MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS herunter. MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS User`s guide Benutzerhandbuch

  • Herunterladen
  • Zu meinen Handbüchern hinzufügen
  • Drucken
  • Seite
    / 210
  • Inhaltsverzeichnis
  • LESEZEICHEN
  • Bewertet. / 5. Basierend auf Kundenbewertungen

Inhaltsverzeichnis

Seite 1 - Writing S-Functions

ModelingSimulationImplementationWriting S-FunctionsVersion 3

Seite 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

Seite 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

Seite 4

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

Seite 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

Seite 6

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

Seite 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);

Seite 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

Seite 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

Seite 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);

Seite 11 - Introduction

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

Seite 12

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

Seite 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

Seite 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

Seite 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

Seite 16

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

Seite 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

Seite 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

Seite 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);

Seite 20

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

Seite 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

Seite 22

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

Seite 23

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

Seite 24

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

Seite 25 - As M-Files

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

Seite 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

Seite 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

Seite 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

Seite 29 - of theblock

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

Seite 30

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

Seite 31

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

Seite 32

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

Seite 33 - M-file S-function:

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

Seite 34

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

Seite 35

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

Seite 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

Seite 37

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

Seite 38

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

Seite 39

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

Seite 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

Seite 41

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

Seite 42

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

Seite 43

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

Seite 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]

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 51

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

Seite 52

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

Seite 53

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

Seite 54

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

Seite 55

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

Seite 56

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

Seite 57 - Exception Free Code

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

Seite 58

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

Seite 59

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

Seite 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

Seite 61

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

Seite 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

Seite 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

Seite 64

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

Seite 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

Seite 66

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

Seite 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

Seite 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

Seite 69

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

Seite 70

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

Seite 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

Seite 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#

Seite 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

Seite 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

Seite 75

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

Seite 76 - Masked Multiport S-Functions

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

Seite 77

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

Seite 78

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

Seite 79

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

Seite 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

Seite 81

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

Seite 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

Seite 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

Seite 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

Seite 85

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 91 - Memory Allocation

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

Seite 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

Seite 93

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

Seite 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

Seite 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

Seite 96

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 104

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

Seite 105

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

Seite 106

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

Seite 107

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

Seite 108

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

Seite 109

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

Seite 110

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

Seite 111 - S, 1, 0.0);

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

Seite 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

Seite 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:

Seite 114

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

Seite 115

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

Seite 116

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

Seite 117

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

Seite 118

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

Seite 119

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

Seite 120

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

Seite 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,

Seite 122

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

Seite 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

Seite 124

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

Seite 125

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

Seite 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

Seite 127

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

Seite 128 - Function

1 Overview of S-Functions1-18

Seite 129

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

Seite 130

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

Seite 131

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

Seite 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.

Seite 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

Seite 134

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

Seite 135

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

Seite 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

Seite 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

Seite 138

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

Seite 139 - Function-Call Subsystems

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

Seite 140 - * call on 1st element */

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 145

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

Seite 146

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

Seite 147 - (S,inputPortIdx,offset)

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

Seite 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

Seite 149 - (S,outputPortIdx,offset)

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

Seite 150

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 156

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

Seite 157

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 168

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 178

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

Seite 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

Seite 180 - How to Inline

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

Seite 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,

Seite 182

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

Seite 183 - The Inlined Code

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

Seite 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

Seite 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

Seite 186

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

Seite 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

Seite 188

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

Seite 189 - User Data Caching

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

Seite 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

Seite 191

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

Seite 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

Seite 193

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

Seite 194

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

Seite 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

Seite 196

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

Seite 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

Seite 198

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

Seite 199

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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 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

Seite 208

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

Seite 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,

Seite 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

Kommentare zu diesen Handbüchern

Keine Kommentare