IF - THEN - ELSIF - ELSE
The IF-THEN-ELSIF-ELSE statement enables you to execute different Logic statements based on the value of an input, for example, to control the value of an item based on the value of another item. The ELSIF part of the statement combines ELSE and IF.
The IF-THEN-ELSIF-ELSE statement avoids nesting of IF - THEN - ELSE statements. It makes statements simpler when the result depends on three or more different values of the input. You can have more than one ELSIF between IF-THEN and ELSE.
You need to enter IF-THEN-ELSIF-ELSE statements in the following order:
- IF expression1 THEN
- statements1;
- ELSIF expression2 THEN
- statements2;
- ELSE
- statements3;
- END_IF;
where <statements> is any block of valid ST code.
The expressions are evaluated in order, and when a TRUE expression is found, the statement is executed. The statements after ELSE are executed if no expression evaluates to TRUE.
Example:
- IF Level > 75 THEN
- Pump1 := TRUE;
- Pump2 := TRUE;
- ELSIF Level > 50 THEN
- Pump1 := TRUE;
- Pump2 := FALSE;
- ELSE
- Pump1 := FALSE;
- Pump2 := FALSE;
- END_IF;
In this Logic, there are 2 pumps (Pump 1 and Pump 2) and the program uses the values of an input called Level to control the state of these pumps:
- When the value of Level is greater than 75, both pumps are set to TRUE (both pumps are on).
- When the value of Level is less than 75 but greater than 50, Pump 1 is set to TRUE (on) and Pump 2 is set to FALSE (off).
- When the value of Level is less than or equal to 50, both of the pumps are set to FALSE (off).
For a related statement, see IF - THEN - ELSE.