Skip to main content

ST Statement: FOR

The FOR loop is used to execute statements 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 than – or in the case of negative increment step less than – the <end value>. This is checked before the execution of the <instructions>.

Every time the <instructions> statement 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 71. 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> must not get 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, then an infinite loop results. For example, an infinite 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 statement within the FOR loop.