Loops – ST

The Structured Text (ST) language supports 3 kinds of loops:

  • FOR ... DO ... END_FOR: Reapeats some processing for some given iteration count
  • WHILE ... DO ... END_WHILE: Repeats some processing while a condition is true
  • REPEAT ... UNTIL ... END_REPEAT
    : Performs some processing at least once, then repeats it until some condition becomes true

Even if these instructions are defined as part of the IEC 61131 standard, their use is viewed as a bad practice and should be avoided. They extend the cycle time . They can even lead to infinite loops when inputs are used in condition expressions! A dedicated article discusses thoroughly why one should avoid these instructions, and provides an alternative solution based on counters and timers.

Nevertheless, for sake of compliance with the standard, PLC3000 supports loop instructions. The following example serves as an example.

PROGRAM demoLoops
VAR
	continue : BOOL;
	stopCount, index, maxCount : INT;
END_VAR
	continue := TRUE;
	WHILE continue  DO
		continue := FALSE;
	END_WHILE
	stopCount := 5;
	REPEAT
		stopCount := stopCount - 1;
	UNTIL stopCount = 0
	END_REPEAT
	maxCount := 0;
	FOR index := 1 TO 42 BY 3 DO
	    maxCount := maxCount + 11;
	END_FOR;
	IF maxCount < 1000 THEN
		%C0.PV := maxCount;
	ELSE
		%C0.PV := 321;
	END_IF
END_PROGRAM