how to create an Enum in ST (TC3)

#PLC #TwinCAT3 #Beckhoff

Learn more at Part 4 - Data types & arrays (IEC 61131-3)

1) Example

TYPE E_Color :
(
	Red := 0,
	Green := 1,
	Blue := 2,
) USINT;
END_TYPE
PROGRAM MAIN
VAR
	eLightTower : E_Color;	
END_VAR

--------------------------------------------------------------------------

eLightTower := E_Color.Red;

2) Documentation

2.1) What are Enums?

An enumeration is a user-defined type that consists of a set of named integral constants that are known as enumerators.
150

With enumerations it's possible to basically put some description to the data, without having to put comments in the code.

An enumeration consists of:

  1. an identifier, which you use when you instantiate the enumeration
    150

  2. Next, we have an enumeration list, in where you define the different values that the enumeration can have.
    300

An enumeration has by default a base type of INT, that is the 2 byte integer. By default and implicitly, the first value is assigned the integer value of 0, and then next one is 1 etc. You can assign other values explicitly
150

  1. Next we have the optional type. If this is not provided, the enumeration will implicitly have a base type of INTEGER.
    300

You declare a enumeration variable by defining a name for it, just as with any other variable, colon and then the enumeration identifier. Then you can assign any of the enumeration values to the variable by using the enumeration identifier DOT and the enumeration value.

Thanks to IntelliSense in Visual Studio, if you enter the identifier, you get all the different enumeration options visible

All enumeration types are globally accessible, which is in contrast to for example C++ where you can define an enumeration to be only accessible in the scope of where it was declared.

More info
Convert Unscoped Enum to Scoped Enum

So, once you create an enumeration, the enumeration type is accessible from everywhere in your program.

Although this has its advantages, it can also be disadvantageous especially when you start to work with libraries.

When you have lots of enumerations available, you can get something called namespace pollution in where two enumerations in two separate libraries but with the same name are used in a project.

Many of you ask the question:
"But why not use comments next to the integer or whatever data type I'm using instead?"
-- Code should be self-explanatory. With comments you just add something else that needs to be maintained and that most likely will be wrong after the code has been changed.

2.2) How to create Enums?

To create an enumeration, right click on DUTs, select Add, then click on DUT.
500

This will bring up a new window, in where you can define new DUTs, that is Data Unit Types.
250

Write the name, that is the identifier in the NAME textbox. Make sure ENUMERATION radio box is selected. Click "Open"

Your enumeration is created. Now you can fill in the enumeration list