Skip to main content

ST Statement: WHILE

The WHILE loop is used like the FOR loop in order to execute statements several times until the abort condition occurs. The abort condition of a WHILE loop is a Boolean expression.

Syntax:

WHILE <boolean expression> DO
  <instructions>
END_WHILE;

CODESYS repeatedly executes the <instructions> statements for as long as the <Boolean expression> returns TRUE. If the Boolean expression is already FALSE at the first evaluation, then CODESYS never executes the statements. If the Boolean expression never applies the value FALSE, then the statements are repeated endlessly, as a result of which a runtime error results.

Example 73. Example
WHILE iCounter <> 0 DO
  Var1 := Var1*2
  iCounter := iCounter-1;
END_WHILE;


Important

You must use programming to make sure that no infinite loops are caused.

In a certain sense the WHILE and REPEAT loops are more powerful than the FOR loop, since you don't need to already know the number of executions of the loop before its execution. In some cases it is thus only possible to work with these two kinds of loop. However, if the number of loop executions is clear, then a FOR loop is preferable in order to avoid infinite loops.

As an extension to the IEC 61131-3 standard you can use the CONTINUE statement within the WHILE loop.