ST Instruction ‘FOR’¶
The FOR
loop is used to execute instructions with a certain number of repetitions.
Syntax:
FOR <counter> := <start value> TO <end value> {BY <increment> } DO
<instructions>
END_FOR;
The section inside the curly parentheses {} is optional.
CODESYS executes the <instructions>
as long as the <counter>
is not greater, or - in case of negative increment - is not smaller than the <end value>
. This is checked before the execution of the <instructions>
.
Every time the instructions <instructions>
have been executed, the counter <counter>
is automatically increased by the increment <increment>
. The increment <increment>
can have any integral value. If you do not specify an increment, the standard increment is 1
.
Example
FOR iCounter := 1 TO 5 BY 1 DO
iVar1 := iVar1*2;
END_FOR;
Erg := iVar1;
If you have pre-configured iVar1
with 1
, iVar1
has the value 32
after the FOR loop.
Caution
The end value <end value> may not attain the same value as the upper limit of the data type of the counter.
If the end value of the counter is equal to the upper limit of the data type of the counter, an endless loop results. For example, an endless loop results in the above example if iCounter
is of the data type SINT
and the <end value>
equals 127
, since the data type SINT
has the upper limit 127
.
As an extension to the IEC 61131-3 standard you can use the CONTINUE
instruction within the FOR
loop.
See also