Main Content

Use Enumerated Data in Generated Code

Enumerated Data Types

Enumerated data is data that is restricted to a finite set of values. An enumerated data type is a MATLAB® class that defines a set of enumerated values. Each enumerated value consists of an enumerated name and an underlying integer which the software uses internally and in generated code. The following is a MATLAB class definition for an enumerated data type named BasicColors, which is used in the examples in this section.

classdef BasicColors < Simulink.IntEnumType
  enumeration
    Red(0)
    Yellow(1)
    Blue(2)
  end
end

For basic information about enumerated data types and their use in Simulink® models, see Use Enumerated Data in Simulink Models. For information about enumerated data types in Stateflow® charts, see Define Enumerated Data Types (Stateflow).

Specify Integer Data Type for Enumeration

When you specify a data type for your enumeration, you can:

  • Control the size of enumerated data types in the generated code by specifying a superclass.

  • Reduce RAM/ROM usage.

  • Improve code portability.

  • Improve integration with legacy code.

You can specify these integer data types:

  • int8

  • uint8

  • int16

  • uint16

  • int32

  • Simulink.IntEnumType. Specify values in the range of the signed integer for your hardware platform.

Use a Class Definition in a MATLAB File

To specify an integer data type size, derive your enumeration class from the integer data type.

classdef Colors < int8
   enumeration
     Red(0)
     Green(1)
     Blue(2)
   end
end

The code generator generates this code:

typedef int8_T Colors;

#define Red      ((Colors)0)
#define Green ((Colors)1)
#define Blue     ((Colors)2)

Use the Function Simulink.defineIntEnumType

To specify an integer data type size, specify the name-value pair StorageType as the integer data type.

Simulink.defineIntEnumType('Colors',{'Red','Green','Blue'},...
[0;1;2],'StorageType','int8')

The code generator generates this code:

typedef int8_T Colors;

#define Red      ((Colors)0)
#define Green ((Colors)1)
#define Blue     ((Colors)2)

Customize Enumerated Data Type

When you generate code from a model that uses enumerated data, you can implement these static methods to customize the behavior of the type during simulation and in generated code:

  • getDefaultValue — Specifies the default value of the enumerated data type.

  • getDescription — Specifies a description of the enumerated data type.

  • getHeaderFile — Specifies a header file where the type is defined for generated code.

  • getDataScope — Specifies whether generated code exports or imports the enumerated data type definition to or from a separate header file.

  • addClassNameToEnumNames — Specifies whether the class name becomes a prefix in generated code.

The first of these methods, getDefaultValue, is relevant to both simulation and code generation, and is described in Specify a Default Enumerated Value. The other methods are relevant only to code generation. To customize the behavior of an enumerated type, include a version of the method in the methods(Static) section of the enumeration class definition. If you do not want to customize the type, omit the methods(Static) section. The table summarizes the methods and the data to supply for each one.

Static MethodPurposeDefault Value Without Implementing MethodCustom Return Value
getDefaultValueSpecifies the default enumeration member for the class.First member specified in the enumeration definitionA character vector containing the name of an enumeration member in the class (see Instantiate Enumerations).
getDescriptionSpecifies a description of the enumeration class.''A character vector containing the description of the type.
getHeaderFileSpecifies the name of a header file. The method getDataScope determines the significance of the file.''

A character vector containing the name of the header file that defines the enumerated type.

By default, the generated #include directive uses the preprocessor delimiter " instead of < and >. To generate the directive #include <myTypes.h>, specify the custom return value as '<myTypes.h>'.

getDataScopeSpecifies whether generated code exports or imports the definition of the enumerated data type. Use the method getHeaderFile to specify the generated or included header file that defines the type.'Auto'One of: 'Auto', 'Exported', or 'Imported'.
addClassNameToEnumNamesSpecifies whether to prefix the class name in generated code.falsetrue or false.

Specify a Description

If you have an Embedded Coder® license, you can enable the Simulink data object descriptions (Embedded Coder) model configuration parameter to include descriptions for enumerated data types in the generated code. To specify a description for an enumerated data type, include this method in the methods(Static) section of the enumeration class:

