How to Use If Else in Structured Text for PLC Programming
In Structured Text, use
IF to check a condition and ELSE to run code when the condition is false. The syntax is IF condition THEN ... ELSE ... END_IF; to control program flow based on conditions.Syntax
The IF statement checks a condition. If true, it runs the code after THEN. If false, it runs the code after ELSE. The statement ends with END_IF;.
- IF: starts the condition check
- condition: a true/false expression
- THEN: code to run if condition is true
- ELSE: code to run if condition is false (optional)
- END_IF;: ends the if statement
structured-text
IF condition THEN
(* code if true *)
ELSE
(* code if false *)
END_IF;Example
This example checks if a temperature is above 30 degrees. If yes, it sets a fan to ON; otherwise, it sets the fan to OFF.
structured-text
VAR
temperature : INT := 35;
fan : BOOL := FALSE;
END_VAR
IF temperature > 30 THEN
fan := TRUE;
ELSE
fan := FALSE;
END_IF;Output
fan = TRUE
Common Pitfalls
Common mistakes include forgetting END_IF;, missing THEN, or using assignment = instead of comparison =:= in some PLCs. Also, not using parentheses for complex conditions can cause errors.
structured-text
(* Wrong: Missing THEN and END_IF *) IF temperature > 30 fan := TRUE ELSE fan := FALSE (* Correct: *) IF temperature > 30 THEN fan := TRUE; ELSE fan := FALSE; END_IF;
Quick Reference
| Keyword | Purpose |
|---|---|
| IF | Start condition check |
| THEN | Code to run if condition is true |
| ELSE | Code to run if condition is false (optional) |
| END_IF | End the if statement |
Key Takeaways
Use IF ... THEN ... ELSE ... END_IF; to control flow based on conditions in Structured Text.
Always include END_IF; to close the if statement.
Use comparison operators correctly and include THEN after the condition.
ELSE is optional but useful for handling false conditions.
Parentheses help clarify complex conditions and avoid errors.