MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS Podręcznik Użytkownika

Przeglądaj online lub pobierz Podręcznik Użytkownika dla Oprogramowanie MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS. MATLAB SIMULINK 7 - DEVELOPING S-FUNCTIONS User`s guide Instrukcja obsługi

  • Pobierz
  • Dodaj do moich podręczników
  • Drukuj
  • Strona
    / 210
  • Spis treści
  • BOOKMARKI
  • Oceniono. / 5. Na podstawie oceny klientów

Podsumowanie treści

Strona 1 - Writing S-Functions

ModelingSimulationImplementationWriting S-FunctionsVersion 3

Strona 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

Strona 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

Strona 4

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

Strona 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

Strona 6

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

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

Strona 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

Strona 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

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

Strona 11 - Introduction

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

Strona 12

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

Strona 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

Strona 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

Strona 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

Strona 16

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

Strona 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

Strona 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

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

Strona 20

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

Strona 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

Strona 22

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

Strona 23

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

Strona 24

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

Strona 25 - As M-Files

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

Strona 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

Strona 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

Strona 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

Strona 29 - of theblock

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

Strona 30

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

Strona 31

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

Strona 32

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

Strona 33 - M-file S-function:

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

Strona 34

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

Strona 35

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

Strona 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

Strona 37

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

Strona 38

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

Strona 39

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

Strona 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

Strona 41

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

Strona 42

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

Strona 43

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

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 51

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

Strona 52

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

Strona 53

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

Strona 54

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

Strona 55

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

Strona 56

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

Strona 57 - Exception Free Code

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

Strona 58

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

Strona 59

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

Strona 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

Strona 61

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

Strona 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

Strona 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

Strona 64

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

Strona 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

Strona 66

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

Strona 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

Strona 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

Strona 69

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

Strona 70

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

Strona 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

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

Strona 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

Strona 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

Strona 75

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

Strona 76 - Masked Multiport S-Functions

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

Strona 77

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

Strona 78

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

Strona 79

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

Strona 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

Strona 81

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

Strona 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

Strona 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

Strona 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

Strona 85

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 91 - Memory Allocation

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

Strona 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

Strona 93

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

Strona 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

Strona 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

Strona 96

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 104

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

Strona 105

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

Strona 106

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

Strona 107

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

Strona 108

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

Strona 109

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

Strona 110

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

Strona 111 - S, 1, 0.0);

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

Strona 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

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

Strona 114

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

Strona 115

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

Strona 116

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

Strona 117

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

Strona 118

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

Strona 119

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

Strona 120

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

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

Strona 122

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

Strona 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

Strona 124

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

Strona 125

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

Strona 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

Strona 127

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

Strona 128 - Function

1 Overview of S-Functions1-18

Strona 129

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

Strona 130

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

Strona 131

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

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

Strona 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

Strona 134

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

Strona 135

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

Strona 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

Strona 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

Strona 138

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

Strona 139 - Function-Call Subsystems

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

Strona 140 - * call on 1st element */

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 145

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

Strona 146

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

Strona 147 - (S,inputPortIdx,offset)

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

Strona 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

Strona 149 - (S,outputPortIdx,offset)

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

Strona 150

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 156

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

Strona 157

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 168

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 178

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

Strona 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

Strona 180 - How to Inline

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

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

Strona 182

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

Strona 183 - The Inlined Code

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

Strona 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

Strona 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

Strona 186

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

Strona 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

Strona 188

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

Strona 189 - User Data Caching

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

Strona 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

Strona 191

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

Strona 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

Strona 193

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

Strona 194

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

Strona 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

Strona 196

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

Strona 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

Strona 198

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

Strona 199

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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 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

Strona 208

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

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

Strona 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

Komentarze do niniejszej Instrukcji

Brak uwag