Using the VAR List to Access Direct Variables
For ST programs, you need to define direct variables in a VAR variables list. The variables list comes after the PROGRAM keyword and uses this syntax:
- VAR
- <Name of variable> AT <AccessType>: <Type of variable>;
- END_VAR
Example:
- VAR
- Input AT %I(..TemperatureSensor.CurrentValueFormatted): STRING;
- END_VAR;
In this example, the variable value is a read only value (indicated by %I). It is read from the CurrentValueFormatted tag of the TemperatureSensor database item. The reference to the TemperatureSensor item is relative—the two periods indicate the levels in the hierarchy.
The %I code is used to indicate that the variable is read only. Read Only is one of three possible access types for variables:
Characters | Access Type |
---|---|
%I |
Read Only |
%Q |
Write Only |
%M |
Read and Write |
When you reference a database item in a Structured Text program, you can specify a field or leave the program to reference the default field for the database item. For example, if you do not specify a field for a point, the CurrentValueFormatted field is referenced.
You can specify which field is referenced by adding the name of the required field to the end of the item's path. You have to place a period between the end of the path and the name of the field, for example:
- Desc AT %I(.Valve.Position.CurrentStateDesc) :STRING;
In this example, the CurrentStateDesc field is referenced and is used for a read-only string value.
NOTE: Direct variables need to be separated from internal variables, constants and function blocks in the VAR lists.
For more information on data types such as STRING, please refer to Built-In Data Types. You can also create custom data types that allow you to define meaningful names for value types (see Derived Data Types).
For information on Logic keywords that you can use to control the behavior of the program, such as IF and THEN, see Controlling the Flow of the Program.
Example: Reading a Point Value and Writing it to Another Point
In this example, an ST program is used to read the current value of a point named 'TemperatureSensor1'. The value that is read is then written to the current value of a point named ‘TemperatureSensor2'.
- PROGRAM ReadTempWriteTemp
- VAR
- Input AT %I(TemperatureSensor1.CurrentValue): INT;
- Output AT %M(TemperatureSensor2.CurrentValue): INT;
- END_VAR;
- Output:=Input;
- VAR
- END_PROGRAM
The %I is used to read a value from the database and %M is used to write a value to the database (%M can be used to both read and write).