FOR Statement
Help Contents
- Fernhill SCADA
- Help
- IEC 61131-3 Scripts
- Structured Text (ST)
- FOR Statement
Introduction
The IEC 61131-3 ST FOR statement executes a list of statements a defined number of times.
The FOR statement has this syntax:
FOR variable := start-value TO end-value [ BY step-value ] DO
statement;
statement;
..
statement;
END_FOR;
Where:
- variable declares a variable that increases (or decreases) on each loop iteration.
variable is any Variable Reference that refers to an ANY_INTEGRAL value.
- start-value declares the starting value of the loop variable.
start-value is any Expression returning a value compatible with variable.
- end-value declares the final value of the loop variable.
end-value is any Expression returning a value compatible with variable.
- step-value is optional. When used it declares how much is added to the loop variable on each loop iteration.
If not used a step value of 1 is assumed.
step-value is any constant Expression returning a value compatible with variable.
- statement declares a statement to execute inside the loop.
statement is any Structured Text Statement.
Execution Logic
The FOR Loop uses this logic to execute statements:
- The start-value is written to the variable.
- The variable is compared with the end-value.
- If the loop has finished, steps 4, 5 and 6 are skipped. Execution continues with the next statement after the END_FOR keyword.
- Each statement inside the loop is executed in order.
- The step-value is added to the variable.
- Execution continues with Step 2.
The condition used to end the loop depends on whether the step value is positive or negative:
- If the step value is positive, the loop finishes when variable is greater than the end-value.
- If the step value is negative, the loop finishes when variable is less than the end-value.
To stop the FOR loop early (before the loop variable reaches its target value) use the EXIT Statement.
Examples
-
Execute code in a loop 6 times:
VAR
Item : ARRAY[0..5] OF LREAL;
Sum : LREAL;
Index : INT;
END_VAR
Sum:= 0;
FOR Index := 0 TO 5 DO
Sum := Sum + Item[ Index ];
END_FOR;
Note: When completed the Index loop variable will be 6.
Standards Compliance
IEC 61131-3 Second Edition: Table 56.6.
IEC 61131-3 Third Edition: Table 72.6.
Further Information
Structured Text
For other Structured Text (ST) statement types.
Variable Reference
To learn about variable references that can be used for the
variable.
Expressions
To learn about expressions that can be used for
start-value, end-value, and step-value.
Glossary
For the meaning of terms used in Fernhill SCADA.