ST instruction WHILE
Like the FOR loop, the WHILE loop is used to execute instructions repeatedly until the termination condition applies. The termination condition of a WHILE loop is a Boolean expression.
Syntax:
WHILE <boolean expression> DO
<instructions>
END_WHILE;
TwinCAT executes the <instructions> repeatedly as long as the Boolean expression <boolean expression> returns TRUE. If the Boolean expression is FALSE at the first evaluation, then TwinCAT never executes the instructions. If the Boolean expression never takes the value FALSE, the instructions are repeated continuously, causing a runtime error.
Example:
WHILE nCounter <> 0 DO
nVar1 := nVar1*2
nCounter := nCounter-1;
END_WHILE;
You must ensure programmatically that no infinite loop is created. |
The WHILE and REPEAT loops are, in a sense, more powerful than the FOR loop, since you do not need to know the number of iterations before you run the loop. In some cases, it is thus only possible to work with these two types of loops. However, if the number of iterations is known, a FOR loop is preferable to avoid infinite loops.
In addition to the IEC 61131-3 standard, you can use the CONTINUE instruction within the WHILE loop.
See also: