Skript : Kap 7, 29.6.2016

F7.1
S‐Function ‐ System‐Function
Ziel: Ersetze Subsystem durch einen Block, der MATLAB‐ oder C‐Code enthält
t
A(t)
h(t)
AS
h( t)  h1


t  t0
 ( AFS  AS) h1  h( t) , t 0  t  t 0  DT
A ( t)   AS 
DT

AFS
t  t 0  DT

1
S‐Function – System‐Function
F7.2
1
2
3
4
5
6
7
8
9
10
S‐Function
S‐Function ‐ Einfache Beispiele
Callback‐Funktionen und Datenstrukturen
S‐Function – Fallschirmsprung ‐ Versuch
S‐Function mit 2 Ausgängen
Zur Mathematik von Simulink‐Blöcken
S‐Functions im Detail – Unit‐Delay und msfuntmpl.m
S‐Functions in C
S‐Function Builder
Aufgaben
2
1 S‐Function
F7.3
Eine S‐Function oder System‐Function ist ein Programm, das einem speziellen Block in einem Simulink‐Modell zugewiesen wird. Bei der Durchführung der Simu‐
lation wird das Programm von der Simulink‐Engine aufgerufen und ausgeführt.
• Nur ganz speziellen Blöcken kann eine S‐Function zugewiesen werden. • Damit Simulink eine S‐Function nutzen kann, muss diese bestimmte Eigenschaf‐
ten besitzen – sogenannte Callback‐Funktionen implementieren. Callback‐Funktionen Ein Satz von Funktionen mit vorgegebenen Namen und Parametern, um eine ganz bestimmte Aufgabe zu lösen. Diese Funktionen müssen vorhanden sein und werden von einem anderen System (hier : Simulink‐Engine) verwendet. Es kann auch optionale Funktionen geben. Falls diese dann nicht vorhanden sind, wird ein Defaultverhalten angewendet.
Block‐A
S‐Function
Block
MATLAB‐Code
C‐Code
Fortran C++
Block‐B
3
F7.4
2 S‐Function ‐ Einfache Beispiele
function mal2M(block)
setup(block);
% setup muss explicit aufgerufen werden
%endfunction
function setup(block)
%% Register number of input and output ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
. . .
%% Register methods
block.RegBlockMethod('Outputs', @Output);
%endfunction
"Ausgangssignal = factor*Eingangssignal"
function Output(block)
block.OutputPort(1).Data = 2*block.InputPort(1).Data;
%endfunction
4
F7.5
2 S‐Function ‐ Einfache Beispiele
5
F7.6
2 S‐Function ‐ Einfache Beispiele
function mal2M(block)
setup(block);
% setup muss explicit aufgerufen werden
%endfunction
Kap7 2Beispiele/mal2M.m
function setup(block)
%% Register number of input and output ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
%% Setup functional port properties to dynamically inherited.
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.InputPort(1).DirectFeedthrough = true;
%% Set block sample time to inherited
block.SampleTimes = [-1 0];
%% Set the block simStateCompliance to default (built-in block)
block.SimStateCompliance = 'DefaultSimState';
%% Run accelerator on TLC
Function Handle zuweisen
block.SetAccelRunOnTLC(true);
Callback‐Funktion Outputs
%% Register methods
block.RegBlockMethod('Outputs',@Output); führt Funktion Output aus
%endfunction
function Output(block)
block.OutputPort(1).Data = 2*block.InputPort(1).Data;
%endfunction
"Ausgangssignal = factor*Eingangssignal"
6
F7.7
2 S‐Function ‐ Einfache Beispiele
Beispiel : In der Zeit 0<=t<5 soll die Eingangsgröße um den Faktor 2 verstärkt
werden , danach um den Faktor 4.
function Output(block)
if block.CurrentTime < 5
factor = 2;
else
factor = 4;
"Ausgangssignal = factor*Eingangssignal"
end
block.OutputPort(1).Data = factor*block.InputPort(1).Data;
%endfunction
7
F7.8
3 Callback‐Funktionen und Datenstrukturen
Callback Methods for Level‐2 MATLAB S‐Functions
Required Callback Methods
Level‐2 MATLAB S‐functions must implement the following callback methods:
• Setup
Specifies the sizes of various parameters in the SimStruct (S‐Function in C) or Simulink.MSFcnRunTimeBlock (S‐Function in MATLAB) , such as the number of output ports for the block.
• Outputs
Calculates the output of the block.
• Terminate
Performs any actions required at the termination of the simulation. If no actions are required, this function can be implemented as a stub.
Diese Callback‐Methoden (Funktionen) besitzen einen Parameter ‐ ein Objekt vom Typ
Simulink.MSFcnRunTimeBlock, das von Simulink.RunTimeBlock abgeleitet ist.
This (MSFcnRunTimeBlock ‐ SimStruct) class allows a Level‐2 MATLAB S‐function or other MATLAB program to obtain information from Simulink software and provide information to Simulink software about a Level‐2 MATLAB S‐Function block. Simulink software creates an instance of this class for each Level‐2 MATLAB S‐Function block in a model. Simulink software passes the object to the callback methods of Level‐2 MATLAB S‐functions when it updates or simulates a model, allowing the callback methods to get and provide block‐related information to Simulink software.
8
F7.9
4 S‐Function – Fallschirmsprung ‐ Versuch
Aufgabe: Ersetze im Simulink‐Modell fallschirmMSource.slx (Kap7 4FallSchirm) den Subsystem Block durch einen Level‐2 MATLAB S‐Function Block. Die Fläche des Fallschirms soll nach dem Öffnen linear anwachsen. Die benötigten Werte für h1, AS, AFS und DT werden aus dem Model‐Workspace entnommen.
9
F7.10
4 S‐Function – Fallschirmsprung ‐ Versuch
function fallschirmM(block)
Kap7 4Fallschirm/fallschirmM.m
global h1
setup(block);
hws = get_param(bdroot, 'modelworkspace');
h1 = hws.getVariable('h1');
% ergänze ...
Beachte h1 ist nicht die Variable h1
%endfunction
function setup(block)
%% bleibt unverändert
...
%endfunction
aus dem Modellworkspace. Es wer‐
den nur die Werte gleich gesetzt.
AS
h( t)  h1


