Skip to content

15Control flow

WHILE, REPEAT, EXIT, CONTINUE and RETURN

Unbounded loops and the jump statements, why WHILE is dangerous inside a controller, and how a guard counter makes it safe.

Lesson 15 of 3412 minIEC 61131-3

WHILE: test, then run

WHILE Rest >= Dose DO
  Rest := Rest - Dose;
  Shots := Shots + 1;
END_WHILE

The condition is tested before every pass, so a condition that is false at the start means the body never runs. Use it when the iteration count is not known in advance.

REPEAT: run, then test

REPEAT
  Guess := (Guess + Value / Guess) / 2.0;
  Count := Count + 1;
UNTIL ABS(Guess * Guess - Value) < 0.01 OR Count >= 20
END_REPEAT

The body runs at least once, then the condition is tested. Note the inverted sense: REPEAT runs until the condition becomes true, WHILE runs while it stays true.

Jump statements

Statement

What it does

EXIT;

leave the current loop immediately

CONTINUE;

abandon this pass, start the next

RETURN;

leave the whole POU

FOR i := 1 TO 200 DO
  IF Ids[i] = Wanted THEN
    Found := i;
    EXIT;                 (* found it, no point checking the rest *)
  END_IF
END_FOR

RETURN is most useful as a gate at the top of a program: if the conditions are not right, do nothing.

IF NOT Enabled OR Faulted THEN
  Pump := FALSE;
  RETURN;
END_IF
(* everything below runs only while the enable holds *)

CONTINUE is not available on every vendor, and an IF wrapping the body usually says the same thing more clearly.

Why WHILE is dangerous

A FOR loop has known bounds on entry, so the worst it can be is slow. A WHILE loop is bounded by a condition, and if the condition never goes false the loop never ends, the scan never ends, and the watchdog stops the controller. The classic disaster:

WHILE Level < 50.0 DO       (* disaster *)
  Pump := TRUE;
END_WHILE

Level is a field input, taken from the input image, which does not refresh mid-scan. It will never change inside the loop, and Pump has not reached the output yet either. The controller will fault. Never wait on a field input inside a loop. Waiting in a PLC is written as a state machine, not as a loop.

How to bound a WHILE

Put a guard counter into the condition itself. Two lines turn a dangerous loop into one that is guaranteed to end:

Guard := 0;
WHILE Rest >= Dose AND Guard < 50 DO
  Rest  := Rest - Dose;
  Guard := Guard + 1;
END_WHILE

Whatever the data does, the loop ends after 50 passes at most. And if you want to know whether it ended on the guard rather than on the real condition, test Guard >= 50 afterwards and raise a diagnostic flag.

What runs in the lab

Runs

Does not run

WHILE ... DO ... END_WHILE

REPEAT, EXIT, CONTINUE, RETURN

This lesson's program uses WHILE only, with a guard. The REPEAT, EXIT and RETURN blocks above are there to read and to take into your vendor's environment.

Which loop do I pick?

Situation

Tool

Iteration count known

FOR

Unknown but bounded by the maths

WHILE with a guard

Must run at least once

REPEAT with a guard

Waiting for a field event

no loop at all: CASE and a state machine

Try it in the lab

The lab runs in your browser: an ST editor, a virtual process that suits the lesson, the same program as a live ladder diagram, a watch table, and export to Siemens SCL.

What to try

  1. Run the program and watch Shots: how many doses still fit in the tank.
  2. Press START: as the level rises Shots comes down, and the lamp lights at two doses or fewer.
  3. Change 7.5 to 0.0 in both lines: without the Guard the loop would never end; with it, it stops at 50.

People find this lesson by searching

WHILE loop structured textREPEAT UNTIL structured textEXIT statement plcRETURN structured textinfinite loop plc watchdogCONTINUE statement stbounded while loop plc

Course outline

  1. 01What is Structured Text, and when to use it instead of ladder
  2. 02How a PLC runs your code: the scan cycle and the process image
  3. 03Program structure: POUs, PROGRAM, FUNCTION and FUNCTION_BLOCK
  4. 04Your first program: starting a pump with seal-in logic
  5. 05Data types: BOOL, INT, REAL, TIME and the rest
  6. 06Declaring variables: VAR, VAR_INPUT and RETAIN
  7. 07Literals and constants: 16#FF, 2#1010 and T#5s
  8. 08Type conversion and scaling a 4-20 mA signal
  9. 09Assignment and arithmetic in ST: := and operator precedence
  10. 10Boolean logic, comparisons and bit operations
  11. 11Standard functions: ABS, SQRT, MIN, MAX, LIMIT, SEL, MUX
  12. 12IF, ELSIF and ELSE: the rules and when to avoid them
  13. 13The CASE statement and your first state machine
  14. 14The FOR loop and the watchdog
  15. 15WHILE, REPEAT, EXIT, CONTINUE and RETURN
  16. 16Edge detection: R_TRIG, F_TRIG and the "it fired every scan" bug
  17. 17Timers: TON, TOF and TP
  18. 18Counters: CTU, CTD and CTUD
  19. 19SR and RS flip-flops: which one wins
  20. 20Writing your own function
  21. 21Writing a function block
  22. 22Arrays in Structured Text
  23. 23Structs and enumerations
  24. 24References and pointers
  25. 25The state machine pattern: a batch sequence that cannot get stuck
  26. 26Alarm management to ISA-18.2: delay, deadband, latch, acknowledge, first-out
  27. 27Analogue signal processing: counts to engineering units, NE43 and filtering
  28. 28Closed-loop control in ST: hysteresis first, then a practical PID
  29. 29Motors and valves in practice: permissives, feedback and travel time
  30. 30The same ST on every platform: SCL, Studio 5000, CODESYS, TwinCAT
  31. 31Testing and debugging ST: the watch table, forcing and simulation
  32. 32An ST style guide: naming, comments, constants and version control
  33. 33Final project: a complete tank station with a state machine and alarms
  34. 3420 interview questions on ST and PLC programming, with answers