Arrays are some of the commonly used data structures in Codesys. They are used to store data of the same type. Grouping data of the same type in the same container makes it easy to manage, access and modify it.
Arrays within a Program Unit (POU) must be declared at compile time and must have a static dimension and length, therefore their dimension cannot be changed at runtime. However, function blocks, methods, and functions can use arrays of variable length which can be used as VAR_IN_OUT Variables.
In Codesys, you can use arrays of 0ne, two or three Dimensions. To declare an array, you must specify its datatype, its dimension and size. Here is how to do an array declaration in Codesys
Declare a one dimension array of Integers of Length 6
arr1 : ARRAY [1..6] OF INT
Declare two Dimension array of Booleans, of length 5
arr2 : ARRAY [1..5, 1...5] OF BOOL
Some times you want to initialize an array at declaration, such that the array has some defaults values. This can be achieved in the following way
Declare and initialize an array of Integers
arr1 : ARRAY [1..6] OF INT := [1,2,3,4,5,6]
As you can see, we have declared an array and initialized each element of the array with a desired value. This is a good approach but it can be frustration if you have arrays of 10’s or 100’s of elements. Let us assume you have an array of length 100 and you want to initialize all the elements to value 2. Here is how you would do it.
Declare and array of Integers of length 100
arr1 : ARRAY [1..100] OF INT
Declare and initialize an array of Integers of length 100, initializing every element to 2
arr1 : ARRAY [1..100] OF INT := [100(2)]
Declare and initialize an array of Integers of length 100, initializing first 10 element to 2 and the rest to 3
arr1 : ARRAY [1..100] OF INT := [10(2), 90(3)]