Main Content

Bitfields

C Construct

typedef struct {
   unsigned int p1 : 1;
   unsigned int p2 : 1;
   unsigned int p3 : 1;
} my_struct_type

Procedure

1. Open example model ex_struct_bitfield_CSC. The model contains three Constant blocks and three Outport blocks.

2. Open the Model Data Editor. On the Modeling tab, click Model Data Editor.

3. In the Model Data Editor, on the Parameters tab, in the Value column, observe that the value of the first Constant block is p1. Next to the parameter value, click the action button (the button with three vertical dots) and select Create.

4. In the Create New Data dialog box, set Value to Simulink.Parameter(false). Click Create. A Simulink.Parameter object, p1, appears in the base workspace. The object stores a Boolean value, false, and uses the data type boolean.

5. In the Simulink.Parameter property dialog box, click OK.

6. Use the Model Data Editor to configure the other Constant blocks to refer to new parameter objects named p2 and p3.

7. Open the Embedded Coder app.

8. In the C Code tab, select Code Interface > Individual Element Code Mappings.

9. In the Code Mappings editor, on the Parameters tab, click the Update Code Mappings button.

10. Use the Storage Class column to apply the storage class BitField to all parameter objects.

10. In the Property Inspector, sse the Struct Name column to configure each object to use the same structure type, my_struct.

11. Generate code from the model.

Results

The generated header file ex_struct_bitfield_CSC.h defines the structure type my_struct_type.

/* Type definition for custom storage class: BitField */
typedef struct myStruct_tag {
  uint_T p1 : 1;                       /* Referenced by: '<Root>/Constant1' */
  uint_T p2 : 1;                       /* Referenced by: '<Root>/Constant2' */
  uint_T p3 : 1;                       /* Referenced by: '<Root>/Constant3' */
} myStruct_type;

The generated source file ex_struct_bitfield_CSC.c defines and initializes the structure variable my_struct.

/* Definition for custom storage class: BitField */
myStruct_type myStruct = {
  /* p1 */
  0,

  /* p2 */
  0,

  /* p3 */
  0
};

Related Topics