0
0
FreertosHow-ToBeginner · 3 min read

How to Use For Loop in Structured Text for PLC Programming

In Structured Text, use the FOR loop to repeat a block of code a fixed number of times. The syntax is FOR variable := start TO end DO ... END_FOR; where the loop variable changes from start to end. This helps automate repetitive tasks in PLC programs.
📐

Syntax

The FOR loop in Structured Text repeats code between DO and END_FOR; a set number of times. The loop variable is assigned a start value and increments by 1 until it reaches the end value.

  • variable: loop counter (usually an integer)
  • start: initial value of the counter
  • end: final value of the counter
  • DO ... END_FOR;: block of code to repeat
structured-text
FOR i := 1 TO 5 DO
    (* code to repeat *)
END_FOR;
💻

Example

This example shows a FOR loop that counts from 1 to 5 and stores the sum of these numbers in a variable.

structured-text
VAR
    i : INT;
    sum : INT := 0;
END_VAR

FOR i := 1 TO 5 DO
    sum := sum + i;
END_FOR;
Output
sum = 15
⚠️

Common Pitfalls

Common mistakes include:

  • Using a loop variable that is not declared or has the wrong type.
  • Forgetting the END_FOR; statement to close the loop.
  • Modifying the loop variable inside the loop body, which can cause unexpected behavior.
  • Using TO with a start value greater than the end value, which results in zero iterations.
structured-text
(* Wrong: modifying loop variable inside loop *)
FOR i := 1 TO 5 DO
    i := i + 1; (* Don't do this! *)
END_FOR;

(* Correct: do not change loop variable inside loop *)
FOR i := 1 TO 5 DO
    (* safe code here *)
END_FOR;
📊

Quick Reference

ElementDescription
FOR variable := start TO end DOStart of the loop with counter variable
variableLoop counter, usually INT type
startInitial value of the counter
endFinal value of the counter
DO ... END_FOR;Code block repeated each iteration

Key Takeaways

Use FOR loops to repeat code a fixed number of times in Structured Text.
Declare the loop variable as an integer before using it in the FOR loop.
Do not modify the loop variable inside the loop body to avoid errors.
Always close the loop with END_FOR; to ensure proper syntax.
If start is greater than end, the loop will not execute any iterations.