function retVal = getDescription() 
% GETDESCRIPTION  Optional description of the data type.
  retVal = 'description';
end

Substitute a MATLAB character vector for description. The generated code that defines the enumerated type includes the specified description.

Import Type Definition in Generated Code

To prevent generated code from defining an enumerated data type, which allows you to provide the definition in an external file, include these methods in the methods(Static) section of the enumeration class:

    function retVal = getHeaderFile()
      % GETHEADERFILE Specifies the file that defines this type in generated code.
      % The method getDataScope determines the significance of the specified file.
      retVal = 'imported_enum_type.h';
    end

    function retVal = getDataScope()
      % GETDATASCOPE Specifies whether generated code imports or exports this type.
      % Return one of:
      % 'Auto':     define type in model_types.h, or import if header file specified
      % 'Exported': define type in a generated header file
      % 'Imported': import type definition from specified header file
      % If you do not define this method, DataScope is 'Auto' by default.
      retVal = 'Imported';
    end

Instead of defining the type in model_types.h, which is the default behavior, generated code imports the definition from the specified header file using a #include statement like:

#include "imported_enum_type.h"

Generating code does not create the imported header file. You must provide the header file, using the file name specified by the method getHeaderFile, that defines the enumerated data type.

To create a Simulink enumeration that corresponds to your existing C-code enumeration, use the Simulink.importExternalCTypes function.

Export Type Definition in Generated Code

To generate a separate header file that defines an enumerated data type, include these methods in the methods(Static) section of the enumeration class:

    function retVal = getDataScope()
      % GETDATASCOPE Specifies whether generated code imports or exports this type.
      % Return one of:
      % 'Auto':     define type in model_types.h, or import if header file specified
      % 'Exported': define type in a generated header file
      % 'Imported': import type definition from specified header file
      % If you do not define this method, DataScope is 'Auto' by default.
      retVal = 'Exported';
    end

    function retVal = getHeaderFile()
      % GETHEADERFILE Specifies the file that defines this type in generated code.
      % The method getDataScope determines the significance of the specified file.
      retVal = 'exported_enum_type.h';
    end

Generated code exports the enumerated type definition to the generated header file exported_enum_type.h.

Add Prefixes To Class Names

By default, enumerated values in generated code have the same names that they have in the enumeration class definition. Alternatively, your code can prefix every enumerated value in an enumeration class with the name of the class. You can use this technique to prevent identifier conflicts or to improve the readability of the code. To specify class name prefixing, include this method in the methods(Static) section of an enumeration class:

    function retVal = addClassNameToEnumNames()
      % ADDCLASSNAMETOENUMNAMES Specifies whether to add the class name
      % as a prefix to enumeration member names in generated code.
      % Return true or false.
      % If you do not define this method, no prefix is added.
      retVal = true;
    end

Specify the return value as true to enable class name prefixing or as false to suppress prefixing. If you specify true, each enumerated value in the class appears in generated code as EnumTypeName_EnumName. For the example enumeration class BasicColors in Enumerated Data Types, the data type definition in generated code might look like this:

#ifndef _DEFINED_TYPEDEF_FOR_BasicColors_
#define _DEFINED_TYPEDEF_FOR_BasicColors_

typedef enum {
  BasicColors_Red = 0,            /* Default value */
  BasicColors_Yellow = 1,
  BasicColors_Blue = 2,
} BasicColors;

#endif

The enumeration class name BasicColors appears as a prefix for each of the enumerated names.

Control Use of Duplicate Enumeration Member Names

When you import the enumeration data from a header file, you can control the use of duplicate enumeration member names during code generation. Duplicate enumeration member names improve the readability of the code. Use the model configuration parameter Duplicate enumeration member names to allow duplicate enumeration member names in different enumeration types during code generation or to generate an error or a warning message. You can use duplicate enumeration member names only if two enumerations have the same StorageType and have these specifications:

  • DataScope set to 'Imported'

  • StorageType set to 'int8', 'int16', 'int32', 'uint8', 'uint16', or 'uint32'

  • Value is the same

