You can define custom structures in C code, which you can integrate with your Stateflow® chart in a Simulink® model for simulation and code generation. For example, the model sf_bus_demo
uses a custom C function to write to the output structure outbus
. By
sharing data with custom code, you can augment the capabilities supported by Stateflow and
take advantage of your preexisting code. For more information, see Reuse Custom Code in Stateflow Charts and
Access Bus Signals Through Stateflow Structures.
In your C code, define a structure by creating a custom header file. The header file
contains typedef
declarations matching the properties of the
Simulink.Bus
object that defines the Stateflow structure. For example, in the model sfbus_demo
, the
header file counterbus.h
declares three custom structures:
... typedef struct { int input; } SIGNALBUS; typedef struct { int upper_saturation_limit; int lower_saturation_limit; } LIMITBUS; typedef struct { SIGNALBUS inputsignal; LIMITBUS limits; } COUNTERBUS; ...
In the Bus Editor, define a Simulink.Bus
object that matches each
custom structure typedef
declaration. In the Header
file field of each Simulink.Bus
object, enter the name
of the header file that contains the matching typedef
declaration.
Configure your C action language chart to include custom C code.
To include custom code for simulation, see Access Custom C Code in Nonlibrary Charts.
To include custom code for code generation, see Integrate External Code by Using Model Configuration Parameters (Simulink Coder).
Build and run your model.
When you write custom code functions that take structure pointers as arguments, pass the
Stateflow structures by address. To pass the address of a Stateflow structure or one of its fields to a custom function, use the
&
operator and dot notation:
&outbus
provides the address of the Stateflow structure outbus
.
&outbus.inputsignal
provides the address of the
substructure inputsignal
of the structure
outbus
.
&outbus.inputsignal.input
provides the address of the field
input
of the substructure
outbus.inputsignal
.
For more information, see Index Substructures and Fields.
For instance, the model sfbus_demo
contains a custom C function
counterbusFcn
that takes structure pointers as arguments. The custom
header file contains this function declaration:
extern void counterbusFcn (COUNTERBUS *u1, int u2, COUNTERBUS *y1, int *y2);
The chart passes the addresses to the Stateflow structures counterbus_struct
and outbus
by using this function call:
counterbusFcn(&counterbus_struct, u2, &outbus, &y2);
The function reads the value of the chart input u2
and the local
structure counterbus_struct
. It writes to the chart output
y2
and the output structure outbus
.