Writing S-Functions | ![]() ![]() |
Multirate S-Function Blocks
In a multirate S-Function block, you can encapsulate the code that defines each behavior in the mdlOutput
and mdlUpdate
functions with a statement that determines whether a sample hit has occurred. The ssIsSampleHit
macro determines whether the current time is a sample hit for a specified sample time. The macro has this syntax
ssIsSampleHit(S, st_index, tid)
where S
is the SimStruct
, st_index
identifies a specific sample time index, and tid
is the task ID (tid
is an argument to the mdlOutput
and mdlUpdate)
.
For example, these statements specify three sample times: one for continuous behavior, and two for discrete behavior.
ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME); ssSetSampleTime(S, 1, 0.75); ssSetSampleTime(S, 2, 1.0);
In the mdlUpdate
function, the following statement would encapsulate the code that defines the behavior for the sample time of 0.75 second.
if (ssIsSampleHit(S, 1, tid)) { }
The second argument, 1
, corresponds to the second sample time, 0.75 second.
Example - Defining a Sample Time for a Continuous Block
This example defines a sample time for a block that is continuous in nature.
/*
Initialize the sample time and offset.*
/ static void mdlInitializeSampleTimes(SimStruct*
S) { ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); }
You must add this statement to the mdlInitializeSizes
function.
ssSetNumSampleTimes(S, 1);
Example - Defining a Sample Time for a Hybrid Block
This example defines sample times for a hybrid S-Function block.
/*
Initialize the sample time and offset.*
/ static void mdlInitializeSampleTimes(SimStruct*
S) { /*
Continuous state sample time and offset.*
/ ssSetSampleTime(S, 0, CONTINUOUS_SAMPLE_TIME); ssSetOffsetTime(S, 0, 0.0); /*
Discrete state sample time and offset.*
/ ssSetSampleTime(S, 1, 0.1); ssSetOffsetTime(S, 1, 0.025); }
In the second sample time, the offset causes Simulink to call the mdlUpdate
function at these times: 0.025 second, 0.125 second, 0.225 second, and so on, in increments of 0.1 second.
The following statement, which indicates how many sample times are defined, also appears in the mdlInitializeSizes
function.
ssSetNumSampleTimes(S, 2);
![]() | Specifying the Number of Sample Times in mdlInitializeSizes | Synchronizing Multirate S-Function Blocks | ![]() |