How to Use Case Statement in Structured Text for PLC Programming
In Structured Text, use the
CASE statement to execute different code blocks based on the value of a variable. It works like a multi-way branch, checking the variable against multiple OF options and running the matching block. Use ELSE for a default case when no match is found.Syntax
The CASE statement evaluates a variable and executes the matching OF block. Each OF defines a possible value or range. The ELSE block runs if no values match. The statement ends with END_CASE.
- CASE: starts the case statement with the variable to check.
- OF: defines a value or range to match.
- ELSE: optional default block if no match.
- END_CASE: ends the case statement.
structured-text
CASE variable OF
value1:
(* code block 1 *)
value2..value3:
(* code block 2 for range *)
ELSE
(* default code block *)
END_CASEExample
This example shows how to use a CASE statement to set a string message based on an integer input value.
structured-text
VAR
inputValue : INT := 2;
outputMessage : STRING(20);
END_VAR
CASE inputValue OF
1:
outputMessage := 'One';
2:
outputMessage := 'Two';
3..5:
outputMessage := 'Three to Five';
ELSE
outputMessage := 'Other';
END_CASEOutput
outputMessage = 'Two'
Common Pitfalls
Common mistakes when using CASE statements include:
- Forgetting the
END_CASEto close the statement. - Not covering all possible values, which can cause unexpected behavior if
ELSEis missing. - Using overlapping ranges or duplicate values in
OFclauses, which is not allowed. - Assigning values incorrectly inside the case blocks.
structured-text
(* Wrong: Missing END_CASE *)
CASE inputValue OF
1:
outputMessage := 'One';
2:
outputMessage := 'Two';
(* Correct: *)
CASE inputValue OF
1:
outputMessage := 'One';
2:
outputMessage := 'Two';
END_CASEQuick Reference
| Keyword | Description |
|---|---|
| CASE | Starts the case statement with the variable to check |
| OF | Defines a value or range to match |
| ELSE | Optional default block if no match is found |
| END_CASE | Ends the case statement |
Key Takeaways
Use CASE to select code blocks based on a variable's value in Structured Text.
Always close the CASE statement with END_CASE to avoid syntax errors.
Include an ELSE block to handle unexpected values safely.
Avoid overlapping or duplicate values in OF clauses.
CASE statements improve readability over multiple IF-THEN-ELSE chains.