Search code examples
plctwincatcodesys

Get String value of a Enum in Twincat 3


In Twincat 3 I have a Enum like this:

TYPE ENUM_FUNCTIONS :
(
EMPTY                       :=0,    
MOTOR_SPEED_INPUT_1         :=1,
MOTOR_SPEED_INPUT_2         :=2,
MAIN_SHAFT_SPEED_MONITOR_3  :=3,
MAIN_SHAFT_SPEED_MONITOR_1  :=4,
MAIN_SHAFT_SPEED_MONITOR_2  :=5
);
END_TYPE

Is there any way to get the String value of the Enum??

For example, use ENUM_FUNCTIONS[5] and get the value MAIN_SHAFT_SPEED_MONITOR_2


Solution

  • Yes. See here how to do it (only available since TwinCAT 3.1.4024.x or CODESYS 3.5.14.0)

    TL;DR, in short, use the to_string attribute on the Enum and TO_STRING function to get the string:

    {attribute 'to_string'}
    TYPE ENUM_FUNCTIONS :
    ...
    END_TYPE
    
    myEnum: ENUM_FUNCTIONS;
    str: STRING := TO_STRING(myEnum);