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.
WHILE: test, then run
WHILE Rest >= Dose DO
Rest := Rest - Dose;
Shots := Shots + 1;
END_WHILEThe 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_REPEATThe 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 |
|---|---|
| leave the current loop immediately |
| abandon this pass, start the next |
| 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_FORRETURN 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_WHILELevel 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_WHILEWhatever 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 |
|---|---|
| |
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 | |
Unknown but bounded by the maths | |
Must run at least once | |
Waiting for a field event | no loop at all: |
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
- Run the program and watch Shots: how many doses still fit in the tank.
- Press START: as the level rises Shots comes down, and the lamp lights at two doses or fewer.
- 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
- 01What is Structured Text, and when to use it instead of ladder
- 02How a PLC runs your code: the scan cycle and the process image
- 03Program structure: POUs, PROGRAM, FUNCTION and FUNCTION_BLOCK
- 04Your first program: starting a pump with seal-in logic
- 05Data types: BOOL, INT, REAL, TIME and the rest
- 06Declaring variables: VAR, VAR_INPUT and RETAIN
- 07Literals and constants: 16#FF, 2#1010 and T#5s
- 08Type conversion and scaling a 4-20 mA signal
- 09Assignment and arithmetic in ST: := and operator precedence
- 10Boolean logic, comparisons and bit operations
- 11Standard functions: ABS, SQRT, MIN, MAX, LIMIT, SEL, MUX
- 12IF, ELSIF and ELSE: the rules and when to avoid them
- 13The CASE statement and your first state machine
- 14The FOR loop and the watchdog
- 15WHILE, REPEAT, EXIT, CONTINUE and RETURN
- 16Edge detection: R_TRIG, F_TRIG and the "it fired every scan" bug
- 17Timers: TON, TOF and TP
- 18Counters: CTU, CTD and CTUD
- 19SR and RS flip-flops: which one wins
- 20Writing your own function
- 21Writing a function block
- 22Arrays in Structured Text
- 23Structs and enumerations
- 24References and pointers
- 25The state machine pattern: a batch sequence that cannot get stuck
- 26Alarm management to ISA-18.2: delay, deadband, latch, acknowledge, first-out
- 27Analogue signal processing: counts to engineering units, NE43 and filtering
- 28Closed-loop control in ST: hysteresis first, then a practical PID
- 29Motors and valves in practice: permissives, feedback and travel time
- 30The same ST on every platform: SCL, Studio 5000, CODESYS, TwinCAT
- 31Testing and debugging ST: the watch table, forcing and simulation
- 32An ST style guide: naming, comments, constants and version control
- 33Final project: a complete tank station with a state machine and alarms
- 3420 interview questions on ST and PLC programming, with answers