0
0
FreertosHow-ToBeginner · 3 min read

How to Use While Loop in Structured Text for PLC Programming

In Structured Text, use the WHILE loop to repeat a block of code as long as a condition is true. The syntax starts with WHILE condition DO, followed by the loop body, and ends with END_WHILE. This loop is useful for repeating tasks until a condition changes.
📐

Syntax

The WHILE loop runs the code inside it repeatedly while the condition is true.

  • WHILE condition DO: Starts the loop and checks the condition.
  • Statements: Code to run each time the condition is true.
  • END_WHILE: Ends the loop.
structured-text
WHILE condition DO
    (* statements to execute *)
END_WHILE
💻

Example

This example counts from 1 to 5 using a WHILE loop and stores the count in a variable.

structured-text
VAR
    counter : INT := 1;
END_VAR

WHILE counter <= 5 DO
    (* Output the current counter value *)
    counter := counter + 1;
END_WHILE
Output
After loop ends, counter = 6
⚠️

Common Pitfalls

Common mistakes when using WHILE loops include:

  • Not changing the condition inside the loop, causing an infinite loop.
  • Using a condition that is always false, so the loop never runs.
  • Forgetting END_WHILE, causing syntax errors.
structured-text
(* Wrong: Infinite loop because counter is not updated *)
VAR
    counter : INT := 1;
END_VAR

WHILE counter <= 5 DO
    (* Missing counter := counter + 1; *)
END_WHILE

(* Correct: Update counter inside the loop *)
VAR
    counter : INT := 1;
END_VAR

WHILE counter <= 5 DO
    counter := counter + 1;
END_WHILE
📊

Quick Reference

Remember these tips for using WHILE loops in Structured Text:

  • Always ensure the loop condition will eventually become false.
  • Update variables inside the loop that affect the condition.
  • Use WHILE loops for unknown iteration counts.
  • Use FOR loops if the number of iterations is known.

Key Takeaways

Use WHILE condition DO ... END_WHILE to repeat code while a condition is true.
Always update variables inside the loop to avoid infinite loops.
The loop body runs zero or more times depending on the condition.
Use WHILE loops when the number of iterations is not fixed.
Remember to close the loop with END_WHILE to avoid syntax errors.