For example:

typedef int32_T enum {
  Red = 0,
  Yellow = 1,
  Blue = 2,
}A;

typedef int32_T enum {
  Black = 0,
  Yellow = 1,
  White = 2,
}B;
You can have a Yellow enumeration member in enumeration A and B without prefixing the member name with a class name to improve the readability of your code.

Control Enumerated Type Implementation in Generated Code

Suppose that you define an enumerated type BasicColors. You can specify that the generated code implement the type definition by using:

  • An enum block. The native integer type of your hardware is the underlying integer type for the enumeration members.

  • A typedef statement and a series of #define macros. The typedef statement bases the enumerated type name on a specific integer data type, such as int8. The macros associate the enumeration members with the underlying integer values.

Implement Enumerated Type by Using enum Block

To implement the type definition by using an enum block:

  • In Simulink, define the enumerated type by using a classdef block in a script file. Derive the enumeration from the type Simulink.IntEnumType.

  • Alternatively, use the function Simulink.defineIntEnumType. Do not specify the property StorageType.

When you generate code, the type definition appears in an enum block.

#ifndef _DEFINED_TYPEDEF_FOR_BasicColors_
#define _DEFINED_TYPEDEF_FOR_BasicColors_

typedef enum {
  Red = 0,            /* Default value */
  Yellow,
  Blue,
} BasicColors;

#endif

Implement Enumerated Type Using a Specific Integer Type

To implement the type definition using a typedef statement and #define macros:

  • In Simulink, define the enumerated type using a classdef block in a script file. Derive the enumeration from a specific integer type such as int8.

  • Alternatively, use the function Simulink.defineIntEnumType. Specify the property StorageType using a specific integer type such as int8.

When you generate code, the type definition appears as a typedef statement and a series of #define macros.

#ifndef _DEFINED_TYPEDEF_FOR_BasicColors_
#define _DEFINED_TYPEDEF_FOR_BasicColors_

typedef int8_T BasicColors;

#define Red ((BasicColors)0)            /* Default value */
#define Yellow ((BasicColors)1)
#define Blue ((BasicColors)2)

#endif

By default, the generated file model_types.h contains enumerated type definitions.

Type Casting for Enumerations

Safe Casting

A Simulink Data Type Conversion block accepts a signal of integer type. The block converts the input to one of the underlying values of an enumerated type.

If the input value does not match an underlying value of an enumerated type value, Simulink inserts a safe cast to replace the input value with the enumerated type default value.

Enable and Disable Safe Casting

You can enable or disable safe casting for enumerations during code generation for a Simulink Data Type Conversion block or a Stateflow block.

To control safe casting, enable or disable the Saturate on integer overflow block parameter. The parameter works as follows:

  • Enabled: Simulink replaces a nonmatching input value with the default value of the enumerated values during simulation. The software generates a safe cast function during code generation.

  • Disabled: For a nonmatching input value, Simulink generates an error during simulation. The software omits the safe cast function during code generation. In this case, the code is more efficient. However, the code may be more vulnerable to run-time errors.

Safe Cast Function in Generated Code

This example shows how the safe cast function int32_T ET08_safe_cast_to_BasicColors for the enumeration BasicColors appears in generated code when generated for 32-bit hardware.

static int32_T ET08_safe_cast_to_BasicColors(int32_T input)
{
	int32_T output;
	/* Initialize output value to default value for BasicColors (Red) */
	output = 0;
	if ((input >= 0) && (input <= 2)) {
	/* Set output value to input value if it is a member of BasicColors */
		output = input;
	}
	return output;
}
Through this function, the enumerated type’s default value is used if the input value does not match one of underlying values of the enumerated type’s values.

If the block’s Saturate on integer overflow parameter is disabled, this function does not appear in generated code.

Enumerated Type Limitations

  • Generated code does not support logging enumerated data.

  • For uint32-based enumerations, enumeration values must be less than or equal to intmax('int32').

See Also

| |

Related Topics