How to Use Arrays in Structured Text for PLC Programming
In Structured Text, use
ARRAY to declare a collection of elements of the same type with a fixed size. Access elements by their index using square brackets, starting at 0 or 1 depending on the PLC system. Arrays help organize multiple values efficiently in your PLC programs.Syntax
To declare an array in Structured Text, use the ARRAY keyword followed by the index range and the data type. You access elements using square brackets with the element's index.
- ARRAY[lower_bound..upper_bound] OF data_type: Declares the array size and type.
- variable[index]: Accesses an element at the given index.
structured-text
VAR myArray : ARRAY[1..5] OF INT; // Array of 5 integers END_VAR // Access example myArray[1] := 10; // Set first element value := myArray[1]; // Read first element
Example
This example shows how to declare an integer array, assign values to each element, and then sum all elements using a loop.
structured-text
PROGRAM ArrayExample VAR numbers : ARRAY[1..4] OF INT := [5, 10, 15, 20]; sum : INT := 0; i : INT; END_VAR FOR i := 1 TO 4 DO sum := sum + numbers[i]; END_FOR // sum now holds 50 END_PROGRAM
Output
sum = 50
Common Pitfalls
Common mistakes when using arrays in Structured Text include:
- Using an index outside the declared range causes runtime errors.
- Forgetting that some PLCs start array indexes at 1, not 0.
- Not initializing arrays before use, leading to unpredictable values.
Always check your PLC documentation for index base and initialize arrays properly.
structured-text
VAR arr : ARRAY[1..3] OF INT; val : INT; END_VAR // Wrong: Accessing index 0 (out of range) // val := arr[0]; // This causes error // Right: Accessing valid index val := arr[1];
Quick Reference
| Concept | Syntax/Description |
|---|---|
| Declare array | VAR myArray : ARRAY[1..10] OF INT; END_VAR |
| Access element | myArray[3] := 100; |
| Initialize array | myArray : ARRAY[1..3] OF INT := [1, 2, 3]; |
| Loop through array | FOR i := 1 TO 3 DO ... END_FOR |
| Index range | Usually starts at 1, check PLC specifics |
Key Takeaways
Declare arrays with ARRAY and specify index range and type.
Access elements using square brackets with valid indexes.
Initialize arrays to avoid unpredictable values.
Check your PLC's index base (0 or 1) to prevent errors.
Use loops to process array elements efficiently.