t  t0
 ( AFS  AS) h1  h( t) , t 0  t  t 0  DT
A( t)   AS 
function Output(block)
DT

AFS
t  t 0  DT
global h1

% ersetze
if block.InputPort(1).Data > h1
block.OutputPort(1).Data = 0.5;
else
block.OutputPort(1).Data = 30;
end
%endfunction
10
F7.11
5 S‐Function mit zwei Ausgängen
Aufgabe: Die S‐Funktion display2M.m für das linke Modell (display2MSource.slx) soll so geändert werden, dass das rechte Modell entsteht. Der geänderte Block besitzt zwei Ausgänge. Bei Ausgang 1 wird das mit dem Faktor 2 multiplizierte Eingangs‐signal ausgegeben. Bei Ausgang 2 wird mit dem Faktor 3 multipliziert.
Beachte : Ohne die MATLAB/Simulink‐Dokumentation mit entsprechenden Beispielen kön‐
nen diese oder ähnliche Aufgaben nicht gut und effektiv gelöst werden. Bei kom‐
plexen Anwendungen ist auch viel Hintergrundwissen über Simulink notwendig.
Hilfe findet man u.a. mit den Suchbegriffen :
S‐Function Level‐2 MATLAB S‐Function S‐Function Basics
Simulink > Modeling > Block Libraries > User‐Defined Functions >
Simulink > Block Creation > Host‐Specific Code >
11
PDF‐Dokument : Developing S‐Functions (548 Seiten)
F7.12
5 S‐Function mit zwei Ausgängen
function display2M_lsg(block)
setup(block);
%endfunction
Kap7 5Display/display2M.m
function setup(block)
. . .
%% Register methods
block.RegBlockMethod('Outputs',@Output);
block.RegBlockMethod('SetInputPortSamplingMode',...
@SetInpPortFrameData);
%endfunction
function Output(block)
block.OutputPort(1).Data = 2*block.InputPort(1).Data;
block.OutputPort(2).Data = 3*block.InputPort(1).Data;
%endfunction
Optionale Callback‐Funktion
function SetInpPortFrameData(block,
block.InputPort(idx).SamplingMode
block.OutputPort(1).SamplingMode
block.OutputPort(2).SamplingMode
%endfunction
idx, fd)
= fd;
= fd;
= fd;
12
F7.13
5 S‐Function mit zwei Ausgängen
MATLAB stellt eine Vielzahl von Beispielen zu S‐Functions bereit. Ohne diese Bei‐
spiele wäre es sehr schwer die Dokumentation zu verstehen.
Die Beispiele zu S‐Functions werden mit dem MATLAB‐Befehl sfundemos angezeigt oder über User‐Defined Functions im Simulink Library Browser.
Siehe nächste Folie.
13
F7.14
Template für S‐Functions
msfuntmpl.m
5 S‐Function mit zwei Ausgängen
matlabroot\toolbox\simulink\simdemos
\simfeatures\msfcn_times_two.m
Entspricht dem Beispiel aus Abschnitt 2 mal2M.m .
14
6 Zur Mathematik von Simulink‐Blöcken
F7.15
x
y
(Input)
(States)
(Output)
States (Memory): x  x c ; x d 
• Discrete States: xd
• Continuous States: xc
y  f0 ( t, x, u)
Outputs
x dk1  fu ( t, x c , x dk ,u) Update
x  fd ( t, x,u)
Derivatives
Dieser Teil wird nur für Blöcke ausge‐
führt, die Continuous States enthalten, z.B. Integrator, Transfer‐Function.
minor time step
u
major time step
A Simulink block consists of a set of inputs, a set of states, and a set of outputs, where the outputs are a function of the simulation time, the inputs, and the states.
The following equations express the mathematical relationships between the inputs, outputs, states, and simulation time.
15
F7.16
6 Zur Mathematik von Simulink‐Blöcken
Simulation Stages
Execution of a Simulink model proceeds in stages. First comes the initialization phase. In this phase, the Simulink engine incorporates library blocks into the model, propagates signal widths, data types, and sample times, evaluates block parameters, determines block execution order, and allocates memory. The engine then enters a simulation loop, where each pass through the loop is referred to as a simulation step. During each simulation step, the engine executes each block in the model in the order determined during initialization. For each block, the engine invokes functions that compute the block states, derivatives, and outputs for the current sample time.
The following figure illustrates the stages of a simulation. The inner integration loop takes place only if the model contains continuous states. The engine executes this loop until the solver reaches the desired accuracy for the state computations. The entire simulation loop then continues until the simulation is complete. See Simulating Dynamic Systems in Using Simulink for more detailed information on how the engine executes a model. See Simulink Engine Interaction with C S‐Functions for a description of how the engine calls the S‐function API during initialization and simulation.
16
F7.17
6 Zur Mathematik von Simulink‐Blöcken
http://de.mathworks.com/matlabcentral/answers/
36663-what-are-continuous-and-discrete-states-in-simulink
Question : I see references in the Simulink documentation to continuous and discrete
states, for example: Does the block need to model continuous or discrete state behavior. Is this the same thing as "Does the block need to solve for time variation of some quantity, either at continuous or fixed time steps?" If not, please define what a state is in Simulink.
Answer : In my own words, a crude word to use in place of "state" is "memory". A state adds memory to a system in such a way that the output at a given time depends
not only on its current input, but also on its previous inputs. There is also a more formal explanation about states here:
Discrete states can be thought purely as internal memory ‐ for example a Unit Delay block has one discrete state, and it's output is computed based on two methods: Outputs and Update, which may be written as follows (u=input, x=state, y=output):
Outputs() Update() y = x; x = u;
Here, the Simulink Engine never reads the discrete states, it only manages the memory allocation/de‐allocation for the states. The delay is caused due to the fact that Update() runs after Output(), which means that the current "u" is only read into "y" at the next time‐step when Output() runs again. …
17
F7.18
6 Zur Mathematik von Simulink‐Blöcken
Der Block Unit‐Delay gibt am Ausgang das um einen Zeitschritt verzögerte Ein‐
gangssignal aus. Die Verzögerung ist damit durch die Step‐Size festgelegt. Bei Simu‐
lationsbeginn (meist t=0) wird ein vorgegebener Anfangswert (Initial Condition) ausgegeben.
1
u
y
(Input)
(Output)
Z
Unit Delay
Time steps : t k  k  T , k  0, 1, 2
Unit‐Delay :
k0
ut 0 
y t 0 
y t 0   Initial Condition
k 1
ut1 
yt1 
y t k   ut k 1 
k2
ut 2 
yt 2 
Wie lauten die mathematischen Beziehungen im Block Unit‐Delay?
y  f0 ( t, x, u)
Outputs
x dk1  fu ( t, x c , x dk ,u) Update
x  fd ( t, x,u)
Derivatives
18
F7.19
6 Zur Mathematik von Simulink‐Blöcken
Konfiguration Parameters:
19
6 Zur Mathematik von Simulink‐Blöcken
F7.20
x
xDiscStates : Werte der States in Abhängigkeit von der Zeit
1 State
x
x
2 States
x1 x2
2 States
x2
x1
3 States
x1
x2 x3
x
x1 x2
x1 x2
x1 x2 x3
xFinalDisc.loggedStates
Werte der States am Ende der Simulation
20
6 Zur Mathematik von Simulink‐Blöcken
F7.21
Der Integrator‐Block gibt am Ausgang das Integral des Eingangssignals über die Zeit aus. Die Integrationskonstante wird durch einen Anfangswert (Initial Condition) festgelegt.
u(t)
(Input)
1
S
Integrator
y(t)
(Output)
t
y( t)  y0   u( t' ) dt'
0
Wie lauten die mathematischen Beziehungen für den Integrator‐Block?
y  f0 ( t, x, u)
Outputs
x dk1  fu ( t, x c , x dk ,u) Update
x  fd ( t, x,u)
Derivatives
21
F7.22
6 Zur Mathematik von Simulink‐Blöcken
Konfiguration Parameters:
xContStates : Werte der States in Abhängigkeit von der Zeit
xFinalCont.loggedStates
Werte der States am Ende der Simulation
22
F7.23
7 S‐Functions im Detail – Unit‐Delay und msfuntmpl.m
function msfcn_unit_delay(block)
setup(block);
%endfunction
function setup(block)
block.NumDialogPrms = 1;
%% Register number of input and output ports
block.NumInputPorts = 1;
block.NumOutputPorts = 1;
%% Setup functional port properties to dynamically inherited.
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.InputPort(1).Dimensions
= 1;
block.InputPort(1).DirectFeedthrough = false;
block.OutputPort(1).Dimensions
= 1;
%% Set block sample time to [0.1 0] - discret
block.SampleTimes = [0.1 0];
zusätzliche Callback‐
%% Set the block simStateCompliance to default
Funktion registrieren
block.SimStateCompliance = 'DefaultSimState';
%% Register methods
block.RegBlockMethod('PostPropagationSetup', @DoPostPropSetup);
block.RegBlockMethod('InitializeConditions', @InitConditions);
block.RegBlockMethod('Outputs', @Output);
block.RegBlockMethod('Update', @Update);
%endfunction
23
F7.24
7 S‐Functions im Detail – Unit‐Delay und msfuntmpl.m
function DoPostPropSetup(block)
%% Setup Dwork – define 1 state variable
block.NumDworks = 1;
define x d
block.Dwork(1).Name = 'x0';
block.Dwork(1).Dimensions
= 1;
block.Dwork(1).DatatypeID
= 0;
block.Dwork(1).Complexity
= 'Real';
block.Dwork(1).UsedAsDiscState = true;
%endfunction
yk  x dk
x dk1  u( t k )
function InitConditions(block)
% Initialize Dwork
x d  initial condition
block.Dwork(1).Data = block.DialogPrm(1).Data;
%endfunction
yk  x dk
function Output(block)
block.OutputPort(1).Data = block.Dwork(1).Data;
%endfunction
function Update(block) x dk 1  u( t k )
block.Dwork(1).Data = block.InputPort(1).Data;
%endfunction
24
F7.25
7 S‐Functions im Detail – Unit‐Delay und msfuntmpl.m
Die Datei msfuntmpl.m (Matlab S‐Function Template, Siehe Verzeichnis Kap7 7Template) ist ein Template für MATLAB S‐Functions. Schreibt man eine neue S‐Function in MATLAB dann sollte diese Datei als
Vorlage verwendet werden.
Alle möglichen Callback‐Funktionen sind bereits vorhanden. Oft ist ein Standard‐
verhalten implementiert. Es werden die Standardnamen für Funktionen und Variablen verwendet. Die Funktionen sind bereits dokumentiert. Erfahrene
Entwickler wissen, welche Bedeutung die Funktionen und Variablen haben. Man sollte sich an diese Konventionen halten. Ansonsten versteht niemand das Programm.
Um die vielen optionalen Callback‐Funktionen zu verstehen, muss man die MATLAB‐Dokumentation lesen und geeignete Beispiele studieren.
Beachte : In der Funktion setup werden die optionalen Callback‐Funktionen
über Function‐Handles gesetzt; z.B.
block.RegBlockMethod('Update', @Update);
25
8 S‐Functions in C
F7.26
S‐Funktionen werden häufig in C geschrieben, weil der Code performanter ist oder weil ein Zugriff auf Hardware notwendig ist.
S‐Funktionen in C werden auf zwei verschiedene Arten geschrieben :
• Quellcode per Hand schreiben (hierzu ist die Dokumentation notwendig und eine Reihe von guten Beispielen) analog zu den S‐Funktionen mit MATLAB
• S‐Function‐Builder
Ein Tool um den C‐Code für eine S‐Funktion über eine graphische Oberfläche automatisch zu erzeugen. Dieser Code kann dann nachbearbeitet werden.
Die C‐Funktion wird danach mit der Mex‐Utility in eine DLL übersetzt. Während der Simulation wird diese DLL aufgerufen (beim Abarbeiten des S‐Function‐Blocks).
Beispiel : mex mal2C.c erzeugt die DLL mal2C.mexw64
mal2CSource.slx
mal2CSourceMultiple.slx
26
F7.27
8 S‐Functions in C
Callback Methods for C MEX S‐Functions
C MEX S‐functions must implement the following (required) callback methods:
• mdlInitializeSizes
Specifies the sizes of various parameters in the SimStruct, such as the number of output ports for the block ‐ entspricht der Funktion setup
• mdlInitializeSampleTimes
Specifies the sample time(s) of the block.
• mdlOutputs
Calculates the output of the block – entspricht der Funktion Output
• mdlTerminate
Performs any actions required at the termination of the simulation. If no actions are required, this function can be implemented as a stub.
Alle Callback‐Funktionen für S‐Functions in C beginnen mit mdl... Der erste
Parameter dieser Callback‐Funktionen ist ein Zeiger auf die Struktur SimStruct
static void mdlOutputs(SimStruct *S, int_T tid)
Die Callback‐Funktionen werden von der Simulink‐Engine aufgerufen. Information, die in SimStruct (entspricht dem Parameter block) enthalten ist, wird über
Macros gelesen oder geschrieben. Diese Macros beginnen mit ss, z.B. int_T ssGetNumOutputPorts(SimStruct *S)
27
F7.28
8 S‐Functions in C
Beispiel : Timestwo (siehe S‐Function Basics in der Simulink Dokumentation)
Bei diesen Beispiel sind keine States erforderlich. Das Ausgangssignal ist eine
Funktion des Eingangssignals. Deshalb muss DirectFeedThrough auf true gesetzt
werden.
28
F7.29
8 S‐Functions in C
#define S_FUNCTION_NAME mal2C
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
/* mdlInitializeSizes Setup sizes of the various vectors.*/
static void mdlInitializeSizes(SimStruct *S) {
ssSetNumSFcnParams(S, 0);
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S))
return; /* Parameter mismatch reported by Simulink */
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetInputPortDirectFeedThrough(S, 0, 1);
if (!ssSetNumOutputPorts(S,1)) return;
ssSetOutputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetNumSampleTimes(S, 1);
/* sim state compliance to be same as a built-in block */
ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
ssSetOptions(S, SS_OPTION_WORKS_WITH_CODE_REUSE |
SS_OPTION_EXCEPTION_FREE_CODE |
SS_OPTION_USE_TLC_WITH_ACCELERATOR);
}
29
F7.30
8 S‐Functions in C
Macros in mdlInitializeSizes (siehe MATLAB‐Doku)
void ssSetInputPortDirectFeed(SimStruct *S, int_T port, int_T dirFeed)
A port has direct feedthrough if the input is used in either the mdlOutputs or
mdlGetTimeOfNextVarHit function. The direct feedthrough flag for each input port can be set to either 1=yes or 0=no. It should be set to 1 if the input, u, is used in the mdlOutputs or mdlGetTimeOfNextVarHit routine. Setting the direct feedthrough flag to 0 tells the Simulink engine that u is not used in either of these S‐function routines. Violating this leads to unpredictable results.
int_T ssSetInputPortWidth(SimStruct *S,int_T port, int_T width)
If the S‐function does not require that its input signals have specific dimensions, set the di‐
mensionality of the input ports to match the dimensionality of the signals connected to them. ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED)
The input port can accept only vector (1‐D) signals but the signals can be of any size.
int_T ssSetNumSampleTimes(SimStruct *S,int_T nSamplesTimes)
Use 1 if input port and output port have the same sampling rate.
30
F7.31
8 S‐Functions in C
/* inherit sample time from the driving block. */
static void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
ssSetModelReferenceSampleTimeDefaultInheritance(S);
}
/* mdlOutputs y = 2*u*/
static void mdlOutputs(SimStruct *S, int_T tid) {
int_T
i;
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
real_T
*y
= ssGetOutputPortRealSignal(S,0);
int_T
width = ssGetOutputPortWidth(S,0);
for (i=0; i<width; i++)
{
*y++ = 2.0 *(*uPtrs[i]);
}
}
/* mdlTerminate No termination needed, but we are required
to have this routine. */
static void mdlTerminate(SimStruct *S)
{ }
31
F7.32
8 S‐Functions in C
mdlOutputs (siehe MATLAB‐Doku)
The engine calls mdlOutputs at each time step to calculate the block outputs. The timestwo implementation of mdlOutputs multiplies the input signal by 2 and writes the answer to the output. The line:
InputRealPtrsType uPtrs =
ssGetInputPortRealSignalPtrs(S,0);
accesses the input signal. The ssGetInputPortRealSignalPtrs macro returns a vector of pointers, which you must access using
*uPtrs[i]
The line:
real_T *y = ssGetOutputPortRealSignal(S,0);
accesses the output signal. The ssGetOutputPortRealSignal macro returns a pointer to an array containing the block outputs. The line:
int_T width = ssGetOutputPortWidth(S,0);
obtains the width of the signal passing through the block. The S‐function loops over the inputs to compute the outputs.
32
F7.33
8 S‐Functions in C
Verwendung von Macros
In den Beispielen zu C‐S‐Functions werden normalerweise nicht die C‐Standard‐
typen verwendet, um Werte von Typ "double" oder "int" zu definieren.
Der Grund ist, dass in C nicht definiert ist, wieviele Bits ein Integer‐Wert oder ein
Double‐Wert besitzt. Das ist abhängig vom Compiler und der Plattform (32‐Bit, 64‐
Bit, Windows, Unix, Mac‐OS). Bei Spezialhardware ist die Situation noch kom‐
plexer. Mit Hilfe von Macros versucht man diese Probleme zu lösen. Diese Macro sind in der Include‐Datei tmwtypes.h definiert.
#ifndef REAL_T
# ifdef REAL64_T
# define REAL_T real64_T
# else
# ifdef REAL32_T
#
define REAL_T real32_T
# endif
# endif
#endif
#ifdef REAL_T
typedef REAL_T real_T;
#endif
#ifndef REAL64_T
# ifndef __MWERKS__
# if DBL_MANT_DIG >= 52
#
define REAL64_T double
# endif
# else
# define REAL64_T double
# endif
#endif
#ifdef REAL64_T
typedef REAL64_T real64_T;
#endif
33
F7.34
34
F7.35
35
F7.36
8 S‐Functions in C
Hinweise zum Schreiben einer neuen S‐Funktion
Verwende als Startpunkt keine leere Datei. Verwende
• sfuntmpl_basic.c
Ein Basis‐Template für S‐Funktionen, das für viele Anwendungen ausreicht.
• sfuntmpl_basic.c
Ein ausführlich dokumentiertes Template für S‐Funktionen. Hilfreich auch zum
Nachschauen. • Ein gut geschriebenes Beispiel, das dann entsprechend angepasst wird.
Am besten eignen sich die Beispiele, die Mathworks bereitstellt, da diese von Experten geschrieben und sehr gut dokumentiert sind.
Weiterhin hilfreich ist die Include‐Datei simstruc.h. Diese Datei besitzt ca. 12000 Zeilen.
36
F7.37
8 S‐Function in C
Aufgabe 2 Die S‐Funktion aufgabe2C.c für das linke Modell (aufgabe2CSource.slx) soll so geändert werden, dass das rechte Modell entsteht. Der geänderte Block besitzt zwei Ausgänge. Bei Ausgang 1 wird das um den Faktor 2 multiplizierte Eingangs‐
signal ausgegeben, bei Ausgang 2 das um den Faktor 3 multiplizierte Eingangs‐
signal.
37
F7.38
8 S‐Function in C
Aufgabe 3 Die S‐Funktion aufgabe3C.c für das linke Modell (aufgabe3CSource.slx) soll so geändert werden, dass das rechte Modell entsteht. Der geänderte Block besitzt zwei Ausgänge. Bei Ausgang 1 wird das um den Faktor 2 multiplizierte Eingangs‐
signal ausgegeben, bei Ausgang 2 das um den Faktor 3 multiplizierte Eingangs‐
signal. Nach 5 Sekunden werden beide Faktoren verdoppelt.
Hinweis :
Die aktuelle Simulationszeit wird in der Funktion mdlOutputs mit dem Aufruf
time_T time = ssGetT(S);
geholt. Der Datentyp time_T ist in der Datei matlabroot/extern
/include/tmwtypes.h definiert.
Die Datei simstruc.h befindet sich in matlabroot/simulink/include38
F7.39
8 S‐Function in C
Aufgabe 3 Die S‐Funktion aufgabe3C.c für das linke Modell (aufgabe3CSource.slx) soll so geändert werden, dass das rechte Modell entsteht. Der geänderte Block besitzt zwei Ausgänge. Bei Ausgang 1 wird das um den Faktor 2 multiplizierte Eingangs‐
signal ausgegeben, bei Ausgang 2 das um den Faktor 3 multiplizierte Eingangs‐
signal. Nach 5 Sekunden werden beide Faktoren verdoppelt.
Hinweis :
Die aktuelle Simulationszeit wird in der Funktion mdlOutputs mit dem Aufruf
time_T time = ssGetT(S);
geholt. Der Datentyp time_T ist in der Datei matlabroot/extern
/include/tmwtypes.h definiert.
Die Datei simstruc.h befindet sich in matlabroot/simulink/include39
F7.40
9 S‐Function Builder
Mit dem Block S‐Function Builder kann eine S‐Funktion über eine graphische Oberfläche definiert und der zugehörige C‐Code automatisch erzeugt werden.
Der C‐Code für die Funktion Output und Update wird über die GUI eingeben.
40
F7.41
8 S‐Funktionen in C
Aufgabe 7 Ersetzen Sie im Model aufgabe7CSource.slx den S‐Function‐Block durch einen S‐Function‐Builder Block.
• Im S‐Function Builder Block werden 4 Parameter AS, AFS, h1 und DT definiert. Siehe Parameters im Tab Data Properties.
• Bei Input Ports und Output Ports im Tab Data Properties ist bereits jeweils ein Port eingetragen. Wichtig sind hier die Namen u0 und y0, damit man in Outputs mit dem C‐Code auf die Ports zugreifen kann.
• Im Tab Initialization wird eine State‐Variable mit dem Namen xD angelegt.
• Die Veränderung der State‐Variablen wird im Tab Discrete Update definiert. Hier muss der entsprechende C‐Code eingegeben werden. • Die Berechnung der aktuellen Fläche des Fallschirms erfolgt im Tab Outputs. Hier wird der entsprechende C‐Code eingegeben. Hier erfolgt auch ein Zugriff auf die State‐Variable.
• Damit die Funktion Outputs auf die Struktur SimStruc zugreifen kann, muss im Tab Builder Info das entsprechende Flag gesetzt werden. • Über den Button Build werden eine sogenannte Wrapper‐C‐Function (enthält den Code aus Outputs und Update) und die eigentliche S‐Function generiert. Danach werden die Programme in eine DLL übersetzt.
41
F7.42
9 S‐Function Builder
42
F7.43
9 S‐Function Builder
43
F7.44
9 S‐Function Builder
44
F7.45
9 S‐Function Builder
45
F7.46
10 Aufgabe 1 ‐ Fallschirmsprung
Ersetze im Simulink‐Modell fallschirmMSource.slx (Kap7 A1FallSchirm) den Sub‐
system Block durch einen Level‐2 MATLAB S‐Function Block. Die Fläche des Fall‐
schirms soll nach dem Öffnen linear anwachsen. Die benötigten Werte für h1, AS, AFS und DT werden aus dem Model‐Workspace entnommen.
46
F7.47
10 Aufgabe 2 ‐ S‐Function mit zwei Ausgängen
Die S‐Funktion display2M.m für das linke Modell (Kap7 A2Display) soll so geän‐
dert werden, dass das rechte Modell entsteht. Der geänderte Block besitzt zwei Ausgänge. Bei Ausgang 1 wird das mit dem Faktor 2 multiplizierte Eingangssignal ausgegeben. Bei Ausgang 2 wird mit dem Faktor 3 multipliziert.
Ändern Sie das m‐File display2M.m so wie in Abschnitt 5 gezeigt.
47
F7.48
10 Aufgabe 3 ‐ Fallschirmsprung mit MATLAB S‐Function
Lösen Sie die Aufgabe mit dem Fallschirmsprung „richtig“ (Kap7 A3Fallschirm‐
Korrekt)! Verwenden Sie keine globalen Variablen! Verwenden Sie die ent‐
sprechenden Callback Funktionen • PostPropagationSetup
Specify the sizes of the work vectors and create the run‐time parameters required by this MATLAB S‐function (Definieren Sie hier die Variablen, die im
Programm benötigt werden).
• InitializeConditions
The Simulink engine invokes this optional method at the beginning of a simulation. It should initialize the continuous and discrete states, if any, of this S‐Function block. In a Level‐2 MATLAB S‐function, use the ContStates or Dwork
run‐time object methods to access the continuous and discrete states. This method can also perform any other initialization activities that this S‐function requires (Lesen Sie hier die Parameter aus dem Modell‐Workspace und speichern Sie die Werte in den Variablen, die zuvor definiert worden sind).
Lesen Sie die Parameter aus dem Modell‐Workspace und speichern Sie deren Werte in "Dwork" . Weiterhin wird eine Variable gebraucht um den Zeitpunkt zu speichern, bei dem sich der Fallschirm öffnet. 48
F7.49
10 Aufgabe 4 ‐ Fallschirmsprung mit MATLAB S‐Function
Die Werte für AS, AFS, h1 und DT werden aus dem Model‐Workspace gelöscht. Die Werte werden über das Eingabefeld "Parameters" des Level‐2 MATLAB S‐Function Blocks eingegeben. Verwende a4fallschirmM aus Kap7 A4Parameter
Hinweis : In der Callback‐Funktion setup wird die Anzahl der Dialogparameter (NumDialogPrms) auf 4 gesetzt. In der Callback‐Funktion DoPostPropSetup
werden 5 Variablen definiert (4 Parameter und der Zeitpunkt des Öffnens t0). Die vier Parameter aus dem Parameters‐Feld werden in der Callback‐Funktion InitConditions gelesen (siehe Beispiel Unit‐Delay) und in den entsprechen‐
den Variablen (work area) gespeichert.
49
F7.50 10 Aufgabe 5 ‐ Fallschirmsprung mit MATLAB S‐Function und Mask
Die Werte für AS, AFS, h1 und DT werden nun in einer Maske gesetzt. Nach einem Doppelklick auf den S‐Function Block soll sich das Fenster links zeigen – eine Maske.
Maske : öffnet sich nach Doppel‐
klick oder über Kontext‐Menü
Über das Kontext‐Menü "Mask" eines Blocks wird eine Maske erzeugt und bearbeitet.
Kontext‐Menü "Block‐Parameters" oder "Look Under Mask"
50
F7.51 10 Aufgabe 5 ‐ Fallschirmsprung mit MATLAB S‐Function und Mask
Containerelemente
Parameter
Mask Editor :
1) Container vom Typ Group box erzeugen
2) Namen der Group box setzen ‐
ConfigParams
3) Vier Parameter (Edit) in die Group box ConfigParams ziehen
4) Eigenschaften der Parameter setzen
51
F7.52
10 Aufgabe 6 ‐ Fallschirmsprung mit C S‐Function
Ändern Sie die S‐Funktion aufgabe5C.c so ab, dass die Fläche des Fallschirms nach dem Öffnen linear ansteigt. Ändern Sie die Funktion mdlOutputs
entsprechend.
Hinweis : Verwenden Sie ssSetNumRWork(S,1) in der Callback‐Funktion mdlInitializeSizes um eine Variable (1) für die Zeit t0 zu definieren. In der Funktion mdlOutputs kann diese Variable mit dem Ausdruck real_T *zg_t0 = ssGetRWork(S); verwendet werden.
static void mdlOutputs(SimStruct *S, int_T tid)
{
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
real_T
*y
= ssGetOutputPortRealSignal(S,0);
real_T
if ( h
*y
} else
*y
}
h = *uPtrs[0];
>300 ) {
= 0.5;
{
= 30;
}
52