How to Declare Variables in Structured Text for PLC Programming
In Structured Text, declare variables using the
VAR block followed by the variable name, a colon, and the data type, ending with a semicolon. For example, VAR myVar : INT; declares an integer variable named myVar. Variables must be declared before use inside a program or function block.Syntax
Variables in Structured Text are declared inside a VAR block. Each variable declaration includes the variable name, a colon, the data type, and ends with a semicolon. The block is closed with END_VAR.
- VAR: starts the variable declaration section.
- variable_name: the name you choose for your variable.
- :: separates the name and type.
- data_type: the type of data the variable holds (e.g.,
INT,BOOL,REAL). - ;: ends the declaration line.
- END_VAR: ends the variable declaration section.
structured-text
VAR
myInteger : INT;
myBoolean : BOOL;
myReal : REAL;
END_VARExample
This example shows how to declare variables and assign values in Structured Text. It declares an integer and a boolean, then sets the boolean based on the integer's value.
structured-text
PROGRAM ExampleProgram
VAR
counter : INT;
isActive : BOOL;
END_VAR
counter := 10;
isActive := counter > 5;Output
counter = 10
isActive = TRUE
Common Pitfalls
Common mistakes when declaring variables in Structured Text include:
- Forgetting the
VARandEND_VARkeywords around declarations. - Missing semicolons at the end of each declaration line.
- Using invalid variable names (e.g., starting with a number or using spaces).
- Not declaring variables before using them in code.
Always check your syntax carefully to avoid these errors.
structured-text
(* Wrong: Missing END_VAR and semicolon *)
VAR
temp INT
(* Correct: Proper declaration *)
VAR
temp : INT;
END_VARQuick Reference
| Element | Description | Example |
|---|---|---|
| VAR | Starts variable declarations | VAR |
| variable_name | Name of the variable | counter |
| : | Separates name and type | : |
| data_type | Type of variable | INT, BOOL, REAL |
| ; | Ends declaration line | ; |
| END_VAR | Ends variable declarations | END_VAR |
Key Takeaways
Always declare variables inside a VAR...END_VAR block before using them.
Each variable declaration must include a name, colon, data type, and semicolon.
Use valid variable names starting with letters and no spaces.
Common errors include missing semicolons and forgetting END_VAR.
Structured Text supports common data types like INT, BOOL, and REAL.