Variables & Data Types
Variables are the foundation of any Structured Text program. Understanding how to declare, initialize, and use different data types is essential for effective ST programming.
๐ Enhance Your Development Experience
Get syntax highlighting, IntelliSense, and debugging support for Structured Text:
Install VS Code Extension โVariable Declaration
Variables must be declared before use within VAR blocks. The basic syntax is:
Variable Declaration Syntax
Basic Data Types
Boolean Types
Values: TRUE, FALSE
Size: 1 bit
Use: Digital signals, flags, conditions
Integer Types
SINT: -128 to 127 (8-bit)
INT: -32,768 to 32,767 (16-bit)
DINT: -2ยณยน to 2ยณยน-1 (32-bit)
UINT: 0 to 65,535 (16-bit unsigned)
Real (Floating Point) Types
REAL: 32-bit floating point
LREAL: 64-bit floating point
Range: ยฑ1.175e-38 to ยฑ3.402e+38 (REAL)
String Types
STRING: Variable-length text
STRING(n): Fixed maximum length
Default length: Usually 80 characters
Time Data Types
Time Data Types
Time Format Examples
T#5s or TIME#5s - 5 secondsT#1m30s - 1 minute 30 secondsT#2h15m - 2 hours 15 minutesT#100ms - 100 millisecondsD#2024-12-25 - December 25, 2024TOD#14:30:45 - 2:30:45 PMVariable Initialization
โ Good Practices
โ Potential Issues
Arrays
Arrays allow you to store multiple values of the same type:
Array Declaration and Usage
Structures (User-Defined Types)
Structures allow you to group related data together:
Structure Definition and Usage
Variable Scope and Storage Classes
| Declaration | Scope | Persistence |
|---|---|---|
| VAR | Local to program/function | Lost on power cycle |
| VAR_GLOBAL | Accessible from anywhere | Lost on power cycle |
| VAR_RETAIN | Local to program/function | Retained through power cycle |
| VAR_INPUT | Function/FB input parameter | Parameter passing |
| VAR_OUTPUT | Function/FB output parameter | Parameter passing |
Example of Different Variable Scopes
Variable Scopes Example
Type Conversion
ST provides explicit type conversion functions for safe data type changes:
Type Conversion Examples
โ ๏ธ
Type Conversion Safety
Always use explicit type conversion functions rather than relying on implicit conversions:
- โข Check for potential data loss (e.g., REAL to INT truncates)
- โข Validate string-to-number conversions for invalid input
- โข Consider range limits when converting between integer types
Common Patterns and Best Practices
โ Naming Conventions
๐ก Initialization Tips
๐ Next Steps
Now that you understand variables and data types, explore:
