Main Content

Structures of Signals

This example shows how to create a structure of signal data in the generated code.

C Construct

typedef struct {
   double signal1;
   double signal2;
   double signal3;
} my_signals_type;

Procedure

To represent a structure type in a model, create a Simulink.Bus object. Use the object as the data type of buses in your model.

1. Create the ex_signal_struct model by using Gain blocks, a Bus Creator block, and a Unit Delay block. The Gain and Unit Delay blocks make the structure more identifiable in the generated code.

2. To configure the Bus Creator block to accept three inputs, in the block dialog box, set Number of inputs to 3.

3. In the toolstrip, on the Modeling tab, in the Design gallery, click Type Editor.

4. In the Type Editor, create a Simulink.Bus object named my_signals_type that contains elements named signal1, signal2, and signal3. For more information, see Type Editor.

5. Save the bus objects in your current folder as ex_signal_struct_data.mat.

This bus object represents the structure type that you want the generated code to use.

6. In the Bus Creator block dialog box:

  • Set Output data type to Bus: my_signals_type.

  • Select Output as nonvirtual bus. A nonvirtual bus appears in the generated code as a structure.

  • Click OK.

7. Open the Simulink Coder app. In the C Code tab, select Code Interface > Individual Element Code Mappings.

8. Open the Signals/States tab. In the model, select the output signal of the Bus Creator block and click the Add selected signals to code mappings button in the Code Mappings editor.

9. For the added signal, set Storage Class to ExportedGlobal.

10. In the Property Inspector, set the Code > Identifier property to sig_struct_var. The output of the Bus Creator block appears in the generated code as a separate global structure variable named sig_struct_var.

11. Generate code from the model.

Results

The generated header file ex_signal_struct_types.h defines the structure type my_signals_type.

typedef struct {
  real_T signal1;
  real_T signal2;
  real_T signal3;
} my_signals_type;

The source file ex_signal_struct.c allocates memory for the global variable sig_struct_var, which represents the output of the Bus Creator block.

/* Exported block signals */
my_signals_type sig_struct_var;        /* '<Root>/Bus Creator' */

In the same file, in the model step function, the algorithm accesses sig_struct_var and the fields of sig_struct_var.

See Also

Related Topics