FOR Loops
Part of the Structured Text section of Coddy's PLC Programming journey. Lesson 12 of 17.
A FOR loop runs the same statements several times in one scan, counting with a variable:
Total := 0;
FOR i := 1 TO 4 DO
Total := Total + i;
END_FOR;Here i is 1, then 2, 3 and 4, so Total ends at 1 + 2 + 3 + 4 = 10. Set Total back to 0 before the loop: the program runs again every scan, and without that line Total would keep growing.
WHILE cond DO ... END_WHILE; is the other loop: it repeats while cond is TRUE. Both loops run inside one scan. Inputs are read only between scans, so a loop can never wait for a button or a sensor: it would never end. The PLC's watchdog notices a scan that takes too long and stops the PLC with every output off. Loop over a fixed range, never until something happens.
In real programs FOR mostly walks through an ARRAY, a list of values in one variable. This simulator has no arrays, so here it adds up numbers.
Challenge
MediumBox scoring: the first box scores 1 point, the second 2, the third 3, and so on. The counter C1 counts the boxes. Add a FOR loop that sums the scores from 1 to C1.CV into Total.
Press Run, try it on the machine, then Check.
Try it yourself
VAR
C1 : CTU;
i : INT;
Total : INT;
END_VAR
Belt := (Start OR Belt) AND Stop;
C1(CU := Entry, PV := 100);
// Sum 1 to C1.CV into Total here
Display := Total;
All lessons in Structured Text
Practice on your own: PLC playground