IF...THEN...ELSE Statements
IF…THEN…ELSE statements drive conditional logic in Structured Text on rungs.dev. Learn syntax, ELSIF chains, and patterns for evaluating BOOL conditions every scan.
The IF statement is the primary way to implement conditional logic in Structured Text. It allows the program to make decisions based on conditions that evaluate to 1 (taken) or 0 (not taken).
Basic IF Statements
A simple IF statement executes one or more statements only when the condition evaluates to 1.
Syntax:
IF <condition> THEN
<statements>;
END_IF;Example:
IF Start_Button THEN
Motor_Start := 1;
END_IF;IF...THEN...ELSE
You can extend an IF statement with an ELSE block to handle the case where the condition evaluates to 0.
Syntax:
IF <condition> THEN
<then_statements>;
ELSE
<else_statements>;
END_IF;Example:
IF Start_Button THEN
Motor_Start := 1;
ELSE
Motor_Start := 0;
END_IF;This structure ensures the motor starts only when the button is pressed, and stops otherwise.
IF...ELSIF...ELSE
For multiple conditions, use ELSIF (else-if). This is helpful for multi-way logic.
Syntax:
IF Mode = 1 THEN
Operation := 1;
ELSIF Mode = 2 THEN
Operation := 2;
ELSE
Operation := 0;
END_IF;Each condition is evaluated in order, and only the first matching block is executed.
Notes
-
Every IF block must be closed with END_IF;
-
Each line inside the block must end with a semicolon
-
You can nest IF statements, but keep them readable
More Examples
// Turn on fan only if temperature exceeds limit
IF Temperature > Temp_Limit THEN
Fan := 1;
ELSE
Fan := 0;
END_IF;
// Set alarm mode based on pressure
IF Pressure > 100 THEN
Alarm_Mode := 2;
ELSIF Pressure < 30 THEN
Alarm_Mode := 1;
ELSE
Alarm_Mode := 0;
END_IF;Practice
Try IF/ELSE in the Select Between exercise — route one of two inputs to the output based on a switch.
Logical Operators
Logical operators AND, OR, XOR, and NOT combine BOOL expressions in Structured Text on rungs.dev, and double as bitwise operators on numeric values for masking and flag manipulation.
CASE Statements
CASE statements in Structured Text on rungs.dev select one branch from many based on a numeric expression — tidier than long IF…ELSIF chains for state machines.