TIP: Working With ENUM types

rickj
2021-09-25
2021-09-25
  • rickj - 2021-09-25

    Every so often questions popup about using enums in visualizations or about how to cast to an enumerated type. Here are a couple of tips that some here may find useful.

    First of all, as far as I know, there is no codesys conversion or cast to enumerated types. The workaround is to remove the 'strict' attribute from the enum declaration and then use the underlying integer implementation (usually UDINT by default?).

    The other thing that is very convenient is to use the 'to_string' attribute in the enum declaration. This allows enum values to be converted to text using the TO_STRING() macro/function.

    In the example below an enumerated type is defined to represent color values that can be used in visualization components. It show how to convert the enum to string and to/from the underlying integer implementation.

    {attribute 'qualified_only'}            // Values must begine with type (i.e. eColor.Red)
    // {attribute 'strict'}                 // Comment out 'strict' to allow conversion from UDINT
    {attribute 'to_string'}                 // Allow string conversion (i.e. TO_STRING(eColor.Red) = 'Red')
    TYPE eColor :
    (
        Red         := 16#FFFF0000,
        Green       := 16#FF00FF00,
        Blue        := 16#FF0000FF
        Yellow      := 16#FFFFFF00,
    ) UDINT;                                // Explicitly specify UDINT as underlying integer implementation
    END_TYPE
    
    // Define some variables 
        ColorVar1   : eColor;
        ColorVar2   : eColor;
        ColorName   : STRING;
        ColorValue  : UDINT;
    
        ColorVar1 := eColor.Green;            // ColorVar1 = 16#FF00FF00
        ColorName := TO_STRING(ColorVar1);    // ColorName = 'Green';
        ColorValue := TO_UDINT(ColorVar1);    // ColorValue = 16#FF00FF00
    
        ColorVar2 := 16#FF00FF00;             // ColorVar1 = eColor.Green
        ColorName := TO_STRING(ColorVar2);    // ColorName = 'Green';
        ColorValue := TO_UDINT(ColorVar2);    // ColorValue = 16#FF00FF00
    
        ColorVar1 := ColorVar2 OR eColor.Red; // Red+Green make Yellow=16#FFFFFF00
        ColorName := TO_STRING(ColorVar1);    // ColorName = 'Yellow';
        ColorValue := TO_UDINT(ColorVar1);    // ColorValue = 16#FFFFFF00
    

    Although this may be rather obvious to some, others less familiar with codesys may find the above simple example helpful.

     
    πŸ‘
    4
  • i-campbell

    i-campbell - 2021-09-25

    Thanks for sharing, Rick!
    One other trick I have found, when the enum comes from a library (and so can't be decorated with those attributes), is to use https://store.codesys.com/fb-visu-creator.html to generate the necessary text list for conversion.

     

Log in to post a comment.