14Control flow
The FOR loop and the watchdog
FOR ... TO ... BY ... DO, counting up and down, and why a long loop drops the controller into a fatal fault.
The construct
FOR i := 1 TO 10 DO
Sum := Sum + i;
END_FORThe loop counter i is an integer you declare in VAR. The loop starts at 1, runs the body, adds one, and stops once the counter passes 10. So 10 is included.
The BY step
FOR i := 0 TO 100 BY 2 DO (* even numbers only: 51 iterations *)
FOR i := 10 TO 1 BY -1 DO (* counting down *)The default step is 1. To count down the step must be negative, otherwise the loop body never executes at all.
The bounds are read once
Start, end and step are evaluated when the loop is entered. Changing them in the body does not extend the loop:
FOR i := 1 TO N DO
N := 1000; (* no effect: the iteration count is already fixed *)
END_FORAnd do not rely on the counter's value after END_FOR. Some vendors leave it at the limit plus the step, others at the limit.
What FOR is good for in a PLC
- One operation repeated over 64 motors or 200 valves.
- A sum, an average or a maximum over a set of values.
- Searching a recipe table.
- Numeric approximation: several passes of an iterative formula in one scan.
And why you should fear it
The whole program must finish inside one scan cycle. If the cycle is 10 ms and the loop body costs 2 microseconds:
Iterations | Time |
|---|---|
100 | 0.2 ms |
1,000 | 2 ms |
10,000 | 20 ms |
1,000,000 | 2 seconds |
At 10,000 we are already past the cycle time. At a million the controller stops: the watchdog sees that the scan did not finish in the allowed time, raises a fatal fault, and drops every output. In a real plant that is a stopped line and a phone call at three in the morning.
The lab on this site mimics it: any loop that runs more than 10,000 iterations in one scan is aborted with an error. Try it, then remember that a real PLC would have faulted instead.
How to handle it
- Keep the upper bound a known constant, not a variable an HMI can write.
- Spread heavy work across scans: do twenty items per scan, remember where you were, resume next scan.
Last := Cursor + 20;
FOR i := Cursor TO Last DO
(* only twenty items in this scan *)
END_FOR
Cursor := Cursor + 21;
IF Cursor > 999 THEN Cursor := 0; END_IF- Put heavy maths in a slow task, every 500 ms rather than every 10 ms.
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 Sum: 1 to 10 adds up to 55, so L1 lights.
- Turn S1 on: Sum becomes 5050 and L2 lights. Turn S2 on: 500500 and L3 lights.
- Watch EXEC at the top: execution time grows with the loop length.
- Change 1000 to 20000 and download again: the program stops on a watchdog error because the loop ran too long.
Terms in this lesson
People find this lesson by searching
FOR loop structured textEND_FOR stplc watchdog timeout loopfor loop plc programmingBY step for loop stscan time overrun plcsplit work across scans 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