ST Instruction ‘WHILE’

The WHILE loop is used like the FOR loop in order to execute instructions 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> 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 instructions. If the boolean expression never adopts the value FALSE, then the instructions are repeated endlessly, as a result of which a runtime error results.

Example

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

Attention

You must ensure by programming means that no endless 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. If the number of executions of the loop is clear, however, then a FOR loop is preferable in order to avoid endless loops.

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

See also