Sei sulla pagina 1di 400

ClearSCADA 2010 R3

Guide to Logic
A ClearSCADA Reference Guide
07/2012

PD-6017.18

This document and attachments contain confidential information and is


to be treated as Commercial-In-Confidence.
Copying or disclosure to a third party is prohibited without prior consent
in writing from Schneider Electric.

www.schneider-electric.com

The information provided in this documentation contains general descriptions and/or technical characteristics of
the performance of the products contained herein. This documentation is not intended as a substitute for and is not
to be used for determining suitability or reliability of these products for specific user applications. It is the duty of
any such user or integrator to perform the appropriate and complete risk analysis, evaluation and testing of the
products with respect to the relevant specific application or use thereof. Neither Schneider Electric nor any of its
affiliates or subsidiaries shall be responsible or liable for misuse of the information contained herein. If you have any
suggestions for improvements or amendments or have found errors in this publication, please notify us.
No part of this document may be reproduced in any form or by any means, electronic or mechanical, including
photocopying, without express written permission of Schneider Electric.
All pertinent state, regional, and local safety regulations must be observed when installing and using this product.
For reasons of safety and to help ensure compliance with documented system data, only the manufacturer should
perform repairs to components.
When devices are used for applications with technical safety requirements, the relevant instructions must be
followed.
Failure to use Schneider Electric software or approved software with our hardware products may result in injury,
harm, or improper operating results.
Failure to observe this information can result in injury or equipment damage.
2005, 2012 Schneider Electric. All rights reserved.

PD-6017 07/2012

Table of Contents

Safety Information .........................................................................................9


About the Guide...........................................................................................11
1

Welcome to the Guide to Logic..................................................................13

Working with Logic Programs....................................................................15


Supported Logic Languages ................................................................................................. 16
How Logic Programs Work.................................................................................................... 18
Choosing a Logic Program.................................................................................................... 19
Using Outputs as Inputs (Feedback Loops) in Logic Programs.......................................... 20
Execution Order for Logic Programs ..................................................................................... 21
Troubleshooting Logic Programs........................................................................................... 25

Characters for Use in Logic .......................................................................27


Restricted Character Set - Logic........................................................................................... 27

ST Programs ................................................................................................29
Create an ST Program in the ClearSCADA Database ........................................................... 31
Edit an ST Program ............................................................................................................... 32
Understanding the Basic Structure of an ST Program .......................................................... 34
Statements, Expressions and Operators............................................................................... 37
Statements ..................................................................................................................... 37
Expressions .................................................................................................................... 38
Operators ....................................................................................................................... 39
Entering a Comment.............................................................................................................. 40
Internal Variables ................................................................................................................... 40
Adding an Internal Variable to an ST Program ............................................................... 41
Using the RETAIN Keyword in an ST Program ............................................................... 42
Direct Variables...................................................................................................................... 43
Using the VAR List to Access Direct Variables............................................................... 44
Using VAR NOCACHE to Prevent Cached Values Being Used in an ST Program......... 46
Using Database Object Structures to Access Direct Variables...................................... 48
Using SQL Queries to Access Direct Variables .............................................................. 50
Using Vectors to Access Direct Variables ...................................................................... 51
Indirect Variables ................................................................................................................... 52
Constants .............................................................................................................................. 57
Historic Values in ST Programs ............................................................................................. 58
Accessing Historic Direct Variables................................................................................ 58
Processed Historic Values in ST Programs (Historic Data Arrays) ................................. 61
Historic Functions and Arguments ................................................................................. 62

PD-6017 07/2012

Built-In Data Types ................................................................................................................ 63


Integer Values................................................................................................................. 63
Floating Point Values...................................................................................................... 68
Time and Date Values..................................................................................................... 68
Binary Values.................................................................................................................. 70
String Values .................................................................................................................. 71
Derived Data Types ............................................................................................................... 72
Using Derived Data Types to Create Names for Types of Value .................................... 72
Using Structured Data Types to Group Internal Values.................................................. 73
Using Enumerated Data Types to Create Names for State Values ................................ 77
Using Nested Data Structures........................................................................................ 79
Arrays ............................................................................................................................. 80
Vectors ........................................................................................................................... 81
Setting the Default Values ..................................................................................................... 87
Default Values for Built-in Data Types (Literals).............................................................. 87
Default Values for Derived Data Types ........................................................................... 88
Default Values for Enumerated Data Types .................................................................... 88
Default Values for Structured Data Types ...................................................................... 89
Executing Methods on Database Items ................................................................................ 90
Viewing which Methods are Available ............................................................................ 90
Entering Methods in your ST Program ........................................................................... 91
Declaring a Method in a METHOD Block....................................................................... 91
Declaring a Method in a DATABASE_OBJECT Structure............................................... 96
Calling a Method ............................................................................................................ 99
Controlling the Flow of the Program ................................................................................... 100
IF - THEN - ELSE ......................................................................................................... 100
IF - THEN - ELSIF - ELSE............................................................................................. 102
AND, OR, and XOR ...................................................................................................... 103
CASE - OF.................................................................................................................... 104
FOR - TO - BY.............................................................................................................. 106
WHILE - DO.................................................................................................................. 107
REPEAT - UNTIL........................................................................................................... 109
RETURN ....................................................................................................................... 110
Using an ST Program to Call an SQL Query ....................................................................... 112
Inserting, Updating, and Deleting Values by Using SQL in an ST Program ........................ 116
Passing Multiple Parameters into an SQL Query in an ST Program ................................... 119
Function Blocks in ST Programs ......................................................................................... 121
Using Libraries in ST Programs........................................................................................... 121
Compiling an ST Program or ST Library ............................................................................. 122
Debugging an ST Program or ST Library ............................................................................ 124
Viewing the Variables in your ST Program........................................................................... 127

Ladder Diagrams ...................................................................................... 129


How Ladder Diagrams Work ............................................................................................... 130
Ladder Diagram Components ............................................................................................. 131

PD-6017 07/2012

Create a Ladder Diagram Database Item ............................................................................ 132


Edit a Ladder Diagram......................................................................................................... 132
Ladder Diagram Display ...................................................................................................... 133
Add Variables to a Ladder Diagram..................................................................................... 134
Add a Direct Variable to a Ladder Diagram.................................................................. 134
Add an Internal Variable to a Ladder Diagram ............................................................. 139
Add Processed Historic Values to Ladder Diagrams .......................................................... 141
Add a Constant Value to a Ladder Diagram ........................................................................ 145
Add a Function to a Ladder Diagram .................................................................................. 146
Add a Function Block to a Ladder Diagram ........................................................................ 147
Add a Conversion to a Ladder Diagram .............................................................................. 148
Add a Comment to a Ladder Diagram ................................................................................ 149
Controlling the Flow of a Ladder Diagram........................................................................... 150
Make a Connection on a Ladder Diagram ................................................................... 150
Add a Connection Block to a Ladder Diagram ............................................................ 150
Edit a Variable on a Ladder Diagram ................................................................................... 151
Rename a Variable on a Ladder Diagram ............................................................................ 151
Delete a Variable on a Ladder Diagram ............................................................................... 152
Compiling a Ladder Diagram............................................................................................... 153
Viewing the Variables in your Ladder Diagram .................................................................... 154
Changing the Update Interval for a Ladder Diagram .......................................................... 155

Function Block Diagrams .........................................................................157


How Function Block Diagrams Work................................................................................... 158
Function Block Diagram Components ................................................................................ 159
Create a Function Block Diagram Database Item ............................................................... 160
Edit a Function Block Diagram ............................................................................................ 160
Function Block Diagram Display ......................................................................................... 161
Add Variables to a Function Block Diagram........................................................................ 162
Add a Direct Variable to a Function Block Diagram ..................................................... 162
Add an Internal Variable to a Function Block Diagram................................................. 167
Add Processed Historic Values to Function Block Diagrams.............................................. 169
Add Raw Historic Values to Function Block Diagrams........................................................ 173
Add a Constant Value to a Function Block Diagram ........................................................... 174
Add a Function to a Function Block Diagram ..................................................................... 175
Add a Function Block to a Function Block Diagram ........................................................... 176
Add a Conversion to a Function Block Diagram ................................................................. 177
Add a Comment to a Function Block Diagram.................................................................... 178
Create a Ladder Diagram within a Function Block Diagram ............................................... 179
Controlling the Flow of a Function Block Diagram.............................................................. 180
Make a Connection on a Function Block Diagram....................................................... 180
Add a Connection Block to a Function Block Diagram................................................ 181
Edit a Variable on a Function Block Diagram ...................................................................... 181
Rename a Variable on a Function Block Diagram ............................................................... 182
Delete a Variable on a Function Block Diagram .................................................................. 183

PD-6017 07/2012

Compiling a Function Block Diagram or Function Block Library ........................................ 184


Viewing the Variables in your Function Block Diagram ....................................................... 185
Changing the Update Interval for a Function Block Diagram.............................................. 186
Viewing the Values on a Function Block Diagram ............................................................... 187

Sequential Function Charts ..................................................................... 189


Sequential Function Chart Components ............................................................................. 190
Steps ............................................................................................................................ 190
Transitions .................................................................................................................... 191
Actions ......................................................................................................................... 191
Action Associations...................................................................................................... 192
Comments.................................................................................................................... 192
Connections ................................................................................................................. 193
How Sequential Function Charts Work ............................................................................... 194
Simultaneous Sequences.................................................................................................... 197
Create a Sequential Function Chart Database Item............................................................ 200
Display a Sequential Function Chart ................................................................................... 201
Add Direct and Internal Variables to a Sequential Function Chart ...................................... 202
Add a Step to a Sequential Function Chart......................................................................... 204
Define a Step as the First Step in a Sequential Function Chart .......................................... 204
Add a Transition to a Sequential Function Chart................................................................. 205
Edit a Transition ................................................................................................................... 206
Display the Actions Window on a Sequential Function Chart............................................. 207
Add an Action to a Sequential Function Chart.................................................................... 208
Edit an Action on a Sequential Function Chart ................................................................... 209
Edit an Action Association .................................................................................................. 210
Add a Comment to a Sequential Function Chart ................................................................ 213
Edit a Comment on a Sequential Function Chart................................................................ 213
Add a Method Variable to a Sequential Function Chart ...................................................... 214
Initiate a Method on a Sequential Function Chart............................................................... 216
Insert a Breakpoint on a Step in a Sequential Function Chart ............................................ 218
Delete Sequential Function Chart Components.................................................................. 218
Rename Sequential Function Chart Components............................................................... 218
Compiling a Sequential Function Chart .............................................................................. 219
Viewing the Variables in your Sequential Function Chart .................................................... 220
Changing the Update Interval for a Sequential Function Chart .......................................... 221

Built-in Functions, Function Blocks, and Conversions......................... 223


Using EN and ENO to Control when a Function is Performed............................................ 224
Combining Functions with other Functions ........................................................................ 225
Built-In Functions ................................................................................................................ 226
Arithmetic ..................................................................................................................... 226
Bit String....................................................................................................................... 234
Bitwise/Boolean ........................................................................................................... 239
Comparison.................................................................................................................. 244

PD-6017 07/2012

Date and Time .............................................................................................................. 251


Numerical ..................................................................................................................... 278
Selection....................................................................................................................... 291
String ............................................................................................................................ 297
Misc .............................................................................................................................. 310
Built-In Function Blocks ...................................................................................................... 319
Counters....................................................................................................................... 319
State Change Detectors ............................................................................................... 330
Set and Reset Bistables ............................................................................................... 334
Timers........................................................................................................................... 339
Conversions......................................................................................................................... 346
Using Logic to Run an Executable File................................................................................ 348
Using Logic to Write to a File or Serial Port ........................................................................ 348

User Function Blocks................................................................................349


Create an ST Library............................................................................................................ 350
Edit an ST Library ................................................................................................................ 350
Create a Function Block Library .......................................................................................... 353
Edit a Function Block Library .............................................................................................. 354
Reference an ST Library or Function Block Library in a Logic Diagram ............................. 355
Reference an ST Library or Function Block in an ST Program............................................ 356
Update an ST Library or Function Block Library ................................................................. 357

10

Logic Program Properties and Values.....................................................359


Configure an ST Program, Ladder Diagram, SFC or FBD................................................... 359
Enable or Disable a Logic Program.............................................................................. 362
Define the Severity of a Logic Program's Alarms and Events...................................... 363
Define the Execution Settings for a Logic Program ..................................................... 364
Define when a Logic Program Updates its Outputs..................................................... 377
Define whether a Logic Program Executes Methods after a Failed Method................ 379
Define the Conversion Types for a Logic Program....................................................... 380
Define the Number of Instructions for a Logic Program .............................................. 382
Define the Time Zone to be used for Calculations within the Logic Program.............. 384
Configure an ST Library....................................................................................................... 385
Choose the Color for Function Blocks Stored in ST Libraries ..................................... 386
Create a ToolTip for an ST Library................................................................................ 387
OPC Properties for Logic Programs.................................................................................... 388

11

Logic Data Types .......................................................................................389


Display the OPC Data Type for a Property .......................................................................... 389
Data Types for Logic, OPC, and ClearSCADA .................................................................... 390
Data Type Hierarchy ............................................................................................................ 392

12

Using Actions Associated with Logic Programs ....................................393


Disable Execution ................................................................................................................ 393

PD-6017 07/2012

Enable Execution................................................................................................................. 394


Execute................................................................................................................................ 394
Restart Execution ................................................................................................................ 395
Set Variable ......................................................................................................................... 395

13

Logic Specific Status Attributes ............................................................. 397

PD-6017 07/2012

Safety Information

Important Information
Read these instructions carefully, and familiarize yourself with ClearSCADA before trying
to install, operate, or maintain your system. The following special messages may appear
throughout this documentation or on the ClearSCADA application to warn of potential
hazards or to call attention to information that clarifies or simplifies a procedure.

Please Note
Electrical equipment should be installed, operated, serviced, and maintained only by
qualified personnel. No responsibility is assumed by Schneider Electric for any
consequences arising out of the use of this material.
A qualified person is one who has skills and knowledge related to the construction and
operation of electrical equipment and the installation, and has received safety training to
recognize and avoid the hazards involved.

PD-6017 07/2012

Before You Begin


ClearSCADA is a Supervisory Control and Data Acquisition (SCADA) solution. It
comprises software that is used to control and monitor various devices, applications and
processes on your system. Due to ClearSCADAs central control and processing role, you
must appropriately design, commission and thoroughly test your systems configuration
for proper operation before placing it in service. Any further configuration changes made
online (once ClearSCADA is commissioned, tested, and in service) must be thoroughly
tested before being used in an operational setting.

WARNING
UNINTENDED EQUIPMENT OPERATION
The configuration of this product requires expertise in the design, configuration and programming
of SCADA control systems. Only persons with such experience should be allowed to configure
ClearSCADA. Only persons with the appropriate programming experience should be allowed to
write any scripts, Logic programs, expressions, or SQL queries intended for use in ClearSCADA.
Follow all local and national safety codes and standards.
Failure to follow these instructions can result in death, serious injury, or equipment damage.

10

PD-6017 07/2012

About the Guide

Document Scope
This guide explains how to use the ClearSCADA ViewX interface to create and edit Logic
programs. ClearSCADA supports Ladder Logic, Structured Text, Function Block
Diagrams and Sequential Function Charts, all of which are part of the IEC 1131-3
Programming industrial control systems standard.
This Guide is designed to explain the interfaces and includes examples of various Logic
programs. It is not a reference guide to the IEC 1131-3 Programming languages.
For information on the subjects covered in this Guide, see Welcome to the Guide to Logic,
on page 13.

Intended Audience
This guide is intended for engineers who are responsible for the design and creation of
Logic programs (programs which define relationships between database items and
system behavior). It is assumed that such engineers have an in-depth understanding of
one or more of the Logic programming languages supported by ClearSCADA.

Validity Note
This guide is valid for ClearSCADA 2010 R3 running on computers that are using an
appropriate Windows operating system (see Operating Systems, on page 25 in the
ClearSCADA Installation Guide).
Further Information
System Requirements: see ClearSCADA System Requirements, on page 11 in the
ClearSCADA Installation Guide.

Related Documents
This guide includes references to content in the following guides:
ClearSCADA Guide to Core Configuration
ClearSCADA Guide to the Database
ClearSCADA Guide to Expressions

ClearSCADA Guide to Server Administration


ClearSCADA Installation Guide.

PD-6017 07/2012

11

User Comments
We welcome your comments about this guide. You can reach us by e-mail at
technicalsupport@controlmicrosystems.com.

12

PD-6017 07/2012

Chapter 1 - Welcome to the Guide to Logic

1 Welcome to the Guide to Logic

Welcome to the ClearSCADA Guide to Logic. This guide is designed to aid you in the
creation and design of ST programs, Function Block Diagrams, Ladder Diagrams, and
Sequential Function Charts.
ClearSCADA supports 4 Logic languages that you can use to define relationships
between values, control sequences, conversion calculations etc. These languages are
part of the IEC 1131-3 Programming industrial control systems standard.
The ClearSCADA Guide to Logic consists of:

Working with Logic Programs (see page 15)

Characters for Use in Logic (see page 27)

ST Programs (see page 29)

Ladder Diagrams (see page 129)

Function Block Diagrams (see page 157)

Sequential Function Charts (see page 189)

Built-in Functions, Function Blocks, and Conversions (see page 223)

User Function Blocks (see page 349)

Logic Program Properties and Values (see page 359)

Logic Data Types (see page 389)

Logic Specific Status Attributes (see page 397).

In the sections listed above, you will find reference information that you can use to find
out about the various Logic languages and how they are supported in ClearSCADA. The
sections contain some detail about the programming of Logic programs, but are not
designed to be a complete reference on the IEC 1131-3 standard. The purpose of this
Guide is to provide details about how you can use ClearSCADA to create the Logic
programs you require on your system.

PD-6017 07/2012

13

Chapter 1 - Welcome to the Guide to Logic

14

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

2 Working with Logic Programs

Before you configure your own Logic programs, you need to understand:

Which Logic languages are supported by ClearSCADA (see Supported Logic


Languages, on page 16)

How Logic Programs Work (see page 18)

Which type of Logic program you need to create (see Choosing a Logic Program, on
page 19).

What considerations you need to make when Using Outputs as Inputs (Feedback
Loops) in Logic Programs (see page 20)

How to determine the Execution Order for Logic Programs (see page 21).

NOTE: If your Logic program does not run or has unexpected results, please refer to
Troubleshooting Logic Programs (see page 25).

PD-6017 07/2012

15

Chapter 2 - Working with Logic Programs

Supported Logic Languages


ClearSCADA supports 4 of the languages included in the International Electro-technical
Commission (IEC) standard for programming industrial control systems (IEC 1131-3):

16

Ladder Diagrams

Function Block Diagrams (FBDs)

Sequential Function Charts (SFCs)

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

Structured Text programs (ST)

In ClearSCADA these languages are referred to as Logic programs, and you can use them
to:

Define complex relationships between the values for the properties of items in the
database

Perform calculations

Execute methods on items in the database (one shots, overrides, controls etc.)

For example, in the water industry, a Function Block Diagram can be used to turn pumps
on when the water level drops to a specified limit.
The Logic programs are interchangeableyou can use one type of Logic program with a
different type of Logic program. For example, you can use ST programs with Function
Block Diagrams or Ladder Diagrams. The only exception is Sequential Function Charts
which can only be used with ST programs.

PD-6017 07/2012

17

Chapter 2 - Working with Logic Programs

How Logic Programs Work


Each Logic program is configured to represent a calculation or a procedure. The Logic
program uses values from the database (inputs) as part of the calculation or procedure.
The result of the calculation or procedure is either written to the ClearSCADA database as
a value or is used to execute a method such as a control.
Logic programs can be set to execute:

When an input value changes

At specified times.

When a Logic program begins, it reads its input values (Tag Read). These values can be
the values of items in the database or can be values specified in a query.
After reading its input values, the Logic program executes. The calculation or procedure
that is defined in the configuration of the Logic program is executed. The input values are
used as part of the calculation or procedure.
When the Logic program has executed, it has an output. The output is either:

The setting of an item's property, for example, a value that is written to a point

or:

The execution of a method on an item in the database, for example, the output of a
Logic program can initiate the Refresh Outstation method.

Logic programs are designed to have a similar architecture to PLC programs. The
procedure for executing a Logic program is:
1.

Logic program reads its inputs

2.

Logic program executes

3.

Logic program writes its outputs

This sequence of events cannot be altered. The inputs are read first, and then the
program executes, and then the outputs are written. Logic programs cannot use any other
type of structure.
NOTE: Methods are sometimes referred to as 'actions'.

18

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

Choosing a Logic Program


You need to decide which type of Logic program you are going to use. For many
requirements, you can use any of the Logic programs to achieve the required effect.
However, in some situations you may need to choose a specific type of program.
By answering the questions below, you can determine whether you need to create a
specific type of Logic program or can use the Logic program of your choice:

If you have a choice of which Logic program to use, we recommend that you use the
Logic program that you find easiest to use. For many engineers, Ladder Diagrams are the
easiest type of Logic program to understand. Ladder Diagrams use relay ladder Logic and
are similar to traditional PLC programs.
Like Ladder Diagrams, Function Block Diagrams and Sequential Function Charts are
graphical displays. Many users prefer to use graphical programs as they show each of the
elements that form the program. It is easier to create a complex program when you can
see its elements.
Structured Text (ST) is a text based programming language and is a very flexible type of
Logic program. You can use ST programs to provide any type of supported behavior, but
to program them you will need a good understanding of the ST language and strong
programming skills.

PD-6017 07/2012

19

Chapter 2 - Working with Logic Programs

For detailed information on the Logic languages, please refer to the following sections:

ST Programs (see page 29)

Ladder Diagrams (see page 129)

Function Block Diagrams (see page 157)

Sequential Function Charts (see page 189).

When creating Logic programs, you may also need to refer to:

User Function Blocks (see page 349)

Built-in Functions, Function Blocks, and Conversions (see page 223)

Logic Program Properties and Values (see page 359).

Using Outputs as Inputs (Feedback Loops) in Logic Programs


The outputs in your Logic programs can also be used as inputs, for example, you can use
the output result of an ADD function as an input on a DIV function. When an output is also
an input, it is referred to as a feedback loop.
If your Logic program uses feedback loops you should use ClearSCADAs built-in
diagnostics tool to check the execution order of your program.

20

For more information on the execution order of feedback loops, see Execution Order
for Logic Programs, on page 21.

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

Execution Order for Logic Programs


Each part of a Logic program is executed in a sequence referred to as the execution
order. The way in which ClearSCADA determines the execution order varies according to
the type of Logic program:

For ST programs, the execution order is clearly defined in the language syntax
(ClearSCADA compiles then executes the code from top to bottom).

For Sequential Function Charts, the execution order is defined by the logical state
transitions in the charts.

For Function Block Diagrams and Ladder Diagrams, ClearSCADA examines the
diagrams and then generates the Structured Text (ST) equivalent of the program.
ClearSCADA then compiles the ST and executes it in the same way that it would
execute the code for an ST Program database item.
The execution order of Function Block Diagrams and Ladder Diagrams is determined
by ClearSCADA when it generates an ST equivalent of the graphical program. Typically,
when ClearSCADA generates the ST equivalent, it attempts to order the program so
that inputs are processed before outputs, based on the block relationship.
For example, if we take the following simple Function Block Diagram:

When this FBD is saved, ClearSCADA will generate the ST equivalent of the program
which is:
PROGRAM $FBD
VAR
dig5 AT %M(.dig5) : BYTE;
dig2 AT %M(.dig2) : BYTE;
dig3 AT %M(.dig3) : BYTE;
dig4 AT %M(.dig4) : BYTE;
END_VAR
VAR
$B1_ENO : BOOL := FALSE;
$B1 : BYTE;
$B2_ENO : BOOL := FALSE;
$B2 : BYTE;
END_VAR
$B1 := AND( IN1 := dig3, IN2 := dig2, ENO => $B1_ENO );
$B2 := OR( IN1 := $B1, IN2 := dig4, ENO => $B2_ENO );
IF $B2_ENO THEN
dig5 := $B2;
END_IF;
END_PROGRAM

PD-6017 07/2012

21

Chapter 2 - Working with Logic Programs

The program has been arranged so that:

The OR block is processed before the output 'D'

Inputs to the OR block are processed before the OR block is processed

Inputs to the AND block are processed before the AND block is processed.

If outputs are also used as inputs (feedback loops), the execution order can become
complicated. In these cases, we advise that you use ClearSCADAs built-in diagnostics
tool to check the execution order of your programs. The diagnostics tool shows the ST
that ClearSCADA generates for your diagram, from which you can clearly see the
execution order. If the order is not as you expected, you can alter your diagram as
required. When you save the altered diagram, ClearSCADA will generate new ST for the
program and you can use this to see how your changes have affected the execution order.
To run the diagnostics tool, simply display the Logic program in Design Mode, then select
the Build menu, then the Compile with Diagnostics option.
Example:
The following function block diagram is an example of a Logic program that could be used
as a safety interlock for controlling a pump. It is used to control a pump - the pump cannot
be started when there is no flow. This is achieved by establishing these relationships:

When a StartPump signal is sent, the pump motor starts. However, if a flow has not
been detected after a 120 second period, the pump is stopped and locked out (the
pump stops responding to controls).

When a StopPump signal is sent, the pump motor stops running.

When a ResetPump signal is sent, the pump is no longer locked out. A StartPump
signal can be sent to the pump to attempt to start it, but if a flow is not detected within
120 seconds, the pump will be locked out again.

As you can see, the LockedOut output is also used as an input for an AND function. This
means there is a feedback loop.
Engineers can view the execution order by running the Compile with Diagnostics tool. This
displays the function block diagram as ST code in the compiler, and lists the order in which
the various elements of the program are executed.

22

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

The execution order is shown in the ST code in


the Compiler.

The Compile with Diagnostics feature is selected and it shows the ST that ClearSCADA has
generated for the Function Block Diagram. The execution order is clearly shown in the ST
code, with the code being executed from top to bottom:

PD-6017 07/2012

23

Chapter 2 - Working with Logic Programs

By analyzing the ST that has been generated for the Function Block Diagram, we can see
that the execution order is as follows:

ClearSCADA executes the elements to produce the LockedOut output/input first, and then
executes the elements required to produce the PointState output.

24

PD-6017 07/2012

Chapter 2 - Working with Logic Programs

Troubleshooting Logic Programs


When configuring a Logic program, you can use the compile feature to check the validity
of your program. For more information, see:

Compiling an ST Program or ST Library (see page 122)

Compiling a Ladder Diagram (see page 153)

Compiling a Function Block Diagram or Function Block Library (see page 184)

Compiling a Sequential Function Chart (see page 219).

However, it is possible to have a program compile successfully at the time of


configuration, but be unable to execute correctly at a later date. If your program is unable
to execute correctly, there are many possible causes, including:

A database item that is referenced by the Logic program has been deleted from the
database. In this situation, you need to either reconfigure the program to reference a
different item or create a new item with the same address and name as the item that
was deleted.

The program is set to execute On Input Processed and does not contain a valid input
(see Define the Execution Method for a Logic Program, on page 367)

The program cannot read from, or write to, a property tag that is referenced in the
program

The program contains a calculation that is attempting to divide by 0

A subscript value for an array exceeds the range specified for the array

The order of execution is not as expected. This is often due to the use of feedback
loops where an output is also used as an input. You can use the Compile with
Diagnostics option to view the actual order in which ClearSCADA executes your
program and then adjust your program accordingly (see Execution Order for Logic
Programs, on page 21).

In many cases, you will need to reconfigure your Logic program.


To find out more information about the specific configuration issue that is affecting the
execution of your Logic program, we recommend that you:
1.

Display the Logic Execution Status List (display the Queries Bar, expand the Queries
branch, then display the Logic Execution Status List).

2.

Locate the entry that corresponds to your Logic program

3.

Examine the Error Message entry for your program. The Error Message provides a brief
description of the cause of the Logic programs inability to execute.

4.

Re-configure the Logic program so that the issue described in the Error Message is
resolved.

PD-6017 07/2012

25

Chapter 2 - Working with Logic Programs

26

PD-6017 07/2012

Chapter 3 - Characters for Use in Logic

3 Characters for Use in Logic

When creating Logic programs, there are limitations regarding the characters you can
use. These are fixed by the language standard, and mean that for some parts of your
programs, you can only use certain characters from the English character set.
The characters you can use vary depending on which part of a Logic program you are
defining:

Language KeywordsThe keywords you use in Logic, for example, FUNCTION, are
fixed by the language standard. They cannot be changed or translated in any way.

IdentifiersWe recommend that you use a restricted character set when you create
identifiers in programs (see Restricted Character Set - Logic, on page 27).

String ConstantsWhen you define constants, you can use any characters from any
language. For example, you can use Chinese characters within the single quotation
marks of the constant.

Tag ReferencesReferences to items in the database can use characters from any
character set. However, the character set that can be used in the actual tag may be
limited.

Restricted Character Set - Logic


We recommend that you only use the following characters in identifiers in Logic programs:
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
_
Logic program identifiers cannot:

Begin with a number

Contain double underscores (an underscore character followed immediately by another


underscore character).

NOTE: Technically, it is possible to use other characters and numbers in the Unicode
standard. But we recommend that you only use the restricted character set shown above.

PD-6017 07/2012

27

Chapter 3 - Characters for Use in Logic

28

PD-6017 07/2012

Chapter 4 - ST Programs

4 ST Programs

Structured Text is a high level programming language that you can use to define the
relationships between values.
ST programs can consist of:

VariablesInput and output values that can change. There are also internal variables
which are values that are only used within the ST program. For example, an ST program
can read the value of an input (such as the value from a property of a database item),
use an internal value to perform a calculation on the input value, then write the result of
the calculation to an output value.

ConstantsThese are special types of value that are used by the ST program. These
values are fixed and cannot change (they are constant).

Data TypesThere are several types of value. You need to specify which type of value
is applicable to each variable. For example, values such as descriptions are STRING
values (they contain a string of characters) whereas values from analog points are REAL
or LREAL values.
There are built-in data types, also referred to as literals, that you can use to define the
type of a value. You can also use derived data types to apply meaningful names to
values, group internal values, and form arrays etc.

MethodsThese are actions that can be performed by an ST program. For example, an


ST program can be created to acknowledge an alarm when a specific condition occurs.

Control StructuresControl structures are used to define the Logic of the ST program.
By using keywords and adhering to the formatting rules, you can create a flow of
conditions and results. These define the behavior that the ST program provides.

Function BlocksFunction blocks are blocks of code that provide specific functionality,
for example, convert a temperature in Celsius to a temperature in Fahrenheit. The
function blocks can be used over and over again in each of your Logic programs,
including ST programs.

To configure an ST program, you will need an appreciation of the Structured Text


standard. As the ST programs are not graphical, some users find them more difficult to
work with. However, you need to have an understanding of ST as you may need to use ST
when working with Function Block Diagrams, Sequential Function Charts etc. This is
especially true if you need to reference historic data or are using SQL queries.

PD-6017 07/2012

29

Chapter 4 - ST Programs

We recommend that you familiarize yourself with the following sections, even if you do not
intend to work with ST programs:

Create an ST Program in the ClearSCADA Database (see page 31)

Edit an ST Program (see page 32)

Understanding the Basic Structure of an ST Program (see page 34)

Statements, Expressions and Operators (see page 37)

Entering a Comment (see page 40)

Internal Variables (see page 40)

Direct Variables (see page 43)

Constants (see page 57)

Historic Values in ST Programs (see page 58)

Built-In Data Types (see page 63)

Derived Data Types (see page 72)

Setting the Default Values (see page 87)

Executing Methods on Database Items (see page 90)

Controlling the Flow of the Program (see page 100)

Using an ST Program to Call an SQL Query (see page 112)

Inserting, Updating, and Deleting Values by Using SQL in an ST Program (see page 116)

Passing Multiple Parameters into an SQL Query in an ST Program (see page 119)

Function Blocks in ST Programs (see page 121)

Using Libraries in ST Programs (see page 121)

Compiling an ST Program or ST Library (see page 122)

Debugging an ST Program or ST Library (see page 124)

Viewing the Variables in your ST Program (see page 127)

By familiarizing yourself with some of the ST basics, you will find it much easier to
understand the principles of the other types of Logic program.
For information on configuring the various properties of an ST program, see Logic
Program Properties and Values, on page 359.

30

PD-6017 07/2012

Chapter 4 - ST Programs

Create an ST Program in the ClearSCADA Database


Before you can create an ST program in ClearSCADA, you need to add an ST Program
item to the database. The ST Program item will store the ST code that you create.
To create an ST Program database item:
1.

In the Database Bar, right-click on the system, Group, or Group Template that is to
contain the ST program.

A context sensitive menu is displayed.


2.

Select the New option, then the Logic option, then the Structured Text Program option.

A new ST program database item is added to the hierarchy. It is selected automatically,


ready for you to define its name.

3.

Enter a suitable name for the ST program then press the Enter key or select another
part of the interface to confirm.

4.

You have now created the ST program database item. To create your ST program, you
will need to edit it (see Edit an ST Program, on page 32).

PD-6017 07/2012

31

Chapter 4 - ST Programs

Edit an ST Program
To enter the code for an ST program, you need to edit as ST Program database item.
During the editing process, you will enter the code that defines the behavior that is to be
provided by the program, for example, you could enter the code that allows the ST
program to perform a calculation. When you save the code, the program you have created
is stored in the ST Program database item.
To edit an ST program:

In the Database Bar, either double-click on an ST program item or right-click on it and


select the Edit option from the context sensitive menu.

The ST program is displayed in Design mode. You can only edit an ST program in
Design mode.

Enter your ST
program code in
the editor.

Diagnostic information is shown in the Compiler.

The main display area of the ST program editor shows the ST program. Each ST program
has PROGRAM <program name>, ;, and END_PROGRAM by default as ST programs
require these attributes. You will define the Logic of your ST program between PROGRAM
and END_PROGRAM.
At the bottom of the ST program editor is a smaller frame. This frame is the compiler.
ClearSCADA displays diagnostic information in this section.

32

PD-6017 07/2012

Chapter 4 - ST Programs

To code an ST program, you will need an understanding of the Structured Text language.
We explain some of the basic principles of the ST language in the following sections, but
you may need to broaden your knowledge by referring to a Third Party source:

Understanding the Basic Structure of an ST Program (see page 34)

Entering a Comment (see page 40)

Internal Variables (see page 40)

Direct Variables (see page 43)

Indirect Variables (see page 52)

Constants (see page 57)

Setting the Default Values (see page 87)

Built-In Data Types (see page 63)

Derived Data Types (see page 72)

Executing Methods on Database Items (see page 90)

Controlling the Flow of the Program (see page 100)

Using an ST Program to Call an SQL Query (see page 112)

Inserting, Updating, and Deleting Values by Using SQL in an ST Program (see page 116)

Passing Multiple Parameters into an SQL Query in an ST Program (see page 119)

Function Blocks in ST Programs (see page 121)

Using Libraries in ST Programs (see page 121).

The following sections explain how to check that your ST program is coded correctly:

Compiling an ST Program or ST Library (see page 122)

Debugging an ST Program or ST Library (see page 124)

Viewing the Variables in your ST Program (see page 127).

The following section explains how to configure your ST program (including how to define
when the program is executed):

PD-6017 07/2012

Logic Program Properties and Values (see page 359).

33

Chapter 4 - ST Programs

Understanding the Basic Structure of an ST Program


Before you begin to create your own ST programs, you need to be aware of the basic
structure of an ST program.
1.

The start of the program.


ST programs begin with a PROGRAM keyword and a program name. This is followed
by a VAR keyword and a list of variables.

2.

The variable blocks.


There are 2 types of VAR blockVAR blocks for internal variables and VAR blocks for
direct and indirect variables. Variables of different types have to be defined in separate
blocks.
For internal variables, the VAR block will begin with a VAR keyword. The variables are
defined after the VAR keyword and use the format:
<name> : <type>;
For direct and indirect variables, the VAR block will also begin with a VAR keyword. The
variables are defined after the VAR keyword and use this format:
<name> <instruction> (<item>.<variable>) : <variable type>;
For example:
VAR
Desc AT %I(.Valve.Position.CurrentStateDesc) : STRING;
END_VAR
Each VAR block is ended by an END_VAR keyword.

When you are using variables, you need to:


i.

Define the type for any arguments

ii. Separate each argument type with a comma, for example, STRING, BYTE,STRING;
means there are 3 arguments, the first is a string, the second is a byte, and the final
argument is a string.
iii. Use VAR INPUT definitions to allow the ST program to receive inputs from a user/
another ST program. The VAR INPUT keyword needs to be included in the recipient
program (so, if one ST program receives the inputs for its indirect variables from
another program, the program that receives the inputs has to have VAR INPUTS).

34

PD-6017 07/2012

Chapter 4 - ST Programs

iv. Define the VAR INPUTS in the same order in which they are to be executed.
To allow a program to use the values from another program, the arguments for the
indirect variables inputs have to be in the same order in both programs. For
example, Program 1 defines a method that has outputs in this order: STRING,
BYTE. These values are output to Program 2. In Program 2, the VAR INPUT
definition has to define that the first argument is a STRING and the second
argument is a BYTE as this is the order defined in Program 1.
v.

Set the Interval to 0s on the ST Program Form for the recipient ST program.
Programs that use manually entered input values or input values from other
programs cannot be executed on an interval basis. However, they can be executed
by another program (the other program executes the recipient ST program at a
regular interval), according to a schedule, and manually. If required, configure a
schedule to execute the program at specific times (see Using Schedules to
Automate Regular Functions, on page 447 in the ClearSCADA Guide to Core
Configuration).
If you execute a recipient ST program manually, you will be prompted to enter the
input value. You need to enter the input value in the dialog box and select the OK
button to proceed. You will only be prompted to enter a value if the recipient
program has inputs defined, but the inputs are not associated with other programs.

3.

The method block.


If an ST program uses methods, the methods are defined in a METHOD block. The
METHOD block has to follow the VAR block(s) and also come before the ST code for
the program. If the ST program does not use methods, there is no METHOD block and
the ST code for the program follows the last VAR block.
The METHOD block begins with a METHOD keyword. The methods that the program
uses are listed and use this format:
<name> <instruction> (<item>.<method>) : <argument types>;
For example:
METHOD
OVR AT %M(AIs.AnalogInp.Override) : LREAL;
END_METHOD
The METHOD block is ended by an END_METHOD keyword.

4.

The ST code for the program. This can include statements, expressions, and operators.

5.

The end of the program.


Each ST program is ended with the END_PROGRAM keyword.

In the following basic example, the ST program contains 3 variables and 3 methods. ST
programs can contain as many variables and methods as required.
For the example, entries in angle brackets < > indicate a name or type that you have to
enter for the program. These will vary depending on the items you want to reference and
the names you want to use. You should not enter the angle brackets in your ST
programswe use them here to indicate that you need to specify a name, location, or
data type that will vary according to your needs.

PD-6017 07/2012

35

Chapter 4 - ST Programs

PROGRAM <program name>


VAR
<name> : <type>;
<name> : <type>;
<name> : <type>;
END_VAR
METHOD
<name> AT %M(<location and name of item>.<method>) : <argument
types>;
<name> AT %M(<location and name of item>.<method>) : <argument
types>;
<name> AT %M(<location and name of item>.<method>) : <argument
types>;
END_METHOD
<ST code>;
<ST code>;
<ST code>;
END_PROGRAM
The ST program begins with a PROGRAM definition and the program name. This is
followed by a VAR definition, and the names and types of the variables that are used by
the program. The list of variables is referred to as a VAR block, and it is ended by an
END_VAR definition.
If the ST program uses methods, a METHOD block is defined after the VAR block. The
METHOD block consists of the METHOD keyword followed by the name of a method, an
instruction, the location and name of the item to which the method will be applied, the
name of the method to be applied, and the argument types that will be used (argument
types are types of data for specific settings, for example, the Override method needs an
argument type that specifies the type of value for the override value). The METHOD block
is ended with an END_METHOD keyword.
The ST code that defines the behavior that the program provides is entered after the
METHOD block (or after the VAR block if there is no METHOD block).
The program is ended by the END_PROGRAM keyword.
NOTE: Constants also need separate VAR blockssee Constants, on page 57.

36

PD-6017 07/2012

Chapter 4 - ST Programs

Statements, Expressions and Operators


You need to use Structured Text statements, expressions, and operators to define the
instructions, calculations, and relationships for each ST program.
The types of operators and expressions that you use in your ST program affects the order
in which the expressions are evaluated.
For more information, refer to the following sections:

Statements (see page 37)

Expressions (see page 38)

Operators (see page 39).

Statements
Statements are used to provide an instruction, such as assign a variable. They can
contain expressions (which are calculations). The basic format for a statement is:
<variable>:= <expression>;
Where the <expression> is a calculation that produces a new value for <variable> when
the statement is evaluated.
Examples:
This statement defines the value of a variable named 'FlowRate'. It defines a constant value
(also known as a literal value):
FlowRate:= 64.5;
The next statement defines a basic expression that can be used to increase a value by a
defined amount:
Count:= Count + 1;
The value for the Count variable increases by 1 each time the statement is evaluated.
These are simple examples of statements. You can create much more complicated
statements, including statements with nested expressions.

PD-6017 07/2012

37

Chapter 4 - ST Programs

Expressions
Expressions are calculations or evaluations that are defined within Statements (see page
37). They can use one or more operators, functions, and variables.
Each ST expression produces a value which can be wither a built-in data type (see Built-In
Data Types, on page 63) or a derived data type (see Derived Data Types, on page 72).
These values can be used within a program or can be written to items in the database.
An expression can be simple or complex. A simple expression includes a single
calculation, for example:
y + 10
or a Boolean expression such as:
x = y
A complex expression contains several calculations that are used to produce a value, for
example:
(x + y) * 2
Expressions are evaluated in order. The precedence of the operators and other
expressions in the statement determines when an expression is evaluated. Expressions
are evaluated in this order:
1.

Parenthesized expressions, such as:


(x + y) * 2

2.

Function calls, such as:


COS(x)
Where COS is the function being called, and x is the argument.

Within this order, operators are evaluated in precedence order (see Operators, on page
39). For example, a parenthesized expression with negation will be evaluated before a
parenthesized expression with inequality.
NOTE: For Boolean operators, the expression is evaluated up to the part of the statement at
which the value can be determined.

38

PD-6017 07/2012

Chapter 4 - ST Programs

Operators
Operators are the calculations and conditions that are used to define the behavior that is
provided by a Logic program. Each operator provides a specific calculation or
comparison, for example, the > operator means 'greater than' and the < operator means
'less than'. They can be used in an expression that compares values like this:
IF Value1 > 50 THEN
Value2 := 10;
ELSIF Value1 < 50 THEN
Value2 := 5;
END_IF;

In this expression, if Value1 is greater than 50, then Value2 is 10. If Value1 is less than 50,
then Value2 is 5.
Each operator has a precedence level. This determines the order in which the operations
are evaluated.
The following table shows the available operators and their precedence:

PD-6017 07/2012

Operator

Description

Precedence Level

( <expression> )

Expression inside
parentheses ( )

1 (Highest)

Function (<expression>)

Parameter list of a function or


function evaluation

**

Exponentiation

Negation

NOT

Value with opposite sign

Multiplication

Division

MOD

Modulus operation

Addition

Subtraction

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

Equality

<>

Inequality

AND, &

Boolean AND

XOR

Boolean exclusive OR

10

OR

Boolean OR

11 (Lowest)

39

Chapter 4 - ST Programs

Entering a Comment
Comments are notes that you can add to your ST program. They are useful as they allow
you to annotate your code with descriptions etc.
Comments are optional and have no effect on the program. Typically, they are used to
explain the structure and purpose of sections of ST code to other users.
To enter a comment in your ST program, you need to use the following format:
(* <comment>*)
For example:
(* This calculation is used to increase the count each time the input
is greater than 50*)

Internal Variables
Each type of Logic program can contain internal variables. These are values that are used
by the program but are not written to an item in the database. They are used for:

Conversions

Separating long, complex calculations into smaller sets of calculations

Storing program states.

Unlike direct variables, internal variables are not stored in the database. This means that if
the program or the server is reset, the internal variables will reset to their default value
(you can stop internal variables from resetting by using the RETAIN keyword, as explained
later in this section). As internal variables are not stored, they are not transferred to any
standby servers (again, this can be avoided by using the RETAIN keyword).
Internal variables are stored internally so that Logic programs can maintain the internal
variables for each execution. For example, if an internal variable is used as a count, the
previous value needs to be stored so that the program can use it to determine the next
value.
NOTE: Internal variables need to be separated from direct variables, constants and function
blocks in the VAR lists. This means that if you have a program that uses constants, internal
variables, direct variables, and function blocks, you will have at least 4 VAR lists1 for
constants, 1 for internal variables, 1 for direct variables, and 1 for function blocks.
For information on adding internal variables or using the RETAIN keyword, please refer to
the relevant sections:

40

Adding an Internal Variable to an ST Program (see page 41)

Using the RETAIN Keyword in an ST Program (see page 42).

PD-6017 07/2012

Chapter 4 - ST Programs

Adding an Internal Variable to an ST Program


To add an internal variable to an ST program, you need to define the internal variable in a
VAR list. You can then use the internal variable throughout the ST program.
You have to define internal variables in the following format:
VAR
<Value Name> : <Value Type>;
END_VAR
Where <Value Name> is the name you allocate to the internal variable, and <Value Type>
is the data type of the internal variable (see Built-In Data Types, on page 63 and see
Derived Data Types, on page 72).
You can then refer to the internal variable by name in your ST program. For example:
VAR
TimeCount:TIME;
END_VAR
VAR
TimedStart AT %M(.Power.StartMotor.CurrentState):BOOL;
END_VAR
IF TimeCount > T#60s THEN
TimedStart := TRUE;
ELSE
TimedStart := FALSE;
END_IF;
This program uses an internal variable to act as a timer. When the timer exceeds 60, the
state of a direct variable (TimedStart) changes from FALSE to TRUE.
The internal variable is defined in a separate VAR list to the direct variable. This is because
internal variables and direct variables cannot be listed in the same variables list. To
overcome this, you need to create multiple VAR lists. Each VAR list needs to be structured
in the same way as any other VAR list except that the END_VAR only has a semi-colon at
the end of the final VAR list.
For more information on data types such as BOOL, please refer to Built-In Data Types
(see page 63). You can also create custom data types that allow you to group internal
variables and define meaningful names for value types (see Derived Data Types, on page
72).
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, on page 100.

PD-6017 07/2012

41

Chapter 4 - ST Programs

Using the RETAIN Keyword in an ST Program


Normally, internal variables are not stored for use after the program or server has been
reset. Similarly, they are not transferred to any standby servers.
However, it is possible to store internal values so that:

They are not reset to their initial values when the server or program is reset

They are transferred to any standby servers.

To do this, you need to use a RETAIN keyword. The RETAIN keyword instructs the
program to store the internal variable so that it can transferred and used after a reset.
In ST programs, you need to use the following format to retain the internal variables:
VAR RETAIN
<Value name> :<Value type>;
END_VAR
For example:
VAR RETAIN
TempConversion: INT;
END_VAR
Where TempConversion is the name of the internal variable and INT is the type of value
that it represents (an integer).

42

PD-6017 07/2012

Chapter 4 - ST Programs

Direct Variables
Direct variables are values that are read from (or written to) items in the ClearSCADA
database. You need to reference direct variables in your Logic programs to allow them to
react to values in the database and apply changes to values in the database.
There are several ways of accessing direct variables in your ST programs. The most
effective type of access for you to use varies according to what you need to achieve.
Usually, if you need your Logic program to read values from the database or write values
to the database, you will use a:

Variables List (see Using the VAR List to Access Direct Variables, on page 44).

However, there are some situations in which using an alternative way of accessing the
direct variables is more effective:

If you need to prevent your ST program from using values stored in the cache, you may
need to use a VAR list in conjunction with the NOCACHE keyword. For example, you
will need to use the NOCACHE keyword if your ST program has values that accumulate
with each execution of the program (see Using VAR NOCACHE to Prevent Cached
Values Being Used in an ST Program, on page 46).

If you need your ST program to reference the same properties for a large number of
database items of the same type, you should use a Database Object Structure (see
Using Database Object Structures to Access Direct Variables, on page 48).By using a
Database Object Structure, you can reduce the amount of time and effort required to
create the references to the database.

If you need your ST program to access multiple database items that meet certain
criteria (but are not named explicitly in the program), you should use an SQL Query to
access the database. The SQL Query can be included within your ST program (see
Using SQL Queries to Access Direct Variables, on page 50).

If you need your ST program to read values from, or write values to an array, you need
to use Vectors to access the direct variables (see Using Vectors to Access Direct
Variables, on page 51).

If you need to access historic values, please refer to Historic Values in ST Programs
(see page 58).

PD-6017 07/2012

43

Chapter 4 - ST Programs

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
For 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 relativethe 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
(see page 63). You can also create custom data types that allow you to define meaningful
names for value types (see Derived Data Types, on page 72).
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, on page 100.

44

PD-6017 07/2012

Chapter 4 - ST Programs

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;
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).

PD-6017 07/2012

45

Chapter 4 - ST Programs

Using VAR NOCACHE to Prevent Cached Values Being Used in an ST


Program
You can use the NOCACHE keyword in your Logic programs to prevent the program from
using a cached value. This is required when you need a value to accumulate each time a
program executes, for example, when a total count value needs to increase when an input
value changes.
If the NOCACHE keyword is not used, the ST program will use the value that was in place
when the program first executed. This means that when a series of values are reported for
one of the ST program's inputs, the value of the variable that is affected by the inputs will
be the same. In the example below, the NOCACHE keyword is used to prevent the
program from calculating the Total value as 0.0 + the current value of the Value variable.
So, if the program receives 10 values for the Value variable, the program will use the
default value of 0.0 for the Total value on the first execution, but will not use 0.0 on
subsequent executions. If the NOCACHE keyword was not used, the program would use
the 0.0 value for the Total value for each execution.
Example:
PROGRAM TotalValues
VAR
FirstTime:BOOL := TRUE;
END_VAR
VAR
Value AT %M(Input Point Value): REAL;
END_VAR
VAR NOCACHE
Total AT %M(Total Point): REAL;
END_VAR;
IF FirstTime THEN
Total := 0.0;
FirstTime := FALSE;
END_IF;
Total := Total+Value;
END_PROGRAM

In this example, the FirstTime value is a Boolean value (true/false) that is used to define
whether the program is being executed for the first time. By default, it is set to TRUE.
The Value variable is a real value that the program reads from the Input Point Value database
item.
The Total value is a NOCACHE value (it is not cached and is retrieved each time the program
executes). The Total value is a real value that is calculated by the program each time it
executes. The result of the calculation is written to the Total Point database item.
The If statement determines whether the Total value is 0 or is another value. If the FirstTime
value is TRUE then the Total value is 0.0 (the FirstTime value is only TRUE the first time that
the program executes). If the FirstTime value is FALSE, the FALSE value is maintained and
the Total value is the current Total value + the value of the Value variable.

46

PD-6017 07/2012

Chapter 4 - ST Programs

This means that the first time the program executes, the Total value is 0.0. Before the first
execution of the program completes, it sets the FirstTime value to FALSE so that the next
execution of the program will cause the Total value to change from 0.0. At the end of the first
execution of the program, the Total value is set to the same value as the Value variable
(Total=0.0 + Value = Same value as Value variable).
On subsequent executions of the program, the FirstTime value will be FALSE and so the
Total will be the current Total value + the value of the Value variable. The program will not use
0.0 as the Total value each time, as the 0.0 is not cached.

To define a NOCACHE value, you have to create a separate VAR list for the values to
which the NOCACHE feature applies. The VAR list has to be started as VAR NOCACHE.
The values need to be entered beneath the VAR NOCACHE definition in the same way as
with normal VAR lists, and the VAR list needs to be closed with END_VAR.

PD-6017 07/2012

47

Chapter 4 - ST Programs

Using Database Object Structures to Access Direct Variables


When using direct variables, you need to declare the variables that are used by the Logic
program. The variables have to be declared in VAR blocks. This can be time-consuming if
the Logic program needs to reference the same set of properties for many different items
of the same type.
ClearSCADA provides a structure for referencing multiple fields of a single database item.
The structure is called a database object structure, and it allows you to group a set of
fields for a type of item. The structure is included at the top of the Logic program and can
be referenced within the program. This means that you can reference the name of the
structure instead of referencing multiple fields several times in the same program.
For example, if your ST program references the CurrentValueFormatted, CurrentState,
and QualityStateDesc of 30 points, you would have to enter the variables for each
separate point. This means you would have to define the CurrentValueFormatted,
CurrentState, and QualityStateDesc variables 30 times (each field for each point).
By using a database object structure, you can create a single reference to the
CurrentValueFormatted, CurrentState, and QualityStateDesc fields. The database object
structure includes the specified fields in the relevant class (in this case, the CDBPoint
class). This means that the same database object structure can be used to reference the
specified fields for any item in the classit can be used for any point.
Example:
A Logic program needs to reference the CurrentValueFormatted, HighLimit, CurrentState
and CurrentStateDesc fields of a 20 different points. If the database object structure is not
used, you will have to add these fields to the program (for each of the 20 points).
The following database object structure is used:
TYPE
PointValues : DATABASE_OBJECT(CDBPOINT)
CurrentValueFormatted: LREAL;
CurrentState: BOOL;
QualityStateDesc: STRING;
END_DATABASE_OBJECT;
END_TYPE
By using the database object structure, the fields are grouped at the top of the program. The
database object structure is allocated a name (PointValues). Where the program needs to
refer to the fields, the name of the database object structure and the specific point is used.
This means that the database object structure can be used to refer to the same specified
fields for multiple points.
In the program, references to the point values use this format:
<name of variable> AT %M(<path of item>) : <name of DATABASE_OBJECT
structure>;

48

PD-6017 07/2012

Chapter 4 - ST Programs

For example:
InputVal AT %M(.Group 1.LimitPoint) :
PointValues.CurrentValueFormatted;
Where InputVal is the name of the variable, and AT %M indicates that the value is a read/
write value. (Group 1.LimitPoint) specifies the location of the point that is being referenced
(the 'LimitPoint' that is stored in the 'Group 1' Group). PointValues is the name of the
database object structure, and .CurrentValueFormatted is the specific field that needs to be
referenced.
This means that each point value can be referenced by a single line. The VAR list only needs
to contain the database object structure and one set of the fields that are to be included
there is no need to reference each field for each item.

When you create a database object structure, you need to adhere to these rules:

The database object structure has to be specified within a TYPE definition.

The TYPE definition has to be positioned at the top of the ST program, above the
PROGRAM information.

The name of the database object structure is the first part of the definition. It is followed
by DATABASE_OBJECT (<class name>) where <class name> is the name of the class
of database items.
You can view the classes of database items by using the ClearSCADA database
schema (see Working with the Database Schema, on page 19 in the ClearSCADA Guide
to the Database).

The list of referenced fields has to include field names that are identical to the field
names in the database. Each field name has to be followed by its data type.
NOTE: When using an SQL Query with a DATABASE_OBJECT structure, you have to
include the Id column as the first column in the SQL Query. This is because
DATABASE_OBJECT structures have an Id field, although this field is not referenced in
the DATABASE_OBJECT definition.

To end the list of fields, you have to enter END_DATABASE_OBJECT; To end the TYPE
definition, you must enter END_TYPE.

The Logic program has to be entered after END_TYPE

NOTE: You cannot access database aggregates via DATABASE_OBJECT structures. You
need to use standard read/write declarations to access database aggregates.

PD-6017 07/2012

49

Chapter 4 - ST Programs

Using SQL Queries to Access Direct Variables


You can use SQL Queries in your ST programs to access the ClearSCADA database.
NOTE: SQL Queries can only be used in ST programs to access the ClearSCADA database.
They cannot be used to access other databases.
ClearSCADA includes an extension to the IEC-1131 standard that allows you to use
Structured Query Language (SQL) to query the ClearSCADA database. When you use an
SQL Query in an ST Program, the SQL Query has to request data for the values specified
in the STRUCT data structure or DATABASE_OBJECT structure (to which the values from
the resultset are passed). This means that the data types specified in your STRUCT or
DATABASE_OBJECT structures have to match the data types of the columns in your SQL
query. When using DATABASE_OBJECT structures, the names of the values in the
DATABASE_OBJECT also have to match the names of the columns in the SQL query.
When you use an SQL query to provide values for a STRUCT data structure, the values
from the SQL query's resultset can only be read. STRUCT data structures cannot be used
for writing to the database or calling methods. The names of the values defined in the
STRUCT data structure can be anything you choose, but the data types of the values
have to match the data types of the columns in your SQL query.
You can use an SQL query and a DATABASE_OBJECT structure to read the values in the
resultset, write new values to the database objects represented by the rows in the
resultset, and access the methods for the objects represented by the rows in the
resultset. This is possible as each row of values returned for a DATABASE_OBJECT
structure represent the values of a specific item in the database.
The values and value types of the DATABASE_OBJECT structure have to match the
column names and value types defined in the SQL query (including the Id column which is
automatically added to DATABASE_OBJECT structures).
Typically, you will use DATABASE_OBJECT structures with SQL queries more often than
STRUCT data structures, as DATABASE_OBJECT structures allow for greater interaction
with the database.
Further Information
STRUCT data structures: Using Structured Data Types to Group Internal Values (see page
73).
DATABASE_OBJECT structures: see Using Database Object Structures to Access Direct
Variables (see page 48).
Using an ST Program to Call an SQL Query (see page 112).
Inserting, Updating, and Deleting Values by Using SQL in an ST Program (see page 116).

50

PD-6017 07/2012

Chapter 4 - ST Programs

Using Vectors to Access Direct Variables


You can use vectors to read from and write to array fields in the ClearSCADA database.
Vectors are similar to arrays in that they can contain multiple values, but they also have a
Length and Capacity that mean they can be used to only read or write a specific number
of values.
For more information, see Vectors, on page 81.

PD-6017 07/2012

51

Chapter 4 - ST Programs

Indirect Variables
Indirect variables are a ClearSCADA specific extension to the IEC 1131-3 language. They
allow an ST Program to perform calculations on tags that are specified at runtime as
opposed to hard coded tags that are used at compile time. At runtime, the program will
either prompt the user to enter a string (the string is the tag of an item in the database) or
will use a string from another program and use the string to calculate the tag for a direct
variable. For example, the user could enter the name of a point and the point would be
used in the ST program's calculation. Indirect variables are normally used with ST
Programs that are triggered by schedules and method pick actions.
To enter an indirect variable, you need to use this format:
VAR_INPUT
<Name of Variable> : STRING;
END_VAR
VAR
<Name of Variable> AT<AccessType>(<Parameter>{Input
Variable}<Parameter>): <TYPE>;
END_VAR
Where:

52

The VAR_INPUT declaration defines an input variable that is a String type.

The VAR declaration defines the indirect variable:

<Name of Variable> is the name that you allocate to the indirect variable. Do not
enter the angle brackets < >.

AT <AccessType> defines whether the indirect variable is read only (%I), write only
(%Q), or read and write (%M).

<Parameter> defines part of a tag. This is coded into the program and is not
affected by the user input/input from another program for the indirect variable. The
<Parameter> parts of the indirect variable are optional.

{Input Variable} represents the part of the tag that will be substituted by the string
that is entered by the user or provided by another program. The input variable has
to match the name of the input variable defined in the VAR_INPUT declaration and
has to be enclosed in braces { }.

<TYPE> is the type of the internal variable, for example, STRING.

PD-6017 07/2012

Chapter 4 - ST Programs

Example 1: Using Indirect Variables to Utilize Values provided by a User


This example demonstrates a very simple use of indirect variables. It uses an ST program
that adds the values of 2 inputs and then writes the result to an output point. The inputs are
provided by a user - when the ST program is executed, it prompts the user to define the
source of the input values.
For this example, the following database items are created:

An ST Program

Three Internal Analog Points (named Analog Point 1, Analog Point 2, and Analog Point
3)

A Mimic

The ST Program is configured to use indirect variables as follows:


PROGRAM Addition
VAR_INPUT
Input1 : STRING;
Input2 : STRING;
END_VAR
VAR
Point1 AT %I(.{Input1}.CurrentValue) : LREAL;
Point2 AT %I(.{Input2}.CurrentValue) : LREAL;
Output AT %M(.Analog Point 3.CurrentValue) : LREAL;
END_VAR
Output := Point1 + Point2;
END_PROGRAM

The indirect variables are '.{Input1}.CurrentValue' and '.{Input1}.CurrentValue'. The { }


instruct ClearSCADA to prompt the user for the source of the inputs. The period before the {
} means that ClearSCADA will search for the source within the same Group that contains the
ST program.
When executed, the program will add the current values of Input 1 and Input 2 and then
write that value to the 'Analog Point 3' point.
The Mimic is configured so that it contains a button that has shows Total Values and has a
pick action animation. When the button is selected, it will trigger the Execute action for the
ST Program. A text box is added to the Mimic and is configured to have a Value animation

PD-6017 07/2012

53

Chapter 4 - ST Programs

that sets the text box to display the CurrentValue property of the 'Analog Point 3' internal
point..

This button is animated to


have a Method pick action
that executes the program
when selected.

This text box has its Value property animated to show


the output of the program (the total value of the 2
inputs).

A user selects the 'Total Values' button, which triggers the Execution action for the ST
Program. ClearSCADA prompts the user to define Input 1 and Input 2 for the program.

In the Input 1 field, the user enters:


Analog Point 1
In the Input 2 field, the user enters:
Analog Point 2
The user then selects the OK button and the ST Program executes. It reads the current
values of Analog Point 1 and Analog Point 2, adds the two values together, and then writes
the result to Analog Point 3.
The text box on the Mimic is animated to show the current value of Analog Point 3, which
means it displays the result of the ST Program (which was written to the Analog Point 3
point). So if Analog Point 1s current value was 10 and Analog Point 2s current value was 8,
the ST program would write the value 18 to Analog Point 3 and this would be shown in the
text box on the Mimic.

54

PD-6017 07/2012

Chapter 4 - ST Programs

Example 2: Using Indirect Variables to Utilize Values provided by another Program


This simple example shows how indirect variables can be used to allow an ST program to
use values that are provided by another ST program.
Program 1 has the following code:
PROGRAM Program1
METHOD
Exec AT %M(.Program2.Execute):STRING;
END_METHOD;
Exec ('Analog Input Point');
END_PROGRAM
The first program is named Program1 and is used to perform a method. The method is
named Exec within the ST program. The Exec method declaration sets the method to
Execute argument. This means that the program will write a value. The value is written to the
Program2 program (which is the other ST program) which is also defined in the method
declaration. The type of value that will be written is a STRING.
The method declaration is finished with the END_METHOD keyword.
The Exec ('Analog Input Point'); line instructs the Exec method to write Analog Input Point as
the string value. This means that when Program 1 is executed, it will write an Analog Input
Point string to the Program2 program.
The Program2 program contains the following code:
PROGRAM Program2
VAR_INPUT
PointName :STRING;
END_VAR
VAR
CurValue AT %M({PointName}.CurrentValueFormatted): LREAL;
END_VAR
CurValue:=24.4;
END_PROGRAM;
Program 2 has two variables. The first is PointName, which is a string value. The VAR INPUT
keyword instructs the program that it is receiving an input value (the input value is received
from Program 1). In Program 2, the input value is called PointName and it is a string. The
data type for the VAR INPUT has to match the data type for the output of Program 1.
Program 2 automatically detects that it has a string input from Program 1 (there is only 1
input).

PD-6017 07/2012

55

Chapter 4 - ST Programs

The second variable is CurValue which is the CurrentValueFormatted of the item that has the
same name as the PointName variable. In this case, it means that the CurValue is the value
that is written to the current value of the database item that is named 'Analog Input Point'.
The CurValue is a long real value.
The variable declarations are ended by END_VAR.
The CurValue :=24.4; line sets the value that is written to the current value of the database
item that is named 'Analog Input Point'.

56

PD-6017 07/2012

Chapter 4 - ST Programs

Constants
Constant values are values that remain the same each time the program executes, such
as pi, time intervals, fixed text string etc. For example, if a program needs a point to
change state after a 2 minute pause, a constant can be used to define the 2 minute time
period. Although the time period does decrease from 120 seconds to 0 seconds as the
program executes, it is still represented by a constant as the time value is fixed as 120
seconds when the program is executed.
NOTE: Constant variables need to be separated from internal variables, direct variables and
function blocks in the VAR lists. This means that if you have a program that uses constants,
internal variables, direct variables, and function blocks, you will have at least 4 VAR lists1
for constants, 1 for internal variables, 1 for direct variables, and 1 for function blocks.
To enter a constant value, you need to use this format:
VAR CONSTANT
<Constant Name> : <Value Type> = <Value including code
characters>;
END_VAR

For example:
VAR CONSTANT
Timer:TIME := T#60s;
END_VAR

Where VAR CONSTANT instructs the program that the value is a constant, read only
value. Timer is the name of the constant, and TIME is the value type. T# is the code for
time values (see Time and Date Values, on page 68) and 60s is 60 seconds. The s for
seconds is lower case, as are time units. END_VAR is used to end the list of constants. If
there are other VAR lists after the constant list, the END_VAR should not have a
semi-colon at the end. However, if the constant list is the last list of variables for your
program, you have to add a semi-colon to the end, like this: END_VAR;
NOTE: Unlike internal and direct variables, constants can only be of a certain data type. Each
constant value has to be one of the Built-In Data Types (see page 63).

PD-6017 07/2012

57

Chapter 4 - ST Programs

Historic Values in ST Programs


You can use historic data variables in your ST programs and Function Block Diagrams.
The following sections explain how to add raw and processed historic variables, and
describe how to specify which historic values are used by your program:

Accessing Historic Direct Variables (see page 58)

Processed Historic Values in ST Programs (Historic Data Arrays) (see page 61)

Historic Functions and Arguments (see page 62).

Accessing Historic Direct Variables


You can use historic data variables in your ST programs and Function Block Diagrams.
You can refer to raw values or processed values that use historic algorithms (average
values for example).
In this section, we explain:

Raw Historic Values in ST Programs (see page 58)

Raw Historic Values in SQL Queries (see page 59)

Raw Historic Values in ST Programs


You can use raw historic values as inputs in your ST programs.
In ST Programs, you need to specify the raw historic variables in the VAR variables list.
The format for a historic variable needs to be:
<name of variable> AT %I(<Path of point>.Historic.<Historic
Function> (<arguments for historic function>) : <type of variable>;
For example:
LastHistoricValue AT %I(Analog Input.Historic.RawValue ('D-1H',
'H+1H', 0, TRUE)) : LREAL;
The variable definition (above) has the name LastHistoricValue. The %I is used as historic
values have to be read only.
Analog Input is the name of the point (which is located in the root directory). Historic is
required to instruct the program to use the point's historic data. RawValue is the historic
function (see Historic Functions and Arguments, on page 62 for more information).
('D-1H', 'H+1H', 0, TRUE) indicates the arguments for the RawValue function. Each
different type of function requires different arguments. The arguments are listed in Historic
Functions and Arguments (see page 62).
LREAL is used to indicate the type of value that is the output of the historic variable.
ATTENTION: You should construct your queries so that they query limited amounts of
historic data. Large and inappropriate query searches can severely affect system
performance and can potentially delay other system operations.

58

PD-6017 07/2012

Chapter 4 - ST Programs

Raw Historic Values in SQL Queries


You can use SQL Queries in your Logic programs to retrieve multiple raw historic values.
As the values are retrieved via an SQL Query, the Logic program only retrieves one value
at a timemultiple values are retrieved by using a 'loop' such as a WHERE or FOR
clause. This causes the program to retrieve the historic values in the specified range one
at a time, in turn.
To retrieve multiple historic values via SQL, you first need to define a TYPE. The Type
defines a record set which includes the fields for which values are to be returned. The
SQL query needs to be added to the VAR variables list, and it has to reference the record
set.

Example:
In this example, an SQL Query is used in an ST Program. It allows the ST Program to
retrieve a point's historic values between the start of the current hour (H in the OPC time
standard) and the end of the current hour (H+1H in the OPC time standard).
TYPE
HistoricRecord : STRUCT
Time : DATE_AND_TIME;
ValueAsReal : LREAL;
END_STRUCT;
END_TYPE

PROGRAM NewStructuredTextProgram
VAR
Historic AT %S(SELECT RecordTime, ValueAsReal FROM CDBHistoric
JOIN
CDBPoint USING (Id) WHERE CDBPoint.FullName = 'Random.Value'
AND RecordTime
BETWEEN { OPC 'H' } AND { OPC 'H+1H' }) : RESULTSET OF
HistoricRecord;
END_VAR;
END_PROGRAM

At the start of the program, there is a TYPE definition. This is used to create a record set.
In this case, the record set is named HistoricRecord and it is a structured data type
(STRUCT).
The values that are to be retrieved for the record set are specified in the TYPE definition:
Time and Value. The data types for these values are also specified (DATE_AND_TIME and
LREAL).
The VAR variables list contains the SQL Query that is used to define which point is to have
its historic values read. It also defines the time range for the valuesthe program will only
read the historic values for the period within the defined time range.

PD-6017 07/2012

59

Chapter 4 - ST Programs

We will look at each part of the variable definition in turn:


Historic AT %S
Historic is the name of the variable that includes the SQL Query. AT %S informs the
program that the variable uses an SQL Query.
(SELECT RecordTime, ValueAsReal FROM CDBHistoric
This is the first part of the SQL Query. It instructs the program to retrieve the values from
the RecordTime field and the ValueAsReal field in the CDBHistoric class. The RecordTime
value will be used as the Time value (specified in the TYPE definition at the start of the
program) and the ValueAsReal value will be used as the ValueAsReal value.
JOIN CDBPoint USING (Id)
As the CDBHistoric class does not contain the name of the required point, the SQL Query
needs to define a JOIN. The JOIN combines the CDBPoint class and the CDBPoint class
into a single table. To combine the point values and the historic values correctly for each
point, the SQL Query has to define the criteria by which the program will join the two
tables. The USING (Id) definition instructs the program to join the data in the CDBPoint
class to the data in teh CDBHistoric class based on the Id valuesthe Ids for the points
are identical in both the CDBHistoric class and the CDBPoint class.
WHERE CDBPoint.FullName = 'Random.Value' AND RecordTime BETWEEN {
OPC 'H' }
AND {OPC 'H+1H' })
The WHERE clause specifies the point for which historic data is to be retrieved. It also
specifies the fields for which values are to be returned. The BETWEEN clause specifies
the time rangethe SQL Query only returns values that were stored during the specified
time range.
: RESULTSET OF HistoricRecord;

Finally, the RESULTSET OF HistoricRecord instructs the program that the values that are
returned are to be the values for the HistoricRecord record set.

ATTENTION: You should construct your queries so that they query limited amounts of
historic data. Large and inappropriate query searches can severely affect system
performance and can potentially delay other system operations.

60

PD-6017 07/2012

Chapter 4 - ST Programs

Processed Historic Values in ST Programs (Historic Data Arrays)


You can use processed historic data values in your ST programs.
An ST program can be used to retrieve processed historic data from the ClearSCADA
database and return the processed values into a historic array.
Historic arrays allow a Logic program to use multiple historic values as inputs. The array
acts as a table, with each returned value occupying one row of the table. You can then
use your ST program Logic to use the returned values.
NOTE: Historic Arrays can only be used as single dimension tables with one column. Unlike
arrays for current data, historic arrays cannot return values that can be used in a matrix.
When you use processed historic values in an ST program, you need to enter a variable
for the array in the VAR variables list. The variable has to be defined using the following
format:
<name of variable> AT %H(<path of point>.Historic;<name of historic
algorithm>; <start of time range>;<frequency of values>) : ARRAY
[<number of first value in range>..<number of last value in range>]
OF <data type of variable>;
Example:
The following variable is used to return the average historic value for each hour in the day:
HourlyAverage AT %H(AnalogInput.Historic;Average;D-1D;1H) : ARRAY
[0..23] OF LREAL;
Where HourlyAverage is the name of the variable. %H is required as this instructs the
program to use historic data.
AnalogInput is the name of the point that has the historic data that the ST program is going
to use. Historic;Average; indicates that the program will use the values that are stored for the
point's Historic.Average tag. D-1D;1H indicates the time period for the historic datathe
values for each hour (1H) starting from the beginning of yesterday (D-1D).
ARRAY [0..23] is used to instruct the program that the values will be returned as an array,
and that there will be 24 values (0-23 inclusive). OF LREAL; indicates that the values in the
array will be long real values.
The historic array returns 24 average values, for example,
A [0] : = 3.5;
A [1] : = 3.9;
A [3] : = 3.6;
A [4] : = 3.6;
A [5] : = 3.2;
A [6] : = 3.7;
and so on.
Each of these values can be used in the ST Program.

PD-6017 07/2012

61

Chapter 4 - ST Programs

Historic Functions and Arguments


You need to use historic functions to specify which historic values are used by your
program. Each historic function requires values for its arguments (as shown below). You
have to include each argument when you use a historic function in an ST program or
Function Block Diagram.
The arguments include StartTime and EndTime which define a time span, RecordIdx
which is the number used to identify one historic value, and Forward which is used to
instruct the program to move through a series of historic values. Forward arguments can
have values of True or False (True means proceed forward to the next historic record;
False means proceed backwards to the previous historic record).
You will need to use the following information when using a historic function:

Function

Arguments

Returns

RawCount

StartTime, EndTime

The number of values between the


StartTime and EndTime

RawValue

StartTime, EndTime,
RecordIdx, Forward

Value between StartTime and


EndTime at RecordIdx

RawTimeStamp

StartTime, EndTime,
RecordIdx, Forward

Time value between StartTime and


EndTime at RecordIdx

RawQuality

StartTime, EndTime,
RecordIdx, Forward

Quality value between StartTime and


EndTime at RecordIdx

RawQualityDesc

StartTime, EndTime,
RecordIdx, Forward

Quality description between


StartTime and EndTime at RecordIdx

RawCountRange

StartTime, Interval

The number of values between


StartTime and StartTime+Interval at
RecordIdx

RawValueRange

StartTime, Interval,
RecordIdx, Forward

Value between StartTime and


StartTime+Interval at RecordIdx

RawTimestampRange

StartTime, Interval,
RecordIdx, Forward

Value between StartTime and


StartTime+Interval at RecordIdx

RawQualityRange

StartTime, Interval,
RecordIdx, Forward

Value between StartTime and


StartTime+Interval at RecordIdx

RawQualityDescRange

StartTime, Interval,
RecordIdx, Forward

Value between StartTime and


StartTime+Interval at RecordIdx

ProcessedValue

StartTime, EndTime,
AggregateId

Historic value between StartTime and


EndTime using AggreagteId.

For a list of the historic algorithms that are available, see OPC Historic Aggregates
(Algorithms), on page 69 in the ClearSCADA Guide to Expressions.
Further Information
Raw Historic Values in ST Programs: See page 58.
Add Raw Historic Values to Function Block Diagrams: See page 173.

62

PD-6017 07/2012

Chapter 4 - ST Programs

Built-In Data Types


There are many different types of built-in value (literal value) that you can add to your
Logic programs, including:

Integer Values (see page 63)

Floating Point Values (see page 68)

Binary Values (see page 70)

Time and Date Values (see page 68)

String Values (see page 71).

The built-in value types, sometimes referred to as literal data types, use a specific name
to define the data type. For example, text values are STRING values. You can use Derived
Data Types (see page 72) to allocate different names to value types.

Integer Values
Integer values are whole numbers. Typically, they are used to represent amounts such as
counts. In this section, we explain:

Integer Types (see page 64)A brief description of the various types of integer you can
use.

Integer Formats (see page 65)Explains how to define the base for an integer value.

Typed Literals (see page 66)Describes how to assign appropriate types of integer for
the literal numbers in a program.

PD-6017 07/2012

63

Chapter 4 - ST Programs

Integer Types
Integer types are often used when defining the variables in an ST program. They allow you
to specify the range of permissible values for a variable.
There are two varieties of integer typesigned and unsigned. Signed integers allow
positive and negative numbers to be used, whereas unsigned integers only allow positive
numbers. Each variety of signed and unsigned integer is suited to representing a specific
range of values and bits (see table below).

Integer Type

Bits

Range

SINT (Short Integer)

-128 to +127

INT (Integer)

16

-32768 to 32767

DINT (Double Integer)

32

-231 to +231 -1

USINT (Unsigned Short Integer)

0 to 255

UINT (Unsigned Integer)

16

0 to 216-1

UDINT (Unsigned Double Integer)

32

0 to 232-1

When you add integers to your Logic programs, you need to use a suitable type of integer.
You should consider the possible range of counts, then use the table above to determine
which type of integer is appropriate for covering the expected range.
When using literal values in a program, you need to pay special attention to the integer
type you use, as literal values use the smallest type of integer possible. For example, if
you use the literal value 2, it will be a SINT by default. As the result of a calculation is the
same type as the largest operand in the calculation, this can cause confusion due to the
result type not supporting the range needed for the result of the calculation. For example,
for 2**7 (which is 27), you may expect 128 as a result, but the result is -1. This is because
the smallest type of integer for 2 is a SINT and the smallest type of integer for 7 is also
SINT. As the type of value for the highest operand (7) is SINT, the result of the calculation
is also SINT. But as SINT can only support the range -128 to +127, it cannot store the
result of 128. Instead, it returns -1.
For this reason, you need to be careful when defining literal values and you should
consider the required integer type for the result. There are two possible ways of working
around these situations:

You can use internal variables for the values (see Adding an Internal Variable to an ST
Program, on page 41)

You can cast one of the operands, for example, SINT_TO_DINT(2) **7.

Further Information
Integer Formats: See page 65
Typed Literals: See page 66.

64

PD-6017 07/2012

Chapter 4 - ST Programs

Integer Formats
When you are specifying an integer value, either as a constant or as part of a variables
definition, you need to specify the base. The base defines the type of value for the integer,
and can be:

DecimalDecimal values can use negative and positive signs, no signs, or underscores
to represent commas. For example:
-2100, 2100, +2100, 2_100.

BinaryBinary values are base 2 values. You need to use 2# to indicate that the values
are base 2, and you need a value for each bit. For example:
2#1111_1111 is 255 (8 bits)
2#0000_1110 is 14 (8 bits)

OctalOctal values are base 8 values. You need to use 8# to indicate that the values
are base 8, for example:
8#377 is 255
8#030 is 24.

HexadecimalHexadecimal values are base 16 values. You need to use 16# to indicate
that the values are base 16, for example:
16#FF is 255
16#B8 is 184

Further Information
Integer Types: See page 64
Typed Literals: See page 66

PD-6017 07/2012

65

Chapter 4 - ST Programs

Typed Literals
When you use constant literal numbers in an ST program, they are automatically assigned
a type. The type that is assigned is the integer type that has the lowest range that can
support the literal number. For example, if you enter 200 as a constant literal, the 200 will
automatically be assigned a USINT integer type (SINT integers only support -128 to 127,
so cannot be used. USINT is the next lowest integer type and as it supports 0 to 255, it
can be used).
The result of a calculation that uses constant literals is also assigned a type automatically.
The integer type that is assigned to the result matches the integer type with the highest
range in the expression. So, if the expression is 150+400, the result is assigned the INT
integer type (the 150 is assigned USINT and the 400 is assigned INT).
The automatic assigning of integer types can cause unexpected results, as the result of
an expression may be a number that exceeds the range of the integer type for the result.
This causes an overflow. For example, with the following program, you would expect the
value of A to be 300 (the result of 100 x 3):
VAR
A : INT;
END_VAR
A := 100 * 3;

However, in this case, the value of A is 44, even though the integer type for A has been
defined as INT, which supports 300. The reason for this is that in the expression 100*3,
SINT is used for both 100 and 3 (as SINT supports the range -128 to 127). This means
that the result of the expression is also SINT as it matches the integer type of the highest
number in the expression. As the expected result of the expression is 300, this means
there is an overflow - the result value exceeds the range supported by the result integer
type. And so 100*300 results in 44. The 44 for the SINT result is then converted into an
INT as declared for A at the start of the program.
ClearSCADA allows you to use typed literals to avoid this situation. By using typed literals,
you can declare a specific integer type for each constant literal in your program. When
there is a declared integer type for a constant literal, the program uses the declared
integer type; the smallest integer type is not assigned automatically.
To declare a specific integer type for a constant literal, you need to use the following
syntax:
<Integer Type>#<Constant Literal>
Where:

66

<Integer Type> is the integer type that will be assigned to the constant literal. Do not
enter the angle brackets < >.

<Constant Literal> is the number to be used in the expression. Do not enter the angle
brackets < >.

PD-6017 07/2012

Chapter 4 - ST Programs

So, if we take the example that we used before, 100*3, the program could be defined like
this:
VAR
A : UINT;
END_VAR
A := INT#100 * 3;
As you can see, the 100 is declared as an INT whereas the 3 is assigned a SINT
automatically (the lowest integer type that supports 3). The code would also produce the
expected result if the 100 was SINT and the 3 was INT or if both 100 and 3 were INT. This
is because one of the constant literals has to be of an integer type that is also large
enough to support the expected result.
So, as the expression has an INT and a SINT for its constant literals, the result is assigned
an INT (the highest integer type used by the constant literals in the expression). The
expected result of the expression - 300 - is supported by integer type of the result (INT,
which supports -32, 768 to +32, 767). This means that the result of the expression does
not overflow and is the expected 300.
The result of 300 is then converted from INT to UINT as A was declared as a UINT at the
start of the program. As UINT supports the range 0 to 65,535, the 300 value is stored by
the A variable. However, had the integer type of A been declared as an integer type that
does not support the result of 300, the value for A would be truncated. To obtain the
expected result, you need to use appropriate integer types for:

The result of the expression in the program. Remember that it is assigned the same
type of integer as the highest integer type used by the constant literals in the
expression.

The variable that is used to store the result of the expression. The variable has to be
assigned an integer type that supports the expected result of the expression, otherwise
the expression may produce the correct result but the result will be stored as a
truncated value.

Further Information
Integer Types: See page 64
Integer Formats: See page 65.

PD-6017 07/2012

67

Chapter 4 - ST Programs

Floating Point Values


Floating point values are analog values (also referred to as REAL values). They are used
for values that can be any number within a range, for example, temperature values.
There are 2 types of floating point value (REAL and LREAL). For more information, see
Floating Point Types, on page 68.
For information on the formatting rules that apply to floating point values, see Floating
Point Formats, on page 68.

Floating Point Types


You may use floating point types when defining the variables in an ST program. The
floating point types specify the range of values that is permitted for a variable.
There are two types of floating point:

Floating Point Type

Bits

Range

REAL (Real numbers)

32

1038

LREAL (Long real numbers)

64

10308

NOTE: REAL values have a precision of 1 in 223. LREAL values have a precision of 1 in 252.
When you add floating point values to your Logic programs, you need to use a suitable
type of floating point value. You should consider the possible range of numbers, then use
the table above to determine which type of floating point value can cover the expected
range.

Floating Point Formats


When you are specifying a floating point value, enter a normal decimal. This applies
whether you are using a floating point value as a constant or as part of a variables
definition. For large and small values, you can use E or e to denote the exponential value
of ten, for example, 0.9E20 or 0.3765e+14.

Time and Date Values


There are several types of time and date value that you can use in your Logic programs.
You can use the time and date values to specify:

Time durations

Calendar dates and specific times

When you enter a time or date value, you need to specify the type of value (see Time and
Date Types, on page 69) and the amount for the value (see Time and Date Formats, on
page 69).

68

PD-6017 07/2012

Chapter 4 - ST Programs

Time and Date Types


There are 4 types of time and date value:

Time and Date Type


TIME

Bits
Varies

Purpose
Use to store an amount of time that begins
after an event takes place. For example, use
TIME to store a timeout that occurs when
plant is in a specific state.
The time is stored as days, hours, minutes,
seconds, and milliseconds.

DATE

Varies

Use to store a calendar date.

TIME_OF_DAY (or TOD).

Varies

Use to store a time (real time clock).


TIME_OF_DAY is also be referred to as TOD.

DATE_AND_TIME (or DT)

Varies

Use to store the date and time of day (real


time clock)

When you define a time and date value, you need to use a specific format (see Time and
Date Formats, on page 69).

Time and Date Formats


Each type of data and time value needs to be entered in a specific format. There are
special codes that allow the program to recognize the type of time or date value being
used, and there are conventions for entering the times and dates.
The format conventions are:

TIMEThere are two formats for TIME values: short and long. The short format uses T#
to represent TIME, whereas the long format uses TIME#. Usually, the short format is
used, but you may wish to use the long format for its improved readability.
Both formats use these characters:

dday

hhours

mminutes

sseconds

msmilliseconds

For example, T#12d3h2s is 12 days, 3 hours, and 2 seconds in the short format. In the
long format, the same amount of time is TIME#12d_3h_2s.

DATEAs with TIME values, there are short and long formats for DATE values. The
short format uses D# to represent DATE, whereas the long format uses DATE#.

TIME_OF_DAYAs with other types of time and date values, TIME_OF_DAY values can
use short and long formats. The short format uses TOD# to represent TIME_OF_DAY
whereas the long format uses TIME_OF_DAY#.

DATE_AND_TIMEAs with other types of time and date values, DATE_AND_TIME


values can use short and long formats. The short format uses DT# to represent
DATE_AND_TIME whereas the long format uses DATE_AND_TIME#.

PD-6017 07/2012

69

Chapter 4 - ST Programs

Binary Values
Digital values (binary values) are stored in bit strings. There are 5 types of bit string.
When you need to use a binary value in your Logic program, you have to define the type
of binary value and the actual value. For more information, see Binary Value Types, on
page 70 and see Binary Value Formats, on page 70.

Binary Value Types


There are several types of binary value:

Binary Type

Description

Bits

Range

BOOL

Boolean value

0 OR 1, True or False

BYTE

String of 8 bits

0 to 255

WORD

String of 16 bits

16

0 to 65536

DWORD

String of 32 bits

32

0 to 232

NOTE: For Boolean values, 0 is False and 1 is True.


You need to define the type of the value when you define a binary value in the program.

Binary Value Formats


When you define a binary value, you need to enter a valid value. This can be 0, 1, TRUE,
or FALSE.
There are no formatting requirements for binary values. To define the value of a binary
value type, you have to set its value to one of the following:

70

TRUE

FALSE

PD-6017 07/2012

Chapter 4 - ST Programs

String Values
If you need to use a text value in your program, you need to define the value as a STRING.
STRING values are used to store text. For example, STRING values are often used to
store messages such as descriptions, batch information, and messages that are used
with string points in the ClearSCADA database.
STRING values can contain printable and non-printable characters, and have to be
enclosed within single quotes like this: 'example'.
Strings allow a maximum of 255 characters unless you specify a different fixed length in
the VAR list.
Example:
VAR
WarningMessage: STRING [60]:= 'Attention. The state has changed';
END_VAR

In this example, WarningMessage is the name of the STRING value. STRING [60] instructs
the program that the value is a string value and has a maximum of 60 characters. 'Attention.
The state has changed' is the value of the stringthe text that is stored.

There are special characters that are reserved. These characters allow you to insert a
non-printable character, a dollar sign, quotation marks, etc. The special characters are:

Character Code

Description

$<hexadecimal number>

The character that is represented by the


hexadecimal number, for example, '$32' is 2.

$$

A single dollar sign $

$'

A single quote character '

$L or $l

A line feed character

$N or $n

New line character

$P or $p

Form feed, new page

$R or $r

Carriage return character

$T or $t

Tab character

PD-6017 07/2012

71

Chapter 4 - ST Programs

Derived Data Types


ClearSCADA supports derived data types for use in ST programs (and Function Block
Diagrams that include ST programs). The derived data types are designed to make it
easier for you to read and write structured text programsthey allow you to name and
group values that are used by your ST programs.
This section explains:

Using Derived Data Types to Create Names for Types of Value (see page 72).

Using Structured Data Types to Group Internal Values (see page 73).

Using Enumerated Data Types to Create Names for State Values (see page 77).

Arrays (see page 80)

Vectors (see page 81).

Using Derived Data Types to Create Names for Types of Value


You can create derived data types so that types of values in your programs have
meaningful names.
For example, the value from a pressure gauge is a REAL value. By creating a new data
type for this value, you can allocate it a more meaningful name such as PRESSURE.
Example:
TYPE
PRESSURE: REAL;
END_TYPE

As you can see, new data types need to be included in a TYPE definition. The TYPE
definition has to come before the PROGRAM definition.
In the example, only one new data type has been created, so there is only one entry within
the TYPE definition. However, if you needed to add more new data types, you would add
them to the existing TYPE definitionyou do not need a TYPE definition for each
separate data type.
When you define a new data type, you need to use this format:
<name of new data type>: <type of value for the data type>;
So, in the example above, the <name of new data type> is PRESSURE and the <type of
value for the data type> is REAL.
When you have created a new data type, you can use it in your Logic program. To do this,
you need to add it to the list of variables (VAR).

72

PD-6017 07/2012

Chapter 4 - ST Programs

Using Structured Data Types to Group Internal Values


Structured Data Types allow you to group internal values (values that are used by the
program but are not written to an item in the database). This means that when you create
a data structure, you create a custom data type that contains several internal values. You
can then refer to these values in your Logic program by referencing the data structure.
NOTE: You cannot use structured data types for direct variables (values that need to be
written to items in the ClearSCADA database).
The main advantages of structured data types is that they allow you to group internal
values and they reduce the number of variables you need to define.
When you create a data structure, you need to define the values that are to be grouped
within STRUCT and END_STRUCT keywords. The STRUCT and END_STRUCT keywords
have to be defined within the TYPE and END_TYPE definition.
You should list the values that you want to be grouped in the data structure within the
STRUCT and END_STRUCT keywords. As with other value definitions, you need to enter
the name of the value, then a colon (:), then define the type of value. Each value has to be
separated by a semi-colon (;).
TYPE <data structure name>
STRUCT
<value name>:<value type>;
<value name>:<value type>;
<value name>:<value type>;
END_STRUCT;
END_TYPE

When you have defined the data structures, you need to add them to the VAR variables
list. To do this, simply create a variable name for the value and then use the name of the
data structure when you define the type of value. You need to define each data structure
as a variable (unless 'nested' data structures are usedwe will explain these later in this
section):
VAR
<Variable name>:<data structure name>;
<Variable name>:<data structure name>;
<Variable name>:<data structure name>;
END_VAR

When you have defined the VAR variables list, you can refer to the values included in the
data structures. To do this, use the following format when referencing a value in your
Logic program:
<Variable name>.<value name>

PD-6017 07/2012

73

Chapter 4 - ST Programs

As with many of the Logic structures, it is easier to understand the concepts and the
formatting by referring to an example. The example in this section uses data structures to
group the values that can be used for pumps in the water industry. It shows:

74

How data structures can be used to group values

How data structures need to be defined

How data structures need to be added as variables in the VAR list

PD-6017 07/2012

Chapter 4 - ST Programs

Example of Data Structures


Let us assume that you want to create a Logic program that needs to use internal values
for a pump. It needs to use the pump status, alarm count, and latest value. You can group
these values in a data structure:
TYPE PUMP:
STRUCT
Status: BOOL;
AlarmCount: INT;
LatestUpdate: DATE_AND_TIME;
END_STRUCT;
END_TYPE
The name of the data structure is defined as PUMP. For each internal variable, the name
of the value is defined and so is its data type (BOOL, INT, DATE_AND_TIME). The data
structure is defined within STRUCT and END_STRUCT keywords which are enclosed
within the TYPE and END_TYPE keywords.
The data structure feature becomes more useful when the data structure needs to be
used to represent the internal values for multiple items. So, rather than using the PUMP
data structure for 1 pump, let's look at how it can be used for 3 pumps:
TYPE
STRUCT PUMP:
Status: BOOL;
AlarmCount: INT;
LatestUpdate: DATE_AND_TIME;
END_STRUCT;
END_TYPE

The 3 pumps can refer to the PUMP data structure. By grouping the data for each pump
into a data structure, it is easier to recognize the source of each value. It is also easier to
use the values in the program.
Once the data structure has been defined, it needs to be added as a variable in the VAR
list. As with other types of variable, each data structure requires a variable name. As the
PUMP data structure needs to be used to provide the values for 3 separate items, there
has to be 3 variables with PUMP as their data type:
VAR
Pump1Data :PUMP;
Pump2Data: PUMP;
Pump3Data: PUMP;
END_VAR
Pump1Data is the name allocated to the PUMP data structure for Pump 1. The other
variables have similar names, for example, Pump3Data uses PUMP to access data for
Pump 3. The data types for the data structure variables have to match the data structure
name.

PD-6017 07/2012

75

Chapter 4 - ST Programs

In the Logic program, any references to the values in the data structures use the following
format:
<Variable name>.<value name>
This means that a reference to the AlarmCount value of Pump 3 would be entered as:
Pump3Data.AlarmCount
A reference to the LatestUpdate value of Pump 1 would be entered as:
Pump1Data.LatestUpdate

76

PD-6017 07/2012

Chapter 4 - ST Programs

Using Enumerated Data Types to Create Names for State Values


You can use the enumerated data types facility to apply names to state values. This can
be useful as it allows state values to have names that are more descriptive of the value.
For example, you can use an enumerated data type to define the state values of a valve
as Open and Closed rather than 0 and 1.
Enumerated data types make it easier to understand a program. The more descriptive
state values mean it is easy to work out what states the program uses. It also means you
can obtain the correct state numbers without referring to the ClearSCADA Database
Schema, as you can use any state name to reference a state number. For more
information on the ClearSCADA Database Schema, see Working with the Database
Schema, on page 19 in the ClearSCADA Guide to the Database.
Another advantage of enumerated data types is that they reduce the amount of alterations
you need to make if you decide to change the states. For example, a valve could have
Open to represent state 0 and Closed to represent state 1. If you changed the states so
that state 0 meant the valve was closed and state 1 meant the vale was open, you would
only need to change the enumerated data types in TYPE sections of your Logic programs.
If you did not use enumerated data types, you would need to change the states of every
instance of the valve's values.
Enumerated data types have to be defined within the TYPE and END_TYPE keywords.
The format for an enumerated data type is:
<Enumerated data type name>:(<state name>, <state name>);
For example:
PUMP_STATES:(STOPPED, RUNNING, FAILED, INVALID);
The STOPPED state name corresponds to State 0, RUNNING corresponds to State 1,
FAILED corresponds to State 2, and INVALID corresponds to State 3. As you have used
state names to reference the various states, you cannot reference the states by number.
For example, you cannot reference the RUNNING state as 1.
The number of <state name> entries varies according to the number of states for the item.
In each case, the first state name corresponds to State 0, the second state name
corresponds to State 1, the third state name corresponds to State 2 and so on.
You can use any names for the states; there is no need to match the state names to the
names used in the ClearSCADA Database Schema. However, if you are defining multiple
enumerated data types, you need to use different names (an enumeration cannot contain
the same name as another enumeration).

PD-6017 07/2012

77

Chapter 4 - ST Programs

Example:
There are enumerations for a valve and a pump. The valve has 4 states that are defined in an
enumeration (OPEN, CLOSED, FAILED, and INVALID).
The pump also has 4 states (STOPPED, RUNNING, FAILED, and INVALID). In the pump
enumeration, the STOPPED and RUNNING states are acceptable, but the FAILED and
INVALID state names cannot be used as the same names are used for the valve
enumeration.
To avoid this situation, we suggest that you use item specific state names. So, for the valve
and the pump, you would use enumeration states such as these:
Valve (VALVE_OPEN, VALVE_CLOSED, VALVE_FAILED, VALVE_INVALID);
Pump (PUMP_STOPPED, PUMP_RUNNING, PUMP_FAILED, PUMP_INVALID);
You can use the same enumeration state names for items of the same type. So if there were
two different pumps, you could use PUMP_STOPPED, PUMP_RUNNING, PUMP_FAILED,
and PUMP_INVALID as long as both pumps have the same states.

78

PD-6017 07/2012

Chapter 4 - ST Programs

Using Nested Data Structures


You can 'nest' data structures within other data structures. This is useful for creating a
sub-group of values. For example, if a Logic program needs to use the values of 3
different pumps, it may have a data structure for a pump. The PUMP data structure
contains definitions for CurrentState: REAL; and UpdateTime: TIME; variables. The
variables for each of the pumps will be set to use the PUMP data structure.
The Logic program also needs to use the name of the engineer that last calibrated each
pump, and the time at which the calibration took place. To achieve this, another data
structure is created:
STRUCT Calibration_Struct
CalibDate: DATE_AND_TIME;
Engineer: STRING;
END_STRUCT;
The Calibration_Struct data structure is included within the TYPE and END_TYPE
definition, and is positioned above the PUMP data structure. (Data structures that are to
be nested within other data structures have to be entered above the non-nested data
structures).
The PUMP data structure is then altered to include the Calibration_Struct data structure:
STRUCT PUMP
Calibration: Calibration_Struct;
CurrentState: REAL;
UpdateTime: TIME;
END_STRUCT;
So, in the PUMP data structure (shown above), the Calibration : Calibration_Struct; line
embeds the Calibration_Struct data structure within the PUMP data structure.
The VAR variables list then needs to include the PUMP data structure. The
Calibration_Struct data structure is not needed as a variable as it is included in the PUMP
data structures:
VAR
Pump1Data: PUMP;
Pump2Data: PUMP;
Pump3Data: PUMP;
END_VAR

In the Logic program, references to the values of the pumps will use the following format:
<Name of variable>.<name of field>
For example, Pump1Data.CurrentState is a reference to the current state value of Pump 1.
To reference the calibration values, use the following format:
<Name of variable>.<name of nested data structure>.<name of field>
For example, Pump1Data.Calibration_Struct.Engineer is a reference to the name of the
engineer that calibrated Pump 1.

PD-6017 07/2012

79

Chapter 4 - ST Programs

Arrays
You can use arrays to form a matrix of values. The matrix can be multidimensional and
can contain Data Structures, Enumerated Data Types, New Data Types, values from other
Arrays and any of the built-in value types such as INT, REAL, and STRING.
NOTE: Arrays can only be used with internal variables. For direct variables, you have to use
the VECTOR keyword, see Vectors, on page 81.
To create an array, define the Array within the VAR and END_VAR keywords using the
following format:
<Array Name> : ARRAY [<x dimensions>, <y dimensions>] OF <Value Type
or Value Name>;
For example:
VAR
TEMPERATURE_MATRIX:ARRAY[1..4,1..5] OF REAL;
END_VAR
In this example, the name of the array is TEMPERATURE_MATRIX. [1..4,1..5] defines the
columns and rows of the matrix (1x4 columns, 1x5 rows) and OF REAL; defines the type
of values that are to be entered in the matrix.
When it comes to defining values for each of the matrix cells, you need to define the value
in the following format:
<Value name>[<matrix grid reference>]:=<value>;
For example:
EngineTemperature[2,5]:=42.5;
This would place the value 42.5 in the second column in cell 5, like this:

42.5

In ViewX, you can use the Debug tool to view the values for each cell (see Debugging an
ST Program or ST Library, on page 124).

Further Information
Vectors (see page 81).

80

PD-6017 07/2012

Chapter 4 - ST Programs

Vectors
A vector is a special type of STRUCT that has an array as its value. It allows you to read
values from and write values to an array in the database. It also allows you to define the
source of array values for use by methods that require array values, such as the Set
Forecast method. To use a vector in an ST program, you need to use the VECTOR
keyword.
Vectors are similar to arrays, except that they have three properties:

CapacityThe maximum number of values that can be read/written by the vector

LengthThe actual number of values that are read/written by the vector. This can be
defined in the declaration or will be calculated automatically.

ValueThe array of the vector. The vector's array will use values that are read from an
array in the database, such as an array variable database item.

The syntax for a vector is:


VECTOR[value range] OF <Value Type>;
Where:

VECTOR is the keyword

[value range] is the maximum number of values that can be read or written. For the
value range, you have to start with 0 (the first value) and end with the number of the last
permitted value. Use two points between the first and last values, for example, [0..99]
sets the value range to 100 values (0 being the first value, 99 the hundredth value).

OF <Value Type> defines the value type of the direct variable that is read or is being
written to. For example, OF UDINT; or OF DINT;

For example:
VAR
V AT %M(.Values) : VECTOR[0..99] OF DINT;
END_VAR
Sets the V variable to represent the vector. The source of the vector's array is defined as
the database item named 'Values', and the capacity of the vector is defined as [0..99]. The
value type of the vector's array is set to DINT. This means that the Capacity property of
the vector is set to 100 (0 to 99 inclusive) and the Value property is set to reference the
array of the 'Values' database item. The Length is not defined, but will be calculated
automatically - it will match the number of values that are actually read from the 'Values'
item's array. So, if there are 10 values in the array, the Length will be set to 10.
You can also write to the properties of a vector in the same way as you would write to the
properties of any item, for example, you can set the Length of a vector by using
<variable>.length := <length value>. Where <variable> is the name of the variable that
represents the vector and <length value> is the number value for the length or is a
calculation to determine the length.

PD-6017 07/2012

81

Chapter 4 - ST Programs

VAR
V AT %M(.Values) : VECTOR[0..99] OF DINT;
V.Length := 6;
END_VAR
In the example above, the Length of the vector is set to 6 so that only 6 values are read
from or written to the array.
NOTE: The Capacity property of a vector is read-only.

Examples:
Example 1 - Using a Vector to Read from an Array
The following example shows how the VECTOR keyword can be used in an ST program that
reads from an array and uses the array values to calculate an average value.

In this program, the variable named Values can read to and write from the direct variable
named Values (which is a variable array database item). As the direct variable is an array, a
vector is used to read and write the values. The VECTOR keyword is used and has a value
range of one hundred values (0..99).The value range is the capacity of the vector. The value
type of the array is DINT.
The Average variable is a read and write direct variable associated with the Average
database item (which is a variable double database item). The data type for the average
variable is LREAL.
An internal variable, SUM, is used to store the result of the average calculation in the
program. The SUM variable is of the data type DINT.
The code for calculating the average value and writing it to the Average variable double
database item is:
Sum := 0;
FOR I := 0 TO Values.Length -1 DO
Sum := Sum+Values.Value[I];
END_FOR;
Average := DINT_TO_LREAL (Sum) /DINT_TO_LREAL (Values.Length);

82

PD-6017 07/2012

Chapter 4 - ST Programs

So the program starts by initializing the Sum value to 0. The internal variable I is used to
represent the index numbers of the elements in the array (each array element can contain a
value, for example, the first element in an array has an index number of 0 and can contain
one value; the second element has an index number of 1 and can contain one value and so
on). The total number of array elements is defined by the Length value of the Values variable
(the Values variable is a direct variable that represents the Values array database item). So,
for the array elements with index numbers between 0 and the Length amount minus 1, the
ST program will perform the calculation:
Sum := Sum+Values.Value[I];
When the ST program has read the values from the Values array, it calculates the average
which is the Sum value divided by the Length value of the vector. The result of this
calculation is stored in the Average variable database item.
Let's assume that the Values array database item has 5 values (stored in its 5 elements).
When the ST program runs, it first initializes the Sum value at 0 and then begins to read the
values in the array. It begins by reading the value from the array element with index number
0. This value is stored in the internal variable, Sum. The ST program then reads the value
from the array element with index number 1 and adds the value to the Sum value. This is
repeated until the ST program has read the values from the array elements with index
numbers 0, 1, 2, 3, and 4. Although the ST program can read up to 100 elements ([0..99]), it
can read fewer elements as required; it does not have to read 100 elements.
When the ST program has read the five array elements in the Values array database item, it
calculates the average value. To do this, it divides the Sum amount by the Length value of
the Vector. The result of this calculation is written to the Average variable database item.

PD-6017 07/2012

83

Chapter 4 - ST Programs

Example 2 - Using a Vector to Write to an Array


In this example, the VECTOR keyword is used to allow an ST program to calculate new
values and write them to an array database item.

In the VAR list, a single variable is defined. The variable is named Fib and it is a direct
variable to the database item named Fibonacci Sequence (which is a variable array database
item). The variable is defined as a VECTOR with a capacity of 100 values ([0 to 99]) and is of
the data type UDINT.
The first part of the IF statement declares that if the length of the vector is 0, then the value
in the array element with index number 0 is set to 0, and the length of the vector is changed
to 1.
The second part of the IF statement declares that if the length of the vector is 1, then the
value in the array element with index number 1 is set to 1, and the length of the vector is
changed to 2.
The final part of the IF statement only applies if the length of the vector is between 2 and 99.
If the length is between 2 and 99, the value for that element is the value of the previous
element plus the value of the element before that, and the vector length is increased by 1.
So, if the Fibonacci Sequence array item contains no values, when the ST program first runs
it will set the number of values the array can contain to 1 and will set the value for the only
element in the array to 0.
The next time the ST program is executed, it will detect that the Fibonacci Sequence array
item contains a single value and so the vector has a length of 1. This means that the ST
program will increase the number of array elements to 2. The element with index number 0
will contain the 0 that was already in the array and the element with index number 1 will
contain a new value defined by the ST program, in this case, 1.
The next time the ST program is executed, it will detect that the Fibonacci Sequence array
item contains two values and that the vector has a length of 2. The ST program will increase
the length of the vector by one to accommodate a new value and will then calculate the new
value. The new value is the total of the previous two values stored in the array. In this case,
the previous two values are 0 and 1 and so the new value is 1. The new value is stored in the
element with index number 2.

84

PD-6017 07/2012

Chapter 4 - ST Programs

The next time the ST program is executed, it will detect that the Fibonacci Sequence array
item contains three values and that the vector has a length of 3. The ST program will
increase the length of the vector by one to accommodate a new value and will then calculate
the new value. The new value is the total of the previous two values stored in the array. In this
case, the previous two values are 1 and 1 and so the new value is 2. The new value is stored
in the element with index number 3.
Each time the ST program is executed, it will increase the length of the vector by 1 and
calculate a new value. When the length of the vector is 99 (and so there are 100 values in the
array), the ST program will no longer create new values or increase the length of the vector.

PD-6017 07/2012

85

Chapter 4 - ST Programs

Example 3 - Using Vectors with Methods that Require Values in an Array


In this example, a vector is used to read the values from an array variable database item. The
values that are read are used as the values for the SetForecast method on a Forecast
database item.

The V variable is defined as a direct variable that references a Long Array variable database
item named 'Values'. As the variable is a direct variable, the Vector keyword is used (the
Vector keyword has to be used for reading from an array in the database). The range of the
Vector is defined as 0-99, as this is the capacity of the vector and the data type is defined as
DINT.
The ST program calls two methodsthe Set Forecast method on a Forecast database item
named 'Forecast (Array)' and the Set Forecast method on a Forecast database item named
'Forecast (Vector)'. Each method requires three types of value: a string, a date-time, and an
array.
For the 'Forecast (Array)' item's Set Forecast method (defined as SFA in the program), the
program declares that the array value is an ARRAY OF DINT. This means that the Set
Forecast method will use the values in the specified array (in this case, the values in the array
for the vector, as defined later in the program by the V.Value entry). As the range of the
vector is defined as 0..99, it means the SFA method will use 100 values.
For the 'Forecast (Vector)' item's Set Forecast method (defined as SFV in the program), the
program declares that the array value is a VECTOR OF DINT. This means that the Set
Forecast method will only use the amount of array values specified by the vector's Length
property. So, if the vector's length is 10, the Set Forecast will only use the first ten values
from the vector's array (the source of the vector's array is an array in the database, such as
an array variable database item).
The SFA and SFV parts of the ST Program define the values for the methods.
For the SFA method (the Set Forecast method for the 'Forecast (Array)' database item), the
string value is 'Test', the date-time value is NOW(), and the source of the array is V.Value. This
means that the array values that are to be used for the method are those defined as the
Value property of the V variable (which, in this program, is the vector). The value property of
the V variable is the array referenced by the vector - the 'Values' array database item.
For the SFV method (the Set Forecast method for the 'Forecast (Vector)' database item), the
string value is 'Test', the date-time value is NOW(), and the source of the array is V. This
means that the vector is used as the source of the array values (v is the variable that
represents the vector in the program). The length property of the vector determines how
many array values are used and the value property of the vector is the source of the array
values. So if the Length of the vector is 10, the SFV method will only use the first ten values
in the'Values' array item (the 'Values' array item is the source of the vector's array).

86

PD-6017 07/2012

Chapter 4 - ST Programs

Setting the Default Values


You can assign default values to any of the variables and derived data types. This is useful
for programs that need to be set to a specific value prior to them being executed.
You can define default values in a VAR block (in which case, they cannot be overridden) or
in a TYPE block (in which case they can be overridden by values in the VAR block).
The following sections describe the formats for entering default values:

Default Values for Built-in Data Types (Literals) (see page 87)

Default Values for Derived Data Types (see page 88)

Default Values for Enumerated Data Types (see page 88)

Default Values for Structured Data Types (see page 89).

Default Values for Built-in Data Types (Literals)


The format for entering default values for integer, real, bit, string, time, and date and time
variables is:
VAR
<Value name> : <data type> := <default value>;
END_VAR

The following example shows how default values can be set for a variety of built-in data
types:
VAR
a: INT:= 535;
d: DATE:= D#2004-06-21;
t: TIME_OF_DAY:= TOD#12:30:07;
n: TIME:= T#1h30m;
p: ARRAY[1..4] OF INT:= [10,90,12,14];
q: ARRAY[1..100] OF REAL:= [100(20.5)];
END_VAR;
NOTE: The default value for the q variable sets 100 array values to have a default value of
20.5.

PD-6017 07/2012

87

Chapter 4 - ST Programs

Default Values for Derived Data Types


The format for entering default values for derived data types is:
TYPE
<Derived Data Type Name>:<Data Type>:=<Default Value>;
END_TYPE

For example:
TYPE
Temperature:REAL:=20.0;
END_TYPE

Default Values for Enumerated Data Types


The format for defining a default value for an enumerated data type is:
TYPE
<Enumerated Data Type Name>: (<Data Type>, <Data Type>)
:=<Default Value>;
END_TYPE

For example:
TYPE
ControlStatus: (Healthy, Overrange, Failed):=Failed;
END_TYPE

In the example, ControlStatus is the name of the enumerated data type. Healthy,
Overrange, and Failed are the names that are applied to the state values as part of the
enumerated data type definition. The default value of the enumerated data type is set to
Failed.

88

PD-6017 07/2012

Chapter 4 - ST Programs

Default Values for Structured Data Types


The format for defining a default value for a structured data type is:
TYPE <Structured Data Type Name>:
STRUCT
<Value Name>:<Value Type>:=<Default Value>;
<Value Name>:<Value Type>:=<Default Value>;
<Value Name>:<Value Type>:=<Default Value>;
END_STRUCT;
END_TYPE
VAR
<Variable Name>:<Structured Data Type Name>;
END_VAR;

For example:
TYPE
TEMPERATURE:REAL;
END_TYPE
TYPE
TemperatureControl:
STRUCT
Current: TEMPERATURE;
SetPoint: TEMPERATURE:=30.1;
Update: DATE_AND_TIME:= DT#1970-01-01-00:00:00;
Status: ControlStatus;
Desc: STRING:= 'Current Temperature';
END_STRUCT;
END_TYPE
VAR
Temp1:TemperatureControl;
END_VAR;

In this example, the user defined data type is defined in the first TYPE section, the
structured data type is defined in the second TYPE section, and the default values are
defined in the STRUCT section. The default values are specified as part of the structured
data type definition.
NOTE: If values were defined for Current, SetPoint, Update, Status, or Desc in the VAR list,
the values in the VAR list would override the default values set in the data structure.

PD-6017 07/2012

89

Chapter 4 - ST Programs

Executing Methods on Database Items


Many items in the ClearSCADA database can be manipulated by a method. For example,
a database point can be manipulated by an Override method so that its value is set to a
specific value that cannot be changed until the Override is released. Methods are
sometimes referred to as 'actions'.
This section explains:

Viewing which Methods are Available (see page 90)

Entering Methods in your ST Program (see page 91)

Viewing which Methods are Available


Each database item has specific methods available for use. These vary according to the
type of database item. There are also additional methods that may be available to an
itemif the item has aggregates, there may be methods that are associated with the
aggregate.
This means that when you want to use a method for a database item, you can use:

A method that is associated with the database item

A method that is associated with an aggregate that is used by the database item. For
example, methods that relate to the historic features of a database item.

You should use the ClearSCADA Database Schema to find out about the methods that are
available (see Working with the Database Schema, on page 19 in the ClearSCADA Guide
to the Database).
NOTE: You can use the ClearSCADA Database Schema to view the available methods for
the class of item to which you want to apply the method. When doing this, we recommend
that you also look at the methods that are available to each of the item's parent classes and
also the aggregates. The historic tables may also include any historic methods that are
available.

90

PD-6017 07/2012

Chapter 4 - ST Programs

Entering Methods in your ST Program


When you know which method you want to use, you need to define it within a METHOD
declaration. The METHOD declaration has to be entered below the PROGRAM keyword
but above the actual program code in your ST program (we recommend that you enter it
after the VAR list).
When you have declared the method, you can refer to it in your ST program. Referencing
a method in a program is often described as 'calling' a method.
This section explains:

Declaring a Method in a METHOD Block (see page 91)

Declaring a Method in a DATABASE_OBJECT Structure (see page 96)

Calling a Method (see page 99)

Declaring a Method in a METHOD Block


The format you need to use to declare a method in a METHOD block varies slightly
depending on whether the method is associated with a database item or an aggregate.
For information on the required format, refer to the relevant section:

Declaring a Method that is Associated with a Database Object Class (see page 92)

Declaring a Method that is Associated with an Aggregate (see page 94).

PD-6017 07/2012

91

Chapter 4 - ST Programs

Declaring a Method that is Associated with a Database Object Class


If your program uses a method that is associated with a class of database item (rather
than associated with an argument), you need to define the method. To do this, you have to
declare the method in the format described in this section.
If you are using a method that is associated with an argument, see Declaring a Method
that is Associated with an Aggregate, on page 94.
When you declare a method for a database item, you have to enclose the declaration in a
METHOD keyword and END_METHOD keyword. This has to be entered above the
PROGRAM. We recommend that you define the METHOD after the VAR list.
To declare a method, you need to use this format:
METHOD
<Method name> AT %M(<database item>.<method name>): <value type>;
END_METHOD
Where the first <Method name> is the name of the method in the program. The <database
item> is the path and name of the database item upon which the method will be used,
and the second <method name> is the name of the method as it appears in the database.
The <value type> is the argument for the method. There may be no arguments, in which
case there is no <value type> entry, a single argument as shown, or multiple arguments
which are separated by commas (<value type>, <value type>, <value type>).
You may need to use the ClearSCADA Database Schema to locate the name of the
method in the database (see Working with the Database Schema, on page 19 in the
ClearSCADA Guide to the Database).
For example:
METHOD
OVR AT %M(AIs.AnalogInp.Override): LREAL;
END_METHOD

Where METHOD defines the start of the method declaration.


OVR is the name of the override value in the ST program (the name you will use to refer to
the method later in the program).
AT %M instructs the program to use a method associated with the database item.
(AIs.AnalogInp.Override) defines the path of the database item upon which the method will
be used. In this case, AnalogInp is the name of the database item and it is located in a group
named AIs. The .Override is a reference to the name of the method that is to be performed.
The name has to be identical to the name of the method as it appears in the ClearSCADA
database schema.

92

PD-6017 07/2012

Chapter 4 - ST Programs

LREAL; sets the value of the method to be a long real value, with the semi-colon indicating
the end of the value. If the method does not set a value, the value type is not requiredyou
would end the method definition by placing the semi-colon after the closing parenthesis. For
example, the Enable Alarms method does not require a value, and so it would be defined as:
AccAlrm AT %M(AIs.AnalogInp.EnableAlarms);
END_METHOD defines the end of the method declaration.

PD-6017 07/2012

93

Chapter 4 - ST Programs

Declaring a Method that is Associated with an Aggregate


When you declare a method for an aggregate, you need to use a slightly different format
to that which is required for database item methods. The difference is that you have to
include the aggregate name in the path of the database item.
So, the format for entering an aggregate method is:
METHOD
<Method name in program> AT %M(<path of database item>.<aggregate
class>.<method name in database>): <value type>;
END_METHOD

For example:
METHOD
PromoteOS AT %M(PSTNOutstation.PSTN.PromoteDialOut): DINT, DINT,
BOOL;
END_METHOD

Where METHOD defines the start of the method declaration.


PromoteOS is the name of the method in the ST program (the name you will use to refer to
the method later in the program).
AT %M instructs the program to use a method associated with a database item (in this case,
it will use an aggregate for the item).
(PSTNOutstation.PSTN.PromoteDialOut) defines the path of the database item upon which
the method will be used. In this case, PSTNOutstation is the name of the database item.
PSTN is the name of the aggregate class and PromoteDialOut is a reference to the name of
the method that is to be performed. The name has to be identical to the name of the method
as it appears in the ClearSCADA database schema.
DINT, DINT, BOOL; sets the value types that will be used by the method.
In this case, the method will use two DINT values and a BOOL value, for example, an interval,
a duration, and an immediate start state. The method could then be used to promote the
outstation at a set interval (defined by the first DINT value), for a set duration (defined by the
second DINT value), and could start immediately or be delayed depending on the state of
the BOOL value.
END_METHOD defines the end of the declaration.

94

PD-6017 07/2012

Chapter 4 - ST Programs

For example, in the program the method could be used like this:
IF Input.CurrentValueFormatted <50 THEN
Override (80.5);
AccAlarm();
END_IF;
PromoteOS (900, 3600, TRUE);
This code works by setting the program to override the input current value to 80.5 if the
current value is reported as less than 50. If the override has to be used, an alarm is raised
(AccAlarm) and the outstation is promoted every 15 minutes (900 seconds) for a total of 1
hour (3600 seconds) and starts immediately (TRUE).

PD-6017 07/2012

95

Chapter 4 - ST Programs

Declaring a Method in a DATABASE_OBJECT Structure


You can also declare methods in a DATABASE_OBJECT structure. This allows you to
group methods with database fields.
As with defining variables in a DATABASE_OBJECT structure, the main advantages of
declaring methods in a DATABASE_OBJECT structure are:

It reduces the amount of time need to write the program as you can reference the
DATABASE_OBJECT structure rather than the same methods for different database
items.

The methods declared in the DATABASE_OBJECT structure can be used with any items
of the same class.

It makes the program easier to write, read, and understand.

If you declare methods in a DATABASE_OBJECT that is used with an SQL query, you can
use the SQL to return methods in the RESULTSET instead of values. For example, you
can override any points that have CurrentQuality Desc values of 'Bad'.
NOTE: Aggregate methods cannot be declared in a DATABASE_OBJECT structure.

To declare methods in a DATABASE_OBJECT structure, you need to use the following


format:
TYPE
<database item name>: DATABASE_OBJECT (<class of database item>)
<Method name>: METHOD;
END_DATABASE_OBJECT;
END_TYPE

Where <database item name> is the name of the database item to which the methods
apply.
DATABASE_OBJECT instructs the program that the methods are part of a database
object structure.
(<class of database item>) is the class with which the method is associated. This may be
the class for the database item or one of its parent classes. For example, it could be
CSCADAPackMPoint for a SCADAPack Modbus point or CDBPoint for all types of point.
<Method name> is the name that you are going to use to identify the method in your
program. For methods that are defined in DATABASE_OBJECT structures, you have to
enter a name that matches the name of the method in the ClearSCADA database. For
example, for an Acknowledge Alarm method, you have to define its name as Accept (as
that is the name of the method in the ClearSCADA database).
METHOD instructs the program that the type of value in the DATABASE_OBJECT is a
method. You need to repeat the <Method name>:METHOD; line for each separate
method that is to be included.
END_DATABASE_OBJECT; ends the database object structure definition and END_TYPE
ends the type declaration.

96

PD-6017 07/2012

Chapter 4 - ST Programs

Example:
TYPE
AlarmConditions: (AlarmNormal, AlarmDisabled,
AlarmAcceptedUncleared, AlarmUnacceptedCleared,
AlarmUnacceptedUncleared);
END_TYPE
TYPE
AlarmDBOBJ: DATABASE_OBJECT (CDBPoint)
AlarmState:AlarmConditions;
Accept: METHOD;
END_DATABASE_OBJECT;
END_TYPE
In the program, the following ST is used to set the Input1 point so that its
UnacknowledgedCleared alarms are acknowledged automatically:
VAR
Input1 AT %O(Input1) :AlarmDBObj;
END_VAR;
PROGRAM
IF(Input1.AlarmState = UnacceptedCleared) THEN
Input1.Accept();
END_IF;
END_PROGRAM
This program uses an enumerated data type (see Using Enumerated Data Types to Create
Names for State Values, on page 77). The enumerated data type defines a value named
AlarmConditions that has 5 state values. The ClearSCADA Database Schema defines the
states as:

State 0Normal

State 1Disabled

State 2AcknowledgedUncleared

State 3UnacknowledgedCleared

State 4UnacknowledgedUncleared

The encapsulated data type is named and has its state values defined in the first TYPE
declaration.
NOTE: You can use any names for the states in encapsulated data types (they do not have to
match the names of states in the ClearSCADA Database Schema).

PD-6017 07/2012

97

Chapter 4 - ST Programs

The second TYPE declaration is used to define the DATABASE_OBJECT structure for the
methods. It is named AlarmDBOBJ, and it is set to be a DATABASE_OBJECT that uses
the CDBPoint class. The following values and methods are included in the
DATABASE_OBJECT:
AlarmState:AlarmConditions;
Accept: METHOD;
The AlarmState value returns a value for the AlarmConditions data type. This means it
returns a value that corresponds to one of the AlarmConditions states.
The Accept value defines the method that is used in the program (the Acknowledge
method). The name of the Accept value has to match the name of the method as it
appears in the ClearSCADA database schema, so in this case it is Accept as the name of
the Acknowledge Alarm method is Accept. The METHOD part of the value instructs the
program that the value is a method.
In the program, the VAR list contains:
Input1 AT %O(Input1) :AlarmDBObj;
This defines a value (Input1) that is a database item (%O). The Input1 value is associated
with the Input1 database item and its values are returned for the AlarmConditions
database object structure. This means that the program will use the Input1 item's values
that correspond to the values that are specified in the AlarmDBObj structure.
PROGRAM
IF(Input1.AlarmState = UnacceptedCleared) THEN Input1.Accept();
END_IF;
END_PROGRAM

This part of the program defines the Logic of the program i.e. the behavior that is defined
by the program. The Logic references one of the values that is defined in the AlarmDBObj
method (Accept). Referencing a method is referred to as calling a method (see Calling a
Method, on page 99). In this case, the Acknowledge method is applied to the Input1 item
when its AlarmState value is Unacknowledged Cleared.

98

PD-6017 07/2012

Chapter 4 - ST Programs

Calling a Method
When you have defined the method declaration, you can reference the methods in your
program. Referencing is also referred to as 'calling'.
To reference a method, use the following format within the ST program:
<Method name in program> (<method value>);
Where <Method name in program> is the name of the method that you defined in the
METHOD declaration. This is not the name of the method as it appears in the
ClearSCADA database schemait is the name you allocated to the method.
<method value> is the value that you want the method to invoke. If there are multiple
values, you need to separate each value with a comma, and if there are no values then
you need to enter ().
For example:
Override (35.6);
This means the Override method is used to set the point to have a value of 35.6
EnableAlarms();
This means that the EnableAlarms method is used. As it has no values (it activates the
alarm feature for an item), the () is entered.
PromoteOS (900, 3600, TRUE);
This means that the PromoteOS method has 3 arguments900 is the interval, 3600 is the
duration, and TRUE sets the outstation to perform a One Shot immediately.
In the METHOD declaration for the PromoteOS method, the PromoteOS value definition
has to include value types for each of the values:
METHOD
PromoteDialOut AT %M(PSTNOS.PSTN.PromoteDialOut):DINT,DINT,BOOL;
END_METHOD
The DINT, DINT, and BOOL definition set the 3 arguments (the interval and duration are
DINTs and the immediate One Shot argument is a Boolean).
The path for the PSTNOS database item includes the PSTN aggregate aswell as the
PromoteDialOut method. For methods that are associated with arguments rather than the
database item, you need to define the method in this format:
<Method name in program> AT %M(<Name of database item>.<Name of
aggregate>.<Name of method in ClearSCADA Database>):<value type>,<value type>,
<value type>;
You only need to add <value type> for each argument for the method.

PD-6017 07/2012

99

Chapter 4 - ST Programs

Controlling the Flow of the Program


Once you have defined the variables, database object structures etc. for your program,
you can begin to define the Logic.
The Logic that you define will determine what happens when the program executes. For
example, it will determine whether values are written to the database or methods are
performed on database items. The result of the program will depend on the variables and
the structure of the Logic.
To define the Logic, you need to refer to the variables and use a series of Logic
conditional statements. The conditional statements allow you to define the flow of your
program.
There are several types of conditional statement, including:

IF - THEN - ELSE (see page 100)

IF - THEN - ELSIF - ELSE (see page 102)

AND, OR, and XOR (see page 103)

CASE - OF (see page 104)

FOR - TO - BY (see page 106)

WHILE - DO (see page 107)

REPEAT - UNTIL (see page 109)

RETURN (see page 110).

IF - THEN - ELSE
The IF-THEN-ELSE statement is a commonly used ST statement. It allows you control the
value of an item based on the value of another item.
Example:
IF Level > 75 THEN
Pump1 := FALSE;
Pump2 := FALSE;
ELSE
Pump1 := TRUE;
Pump2 := TRUE;
END_IF;

In this Logic, the Pump state and Power state are set to OFF (FALSE) when the value of
the Level is less than 75. When the value of the level is not less that 75 (i.e. is greater than
75), the Pump and Power states are set to ON (TRUE). This type of Logic can be used in
the water industry where a pump needs to be turned on to pump water out of a pipe when
the level is greater than 75.

100

PD-6017 07/2012

Chapter 4 - ST Programs

You need to enter IF-THEN-ELSE statements in the following format:


IF <item name or value name> = <value> THEN
<Value name> := <specific value>;
ELSE
<Value name> := <specific value>;
END_IF;

You can also nest IF-THEN-ELSE statements to create complicated control Logic. For
example:
IF PumpQuality = Good THEN
IF Valve = CLOSED THEN
Valve := OPEN;
END_IF;
ELSE
PumpQuality := Bad;
END_IF;

In this example, the parent IF-THEN-ELSE statement instructs the program to evaluate
the nested IF-THEN-ELSE statement when the PumpQuality is Good. If the PumpQuality
is Bad, the program will not evaluate the nested statement.
The nested IF-THEN-ELSE statement is only executed when the PumpQuality is Good. It
instructs the program to check if the valve is closed. If it is closed, then the program will
open the valve.

When you nest an IF-THEN-ELSE statement, you need to apply the same formatting
rules. The statement needs to be started with an IF keyword and has to be ended with an
END_IF; keyword.
NOTE: We recommend that you indent nested IF-THEN-ELSE statements as this makes the
program easier to read.

PD-6017 07/2012

101

Chapter 4 - ST Programs

IF - THEN - ELSIF - ELSE


The IF-THEN-ELSIF-ELSE statement is a commonly used ST statement that allows you
control the value of an item based on the value of other items. The ELSIF part of the
statement combines ELSE and IF.
You have to enter IF-THEN-ELSIF-ELSE statements in the following order:
IF <code> THEN
<code>;
ELSIF
<code>;
ELSE
<code>;
END_IF;

Where <code> is any valid code structure. When using the IF-THEN-ELSIF-ELSE
keywords, the keywords have to be used in that order (IF first, followed by THEN, and
then ELSIF, with ELSE last).
Example:
IF Level > 75 THEN
Pump1 := TRUE;
Pump2 := TRUE;
ELSIF Level > 50
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:

102

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 75 and less than 50, both of the pumps are set to
False (off).

PD-6017 07/2012

Chapter 4 - ST Programs

AND, OR, and XOR


You can use AND, OR and XOR for multiple conditions. These keywords provide the
following results:
Input Values

AND

OR

XOR

Input A = True
Input B = True

True

True

False

Input A = True
Input B = False

False

True

True

Input A = False
Input B = True

False

True

True

Input A = False
Input B = False

False

False

False

The syntax for entering an AND, OR or XOR keyword is:


<Value name> := <Value1> <Keyword> <Value2>;
Where value name is the name of the variable that will store the result of the statement,
Value1 is the first input value, Value2 is the second input value, and Keyword is AND, OR or
XOR as required.
Examples:
Output := Input1 AND Input2;
This sets the value of the variable named Output to be True if Input1 and Input 2 are both
True, or False if only one of the inputs is True.
Output := Input1 OR Input2;
This sets the value of the variable named Output to be True if either Input1 or Input 2 are
True. The Output value will only be False if both of the inputs are False.
Output := Input1 XOR Input2;
This sets the value of the variable named Output to be True if one of the inputs is True and
the other is False. The Output will only be False if both of the inputs are True or both of the
inputs are False.

PD-6017 07/2012

103

Chapter 4 - ST Programs

CASE - OF
You can use the CASE - OF statement to set the values of defined variables based on an
integer input. For example, you can use the CASE - OF statement to set the values of
points named 'Point 2' and 'Point 3' based on the status value of a point named 'Point 1'.
The 'Point 1' status is represented by an integer value that is used as an input.
When you enter a CASE - OF statement, you need to use the following format:
CASE <Name of Integer Input> OF
<Integer Value 1> : <Statements>;
<Integer Value 2> : <Statements>;
ELSE
<Statements>;
END_CASE;
Where <Name of Integer Input> is the name of the integer variable that is used to
determine the values of the other variables. The <Name of Integer Input> has to be
defined in the VAR list for the program.
<Statements> represents the values that are set when the integer variable is the defined
value. You can set multiple statements based on the integer variable being a defined
value. For example, if Integer Value 2 is 6, you can define statements that set variable 3 to
90 and variable 4 to 15. The format for defining a statement is:
<Variable name> := <value>;
You can use the ELSE statement to define the values for the statements when the integer
input is not a value included in the CASE - OF definition. For example, if an integer value
has 6 possible settings and only setting 1 and 2 are used in the CASE - OF statement, the
ELSE statement needs to be used to define the variable values when the integer value is
3, 4, 5, or 6. You need to end the CASE - OF statement with an END_CASE; keyword.

104

PD-6017 07/2012

Chapter 4 - ST Programs

Example:
TYPE
FanCooler: (Low, High, Off);
END_TYPE
PROGRAM CoolerSpeed
VAR
Fan_Setting: INT;
SPEED: INT;
COOLER: FanCooler;
END_VAR
COOLER := Off;
CASE Fan_Setting OF
1: SPEED := 5;
2: SPEED := 10;
3,4,5: SPEED := 20; COOLER := Low;
6..8: SPEED := 40; COOLER := High;
ELSE
SPEED := 0;
END_CASE;
END_PROGRAM
In this example, the Logic is used to set the speed of a fan and its cooler based on the
integer input of the fan.
An encapsulated data type is created to define the fan cooler settings. The data type is
named FanCooler and it defines the three fan cooler values (Low, High, and Off).
At the start of the program, the COOLER variable is defined as Off. This means that the
COOLER variable is set to Off unless set to be Low or High by the Logic.
The variables list contains 3 variables: Fan_Setting which represents the integer value that
indicates the state of the fan, SPEED which represents the rate at which the fan is
running, and COOLER which represents the fan cooler setting. The Fan_Setting variable is
set to INT as it provides an integer value. This value is used by the Logic program to
determine the values of the COOLER and SPEED variables. The SPEED variable is also an
integer value (for the example, the values are internal values), and the data type for the
COOLER variable is FanCooler (a reference to the encapsulated data type).
The CASE - OF statement is used to define how the Logic program sets the values for the
variables:
When the Fan_Setting variable is 1, the program sets the SPEED variable to 5.
When the Fan_Setting variable is 2, the program sets the SPEED variable to 10.
When the Fan_Setting variable is 3, 4, or 5, the program sets the SPEED variable to 20
and the COOLER variable to Low.
When the Fan_Setting variable is 6 to 8 inclusive, the program sets the SPEED variable to
40 and the COOLER variable to High.
Other Fan_Setting variable values cause the program to set the SPEED variable to 0.

PD-6017 07/2012

105

Chapter 4 - ST Programs

FOR - TO - BY
You can use the FOR - TO - BY statement to create a loopthe program repeats a set of
statements on each execution, until a specific value is reached.
When you use a FOR - TO - BY statement, you need to enter it in this format:
FOR <Variable> :=<Initial value> TO <End loop value> BY <Decrement
value>
DO
<Statements>;
END_FOR;

Where <Variable> is the name of the value that will be used to determine whether the
program continues to execute the <Statements>. With FOR - TO - BY statements, you
enter the variable in the FOR - TO - BY declaration and not in the VAR list. The variable
has to be an integer.
The <Initial value> is the starting value of the integer <Variable>.
TO <End loop value> defines the value at which the program will stop executing the
<Statements>. When the <Variable> reaches the <End loop value>, the program will no
longer attempt to execute the <Statements>.
BY <Decrement value> defines the amount by which the <Variable> value will change
upon each execution. The BY declaration is optional and is +1 by default.
DO <Statements> defines the statements that the program performs each time that the
program executes and the <Variable> value is not the <End loop value>.

Example:
FOR InputA := 10 TO -10 BY -1 DO
Square[InputA] := InputA * InputA;
END_FOR;

In this example, the FOR - TO - BY statement instructs the program to decrease the
InputA value by 1 on each execution of the program. It will decrease the InputA value by 1
until the InputA value is -10.
The Square[InputA] : InputA * InputA calculation is performed after each execution. This
array is used to produce the square values of the array variables (which would be defined
in the array above the FOR - TO - BY statement in the program).
As the array values are calculated based on the current value of InputA, it means that
each time the program executes, it provides a new set of results for the array. This occurs
due to the FOR - TO - BY statement decreasing the InputA value by 1 for each execution
(until the InputA value is -10). As the InputA value is lower for each execution, the results
for the array values are different for each execution (the program uses the InputA value to
calculate the values for the array).

106

PD-6017 07/2012

Chapter 4 - ST Programs

WHILE - DO
You can use the WHILE - DO statement to set a program to execute statements in a loop
while an input is true. A typical use of the WHILE - DO statement is to set a program to
define values or perform methods on a resultset of an SQL Query when a particular
condition is in place.
NOTE: The WHILE - DO expression is evaluated before the statements are executed. This
means that if the expression in the WHILE - DO definition is false, the program will not begin
to execute the statements in the program.
You can define a WHILE - DO statement by using this format:
WHILE <Condition expression> DO
<Statements>;
END_WHILE;

Where:
<Condition expression> is the expression that defines the value that has to be true before
the program will check the statements.
<Statements> are the values and methods that are set as a result of the <Condition
expression> being true.
Example:
TYPE
AlarmConds : DATABASE_OBJECT (CDBPoint)
AlarmDesc: STRING;
Accept: METHOD;
END_DATABASE_OBJECT;
END_TYPE
PROGRAM Name
VAR
PointList AT %S(Select Id, AlarmDesc FROM CDBPoint): RESULTSET
OF AlarmConds;
END_VAR
WHILE PointList.Value.AlarmDesc='Unaccepted Cleared' DO
PointList.Value.Accept();
PointList.Next();
END_WHILE;
END_PROGRAM;

In this example, we use a DATABASE_OBJECT structure to group a type of value and a


method. In this case, the DATABASE_OBJECT structure references the CDBPoint class
and includes the AlarmDesc value (which is a STRING) and the Accept method (that
acknowledges alarms).

PD-6017 07/2012

107

Chapter 4 - ST Programs

In the VAR list, the variable defines the SQL Query that is used to obtain data from the
CDBPoint class. The name of the SQL Query is defined as PointList and it is used to
extract the Id and AlarmDesc values from the CDBPoint class (the Query returns the
values for the RESULTSET of the AlarmConds DATABASE_OBJECT structure).
In the Logic of the program, the WHILE - DO statement is used to instruct the program to
acknowledge any point alarms that are Unacknowledged Cleared:
WHILE PointList.Value.AlarmDesc= 'Unaccepted Cleared' DO
PointList.Value.Accept();
PointList.Next();
END_WHILE;
This defines that as long as the current record in the SQL Query result set has an
AlarmDesc value of 'Unacknowledged Cleared', the Accept method has to be used. The
Accept method is applied so that the 'Unacknowledged Cleared' alarm is acknowledged
for the point to which the current record relates.
The PointList.Next() instruction sets the program to proceed to the next record in the
result set once the current record has had any 'Unacknowledged Cleared' alarms
acknowledged.
The Logic program continues to step through each of the records in the record set,
acknowledging any 'Unacknowledged Cleared' alarms until it reaches the end of the
record set. When the records have been checked, the program stops executing.

108

PD-6017 07/2012

Chapter 4 - ST Programs

REPEAT - UNTIL
You can use the REPEAT - UNTIL statement to create a loop that continues to execute
until a specified condition occurs. For example, you can use a REPEAT - UNTIL program
to increase a count by 1 and a value by 10 until the value reaches 100:
REPEAT
CountValue := CountValue+1;
CurrentValueFormatted : = CurrentValueFormatted +10;
UNTIL
CurrentValueFormatted >=100
END_REPEAT;
Where CountValue and CurrentValueFormatted are the names of variables (that would be
defined in the VAR list).
In this example, the program increases the CountValue by 1 and the
CurrentValueFormatted by 10 on each execution. This part of the program repeats itself
until the CurrentValueFormatted is equal to or greater than 100.
If the CurrentValueFormatted is 200 when the program starts, the program will still
increase the CountValue by 1 and the CurrentValueFormatted by 10 one timeREPEAT
statements are performed at least once (as the condition is a the end of the statement).

When you enter a REPEAT - UNTIL statement, you need to use the following format:
REPEAT
<Statements>;
UNTIL
<Condition>
END_REPEAT

Where <Statements> defines the values and methods that are set by the program in the
REPEAT statement. <Condition> is the value that causes the program to stop repeating
the Logic defined in the REPEAT statement.

PD-6017 07/2012

109

Chapter 4 - ST Programs

RETURN
You can use the RETURN statement within a Function Block (see Function Blocks in ST
Programs, on page 121). The RETURN statement terminates the Function Block but
instructs the program to use the Function Block values that had been calculated up to
that point. For example, if a Function Block calculates 4 output values and the RETURN
statement is positioned after the second value has been calculated, the first 2 values will
be used by the program but the 3rd and 4th values will not be used as the RETURN
statement terminates the function block before they are calculated.
The RESULT statement is useful when certain values that are calculated by a Function
Block are not required in a particular scenario. You should enter the RETURN statement at
the position where you want the program to terminate the Function Block (when a defined
condition occurs).
Example:
FUNCTION_BLOCK POWERLOAD
VAR_INPUT
CURRENT,POWER1,POWER2,POWER3:REAL;
END_VAR
VAR_OUTPUT
OVERLOAD:BOOL;
END_VAR

IF((power1 * current) > 100) THEN


overload := TRUE;
RETURN;
END_IF;
IF((power1 * (current + 10)) > 100 THEN
overload := TRUE;
RETURN;
END_IF;
IF((power1 * (current + 20)) > 100 THEN
overload := TRUE;
END_IF;
END_FUNCTION_BLOCK;

110

PD-6017 07/2012

Chapter 4 - ST Programs

In this example, the Function Block is used to determine whether there is a power
overload. If the power1 value x the current value is equal to or greater than 100, there is a
power overload and so the overload value is true.
If the power2 value x the current value +10 is equal to or greater than 100, there is a
power overload and so the overload value is true.
If the power3 value x the current value +20 is equal to or greater than 100, there is a
power overload and so the OVERLOAD value is true.
Each IF statement needs to be performed in turn. There is a RETURN statement after the
first IF statement and another after the second IF statement. This means that if the
overload value is true after the first IF statement, the rest of the program is ignored.
Similarly, if the overload value is true after the second IF statement, the rest of the
program is ignored.

PD-6017 07/2012

111

Chapter 4 - ST Programs

Using an ST Program to Call an SQL Query


You can code an ST program to retrieve information from the database via an SQL Query.
The requested data is returned in a RESULTSET and can then be used in the ST
Program's calculations.
Each Query returns a RESULTSET that has these variables:

.ValidThis is a Boolean variable that indicates whether the current row is Valid (True is
valid; False is invalid).

.IdxThis is a DINT and is the index number of the current row.

.SizeThis is a DINT and is the total number of rows in the RESULTSET.

.ValueThis corresponds to the Type defined in the Query and represents the
requested property of the current row.

The following methods can be used to navigate through the RESULTSET:

.First()Go to first record in RESULTSET

.Last()Go to last record in RESULTSET

.Next()Go to the subsequent record in the RESULTSET

.Prev()Go to the preceding record in the RESULTSET

NOTE: The SQL Query in an ST Program can only access data in the ClearSCADA database.

The syntax for calling an SQL Query in an ST program is:


TYPE
<Name of Type for RESULTSET>:<STRUCT or DATABASE_OBJECT>
<Member Name> : <Type>;
<Member Name> : <Type>;
<Method Name>: METHOD;
<END_STRUCT or END_DATABASE_OBJECT>;
END_TYPE

PROGRAM <Program Name>


VAR
<Var name> AT %S(SELECT <column 1>, <column 2>,<column 3> FROM
<Database Table> WHERE <Filter>) :RESULTSET OF <Name of Type for
RESULTSET>;
END_VAR

112

PD-6017 07/2012

Chapter 4 - ST Programs

Where:

Type indicates the start of the type definition.

<Name of Type for RESULTSET> is the name of the user defined type that will contain
the data returned by the SQL SELECT Query.

<STRUCT> declares the start of a Structure and <DATABASE_OBJECT> indicates the


start of a database object structure. Structures are used when the ST Program only
needs to reference one field of an item's data; DATABASE_OBJECT structures are used
when the ST Program needs to reference more than one of a database item's fields.
When declaring a DATABASE_OBJECT structure, the required database table has to be
included in parenthesis after DATABASE_OBJECT, for example,
DATABASE_OBJECT(CPointAlgManual).

<Member Name> : <Type>; declares the name and type of a data field that you want to
use in your ST Program. For DATABASE_OBJECT structures, the name has to match
the name of a column in the SQL Query. You can declare as many member names and
types as required.

<Method Name> : METHOD; declares the name of a method that is available to the
declared structure. For example, the DATABASE_OBJECT(CPointAlgManual) structure
has an Current Value method that can be declared as: CurrentValueFormatted:
METHOD; The method can then be called in the ST Program by using the syntax
<Variable Name>.Value.CurrentValueFormatted(); where <Variable Name> is the name
of the variable that is used to store the RESULTSET of the SQL Query.

<END_STRUCT or END_DATABASE_OBJECT>; ends the structure declaration.

END_TYPE ends the Type declaration.

PROGRAM <Program Name> declares the start of the ST program. The Program Name
can be any name you require.

VAR defines the start of the variable declaration.

<Var name> AT %S declares the name of the variable used for the SQL Query and AT
%S indicates that the variable will be used to contain data returned from an SQL
SELECT Query. You can enter any name for the variable.

(SELECT <column 1>, <column 2>,<column 3> FROM <Database Table> WHERE
<Filter>) defines the columns that are to be included in the SQL Query.
The column names have to match the names of columns in the selected database table
(and the member names for the DATABASE_STRUCTURE, as these also have to match
the columns in the selected database table).
NOTE: When you are using a DATABASE_OBJECT structure, the first column in your
SQL Query has to be the Id column. This is because DATABASE_OBJECT structures
have an Id field (although it is not included as one of the member names for the
DATABASE_OBJECT structures).
The FROM <Database Table> part defines which table in the database the SQL Query is
to search for the defined columns, and the WHERE <Filter> part defines any filtering.
For example, SELECT CurrentValueFormatted FROM CPointAlgManual WHERE
FullName LIKE 'Pumps.%') instructs the Query to search for the CurrentValueFormatted
column in the CPointAlgManual table and to filter its results to include only those that
are in the 'Pumps' Group or one of its children.

PD-6017 07/2012

113

Chapter 4 - ST Programs

RESULTSET OF <Name of Type for RESULTSET> declares that the results of the Query
will be returned into a RESULTSET of the defined type (the name of the type should
match the name of the type that was defined at the start of the TYPE declaration).

When you have declared the Type, Members, Methods, and SQL Query as required, you
can use the RESULTSET variables and methods in your ST Program. Typically, they are
used within WHILE...DO functions.
NOTE: Do not enter the angle brackets < >. As with other syntax descriptions, you should
not enter the angle brackets unless specifically instructed to do so.
Examples:
Example 1.
The following example shows an ST Program that is used to search for internal analog points
in a Group named 'Power Simulation'. When the program locates the internal points, it steps
through each record and increases the corresponding point's current value by 1:
TYPE
Point : DATABASE_OBJECT(CPointAlgManual)
CurrentValue : LREAL;
CurrentState : INT;
END_DATABASE_OBJECT;
END_TYPE
PROGRAM SQLTestHanddressPts
VAR
Pts AT %S(SELECT Id, CurrentValue, CurrentState FROM
CPointAlgManual WHERE FullName LIKE 'Power Simulation.%') :
RESULTSET OF Point;
END_VAR
WHILE Pts.Valid DO
Pts.Value.CurrentValue := Pts.Value.CurrentValue + 1;
Pts.Next();
END_WHILE;
END_PROGRAM

114

PD-6017 07/2012

Chapter 4 - ST Programs

Example 2.
The following example shows an ST Program that is used to search for advanced
outstations. When the program locates the outstations, it steps through each record and
resets the corresponding outstation's communication statistics:
TYPE
Outstation : DATABASE_OBJECT( CAdvOutstation )
ResetCommsStatistics : METHOD;
END_DATABASE_OBJECT;
END_TYPE

PROGRAM ResetAllOsCommsStats
VAR
Os AT %S(SELECT Id FROM CAdvOutstation) : RESULTSET OF
Outstation;
END_VAR

WHILE Os.Valid DO
Os.Value.ResetCommsStatistics();
Os.Next();
END_WHILE;

END_PROGRAM

PD-6017 07/2012

115

Chapter 4 - ST Programs

Inserting, Updating, and Deleting Values by Using SQL in an ST


Program
You can use the INSERT, UPDATE, and DELETE Data Manipulation Language (DML)
statements in SQL queries within your ST programs. These statements are especially
useful when creating, updating, or removing values in data tables.
Although ClearSCADA supports the use of INSERT, UPDATE and DELETE with any of the
database tables, we strongly recommend that you do not use these statements with any
query that affects the configuration of the database on a regular basis. Frequent
alterations to the configuration may cause slow performance and affect the running of
your system. This does not affect data tables as they do not store configuration.
If you are using the INSERT, UPDATE and DELETE statements, they need to be declared
in your SQL query. When the ST program runs, it will create a queue of the insertions,
updates and deletions it needs to make and will only perform these actions once the
program has executed.
To use the INSERT, UPDATE or DELETE statement, you need to include the statement
keyword in your SQL query and use %D to declare that DML statements are being used.
You can use multiple DML statements in the same ST programwhen the program has
executed, the insertions, updates and deletions are performed in the order in which they
appear in the code.
If you wish to include parameters for an insertion, you can do so by using the ? character
to represent the values and the WITH_PARAMS keyword to indicate that there are
parameters (see Passing Multiple Parameters into an SQL Query in an ST Program, on
page 119).
Example:
The following example shows how an ST program can make use of the DML statements. In
this example, the program:

1.

Deletes the values from a data table item called 'LogicDataTable'.

2.

Inserts an entry in the data table with STRING[64] and DINT type values. The values will
be used for the StringField and NumberField fields for the new entry in the data table. In
this case, the values are: 20 and 'First Record'.

3.

Updates the data table so that NumberField entries are increased by 5.

4.

Inserts another entry into the data table, again with STRING[64] and DINT type values.
The values used for the entry are 10 and 'Second Record'.

5.

Deletes entries that have a specific NumberField value (in this case, 25).

The ST program code is as follows:


PROGRAM test
VAR
Num : DINT;
Str : STRING[64];
END_VAR

116

PD-6017 07/2012

Chapter 4 - ST Programs

VAR
Init AT %D(DELETE FROM LogicDataTable );
R1 AT %D(INSERT INTO LogicDataTable VALUES ( ?, ? ) ) WITH_PARAMS
Str, Num;
R2 AT %D(UPDATE LogicDataTable SET NumberField = NumberField + 5
);
R3 AT %D(DELETE FROM LogicDataTable WHERE NumberField = ?)
WITH_PARAMS Num;
END_VAR
Init.Execute();
Num := 20;
Str := 'First Record';
R1.Execute();
R2.Execute();
Num := 10;
Str := 'Second Record';
R1.Execute();
Num := 25;
R3.Execute();
END_PROGRAM

If you look at the program code, you will see that in the second VAR declaration there are 4
variables; 1 for each DML statement:

The Init variable contains a query that instructs the program to delete data from the
LogicDataTable object when the variable is called.

The R1 variable contains a query that instructs the program to insert values into the
LogicDataTable object when the variable is called - it will create a row with 2 values of a
specific type (defined in the first VAR declaration).

The R2 variable contains a query that instructs the program to update the NumberField
fields in the LogicDataTable object so that they increase by 5.

The R3 variable contains a query that instructs the program to delete entries from that
LogicDataTable that have a specific NumberField value.

In the code following the second VAR declaration, you can see the order in which the
methods will be called:

1.

When the program is executed, the Execute method will be called on the query in the
Init variable: data will be removed from the LogicDataTable object.

2.

The Execute method will be called on the query in the R1 variable. This will create a new
entry in the LogicDataTable that has 20 for the NumberField value and 'First Record' for
the StringField value.

PD-6017 07/2012

117

Chapter 4 - ST Programs

3.

The Execute method will be called on the query in the R2 variable. This will update the
row in the LogicDataTable so that the row has 5 added to its NumberField value. So the
row will have a NumberField of 25.

4.

The Execute method will be called on the query in the R1 variable again. This will create
another new row, this time with the values 10 and 'Second Record'.

Finally, the Execute method will be called on the query in the R3 variable. This will delete the
entries in the LogicDataTable that have 25 as their value in the NumberField field. So, the
first row that was inserted by the program will be deleted.

Further Information
WITH_PARAMS: Passing Multiple Parameters into an SQL Query in an ST Program (see
page 119).

118

PD-6017 07/2012

Chapter 4 - ST Programs

Passing Multiple Parameters into an SQL Query in an ST Program


You can pass multiple parameters into an SQL query in an ST program. This is useful
when you want to apply additional criteria that has to be met by the values in the
RESULTSET (this works similarly to a filter) and is also useful when you are using DML
statements to insert multiple values for one or more rows in a table (see Inserting,
Updating, and Deleting Values by Using SQL in an ST Program, on page 116).
To enter multiple parameters in an SQL query within an ST program, you need to use the
? character to represent the value of each parameter and the WITH_PARAMS keyword to
define the parameters.
When entering multiple parameters in an SQL query in an ST program, you need to use
the ? character to represent each parameter value in the query. The WITH_PARAMS
keyword has to be used in the RESULTSET and each parameter listed after the
WITH_PARAMS keyword has to correspond to the name of one of the ST program's VAR
inputs. You should separate the parameters after the WITH_PARAMS keyword with
commas.
The order of the parameters that you define after the WITH_PARAMS keyword
corresponds to the order of the ? characters defined in the SQL query. You can repeat the
parameters so that the same parameter can be used multiple times in the SQL.
Example:
In this example of an ST Program, the parameters for the SQL query are defined as
VAR_INPUTs with the names objName and objFullScale. In the SQL query, the ? character is
used to represent the parameters. The DATABASE_OBJECT is used to define the database
table (in this case, CPointAlg) and the type of value for the properties defined in the SQL
query (Name and FullScale).

TYPE
Point: DATABASE_OBJECT (CPointAlg)
Name:STRING;
FullScale: LREAL;
END_DATABASE_OBJECT;
END_TYPE

PROGRAM NameAndFullScale

PD-6017 07/2012

119

Chapter 4 - ST Programs

VAR_INPUT
objName : STRING;
objFullScale: LREAL;
END_VAR

VAR
objList AT %S(SELECT Id, Name, FullScale FROM CPointAlg WHERE
Name LIKE? || '%' AND FullScale > ?) : RESULTSET OF Point
WITH_PARAMS objName, objFullScale;
END_VAR
;
END_PROGRAM
So, the SQL query in the ST Program will return the Id, Name, and FullScale values from the
CPointAlg database table. It will only return the values for those items that have a Name
value that is like the value of the first parameter followed by any amount of characters and
has a FullScale value that is greater than the value of the second parameter. The first
parameter is the objName parameter as this is the first parameter listed after the
WITH_PARAMS keyword. The objFullScale parameter is the second parameter as it is listed
second after the WITH_PARAMS keyword. So in the SQL query, the first ? character
corresponds to the objName parameter and the second ? character corresponds to the
objFullScale parameter. If the SQL query was to contain an additional ? character, an
additional parameter would be required in the list of parameters after the WITH_PARAMS
keyword. The additional parameter in the list could be a new parameter or could be one of
the existing parameters used again, for example, it could be another use of the objFullScale
parameter.

120

PD-6017 07/2012

Chapter 4 - ST Programs

Function Blocks in ST Programs


Function blocks are blocks of code that define a type of Logic behavior or calculation. As
they provide a specific Logic behavior or calculation, they can be used in ST programs
and other Logic programs. This means you can save time when coding your ST programs
as if there are function blocks (default or custom) that provide the Logic or calculations
that you require in your program, you can attach the function block instead of recreating
the code. Function blocks act as 'building blocks' that you can use to create your
programs.
Each function block has inputs, an internal data structure that defines the Logic that is
provided by the function block, and outputs.
You can define a built-in function block within an ST program. The function block will use
inputs to perform a specified calculation, then write the results to outputs. If you enter a
function block within an ST program, the function block is only available to that ST
program. For more information, see Built-In Function Blocks, on page 319.
Alternatively, you can define a function block in a Structured Text Library or in a Function
Block Library. The Libraries can be used over and over again in your Logic programs. This
means you can define the function block once in an ST Library or Function Block Library
and use it in as many programs as you wish (see Using Libraries in ST Programs, on page
121).
For information on the required syntax when entering a function block in an ST program,
please refer to Built-In Function Blocks (see page 319).

Using Libraries in ST Programs


We recommend that you store reusable blocks of code in Structured Text libraries. The ST
libraries can then be attached to other ST programs. The advantages of using ST libraries,
include:

ST libraries reduce the amount of time and effort needed to create ST programs. If you
create an ST library for a block of code that is needed in several ST programs, you can
write the code for the library once and then attach the library to each ST program as
required.

ST libraries reduce the amount of time it takes to make alterations to a block of code
that is used in several ST programs. You can make the required changes to the ST
library and then update the library in each ST program. This is much quicker than
having to alter the code in each ST program separately.

You can also use Function Block Libraries to store custom function blocks that can be
referenced by multiple Logic programs.
For more information on ST Libraries and Function Block Libraries, see User Function
Blocks, on page 349.

PD-6017 07/2012

121

Chapter 4 - ST Programs

Compiling an ST Program or ST Library


You can use the Build menu options to compile your ST program. The compilation feature
is useful as it checks that your program has the correct syntax.
There are 2 compile options:

CompileCompiles the program. If the program is invalid, the compiler display


provides a message that briefly describes the syntax error in your program. If the syntax
is correct, the compiler displays a success message.

Compile with DiagnosticsCompiles the program and provides detailed diagnostic


information (the Logic in ST, the ST code formatted with indented text etc., and the op
codes which is the machine code version of the ST code). As with the Compile option,
there are messages for any errors in the syntax. If the syntax is correct, the compiler
displays a success message.
NOTE: The Compile with Diagnostics tool is useful when working with other types of
Logic program that you want to use as ST programs. For example, you may find it
easier to create a Function Block Diagram and then use the Compile with Diagnostics
tool to access the ST code for the Function Block Diagram. You can then copy this
code into an ST program (you have to remove the $ signs in the code).

122

PD-6017 07/2012

Chapter 4 - ST Programs

To compile an ST program or ST library:


1.

Display the ST program or ST library in Design mode.

2.

Select the Build menu, then select the Compile option or the Compile with Diagnostics
option as required.

The program or library is compiled and the compile messages are shown in the
Compiler display.

Compiler display shows compiler messages and diagnostics.

If there are syntax errors, you will need to alter the ST code. Typically, the causes of
syntax errors are minor, such as the wrong type of value being specified or a missing
semi-colon.
When you have successfully compiled your program, you can use the Debug option to
check that its Logic defines the required behavior (see Debugging an ST Program or ST
Library, on page 124).

PD-6017 07/2012

123

Chapter 4 - ST Programs

Debugging an ST Program or ST Library


You can use the Debug feature to debug your ST program or ST library. The debugging
feature allows you to check that your program provides the expected Logic functions. It is
particularly useful when you need to check separate parts of large programsyou can
step through each section of the program and view its effect on the variables. To view the
variables, you need to use the Variables window (see the Variables option later in this
section). This helps you to determine which parts of your ST programs are not working as
intended (if any).
NOTE: A Logic program can only be debugged by one user at a time. When a user has a
Logic program in debug mode, it cannot be executed manually or by schedules.
There are two ways to start the debugging process:

When displaying an ST program or ST library in Design mode, you can select the Start
Debugging option from the Build menu. This switches the ST program or ST library and
starts the debugging feature.

You can display an ST program or ST library in Run mode (either from the Database Bar
or by switching the ST program or library to Run mode manually), then select the Start
Debugging option from the Debug menu.

Typically, you will need to use the debugging feature to debug separate sections of an ST
program. For example, if a complex ST program is not returning the values you expected,
you will need to debug each calculation within the program separatelythis allows you to
determine which sections of the ST program are incorrect.
To debug parts of a program, you need to use the Debug menu options:

124

GoThe debugger runs the program until it reaches a breakpoint or the program
completes.

RestartStarts the debugging feature again (after it has been stopped).

Stop DebuggingStops the debugging feature. The debugger will not run again until
you select the Restart option.

PD-6017 07/2012

Chapter 4 - ST Programs

Insert/Remove BreakpointInserts or removes a break point at a selected position. You


need to use this option to divide your program into sections.
To insert a breakpoint, position the cursor in the line of code that you want to use as a
breakpoint, then select the Insert/Remove Breakpoint option.
The debugger only
runs the program
up to the
Breakpoint

The debugger will only run up to the breakpointit does not run the parts of the
program that are after the breakpoint. By using the Variables window (see Viewing the
Variables in your ST Program, on page 127), you can view the values that are created by
the program up until the breakpoint. By examining the values, you can determine
whether the code in the section before the breakpoint is causing unexpected results.
If the code up to the breakpoint is working as expected, you can remove the breakpoint
using the Insert/Remove Breakpoint option. Alternatively, you can disable it by selecting
the Enable/Disable Breakpoint option.

Enable/Disable BreakpointYou can use the Enable/Disable Breakpoint option to turn


a breakpoint on or off without having to insert or delete it. This is useful when you want
the debugger to run past a breakpoint you have inserted, but you do not want to
remove the breakpoint (because you need to use it again at some point).
The Enable/Disable Breakpoint option works as a toggle. When you first select it, you
disable a breakpoint so that the debugger ignores it. When you select it again, the
breakpoint is enabled and the debugger will stop running the program at the
breakpoint.

Step IntoWhen a program is being debugged, the debugger ignores the code in any
function blocks that are contained within the program. You can set the debugger to run
the function block code as well as the rest of the program code by selecting the Step
Into option.
The Step Into option is useful when investigating function blocks within an ST program.
If the function blocks have already been debugged, there is no need to use the Step
Into option.

Step OverSets the debugger to ignore any further statements in a function block that
is contained within the ST program. If the debugger is set to Step Into when you select
this option, it will execute the current statement in the function block and then return to
the main part of the ST program. It will not execute the remaining calculations in the
function block (unlike the Step Out option).
The debugger is set to Step Over by default.

PD-6017 07/2012

Step OutSets the debugger to ignore any further statements in a function block that
is contained within the ST program. If the debugger is set to Step Into when you select
this option, it will execute the remaining statements in the function block and then
return to the main part of the ST program.

125

Chapter 4 - ST Programs

Run to CursorSets the debugger to execute the program statements up to the cursor
position. When you select this option, the position of the cursor acts like a breakpoint.

Show Next StatementPositions the cursor at the line of the next statement that is to
be executed.

VariablesDisplays the Variables window. You need to use this window to view the
values that are being produced by each section of the ST program. By examining the
values that are produced, you can determine which values are unexpected (and
therefore which parts of the ST code may be incorrect). For more information, see
Viewing the Variables in your ST Program, on page 127.

Rerun on CompletionBy default, when the debugger has executed every statement
successfully, it waits a short time before starting the debugging process again. You can
use the following options to control how long the debugger waits and whether it will
repeat the debugging process:

EnabledWhen this option is selected, the debugger will repeat itself after it has
executed each statement successfully. It will wait for a specific amount of time before it
repeats.
If you clear this option, the debugger will only run once.

126

Break on ErrorThe debugger will execute each statement in the program (up to a
breakpoint if a breakpoint is defined). If there is an error in the program, the debugger
will stop at the line in which the error occurs.

After 1s, 2s, 5s, 10s, 30s, 60sDefines the amount of time the debugger will wait after
successfully executing each statement before it starts again. The options correspond to
1 second, 2 seconds, 5 seconds, 10 seconds, 30 seconds, and 60 seconds
respectively.

PD-6017 07/2012

Chapter 4 - ST Programs

Viewing the Variables in your ST Program


When you display an ST program in Run mode, you can view a list of the variables in an
ST program. The list shows the current values for the variables and is often used during
debugging. The variables window is useful during debugging as it allows you to view the
variables that are produced by each section of the code (you need to use breakpoints to
separate the ST code into sections).
To display the variables window:
Either:
1.

Display your ST program in Design mode, then select the Build menu then the Start
Debugging option.

The program switches to Run mode.


2.

Select the Debug menu, then select the Variables option.

The variables window is displayed.


Or:
1.
2.

Display the ST program in Run mode (right-click on it in the Database Bar then select
the Display option).
Select the Debug menu, then select the Variables option.

The variables window is displayed.

The variables window contains expandible lists of the variables in your ST program. For
each variable, it lists the Name of the variable, the Type (which shows the data type), and
the Value (which shows the current value of the variable).
For more information, please refer to Debugging an ST Program or ST Library (see page
124).

PD-6017 07/2012

127

Chapter 4 - ST Programs

128

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

5 Ladder Diagrams

Ladder Diagrams are graphical programs that are similar to 'relay ladder' programs.
Traditionally, 'relay ladder' programs have been used to program PLCs and similar
devices. They are ideally suited to programs that provide complicated AND and OR logic.
If you are familiar with 'relay ladder' programs, you will soon become accustomed to
working with Ladder Diagrams as they use similar symbols and features.
The following sections explain the concepts and features of Ladder Diagrams:

How Ladder Diagrams Work (see page 130)

Ladder Diagram Components (see page 131)

Create a Ladder Diagram Database Item (see page 132)

Edit a Ladder Diagram (see page 132)

Ladder Diagram Display (see page 133)

Add Variables to a Ladder Diagram (see page 134)

Add Processed Historic Values to Ladder Diagrams (see page 141)

Add a Constant Value to a Ladder Diagram (see page 145)

Add a Function to a Ladder Diagram (see page 146)

Add a Function Block to a Ladder Diagram (see page 147)

Add a Conversion to a Ladder Diagram (see page 148)

Add a Comment to a Ladder Diagram (see page 149)

Controlling the Flow of a Ladder Diagram (see page 150)

Edit a Variable on a Ladder Diagram (see page 151)

Rename a Variable on a Ladder Diagram (see page 151)

Delete a Variable on a Ladder Diagram (see page 152)

Compiling a Ladder Diagram (see page 153)

Viewing the Variables in your Ladder Diagram (see page 154)

Changing the Update Interval for a Ladder Diagram (see page 155).

For information on the properties of the Ladder Diagram database item, see Logic
Program Properties and Values, on page 359.

PD-6017 07/2012

129

Chapter 5 - Ladder Diagrams

How Ladder Diagrams Work


In ClearSCADA, each Ladder Diagram represents a circuit consisting of 2 rails. Between
the 2 rails are a 'rung' of contacts and coils that represent the inputs and outputs. Each
'rung' represents an AND Logic function. By adding branches to a rung, you can create
OR Logic functions.
Power for the circuit starts at the left rail and passes through the contacts and coils to the
right rail. The power can only pass through the contacts if they are in a 'true' state. When
power reaches a coil and passes to the right rail, an output is written.
For example, a simple Ladder Diagram can be used to set a pump to start when both a
flow is detected and power is detected in the pump. The inputs from the flow detection
and pump power sensors are represented by direct contacts and the command to start
the pump is represented by a coil.

In the Ladder Diagram shown above, the StartPump coil is only put into effect when the
FlowPresent and PumpPower contacts are 'true'. As the FlowPresent contact is 'false',
the power from the left rail cannot pass the FlowPresent contact and so the StartPump
coil is not activated.
If both the FlowPresent and PumpPower contacts were 'true', the power from the left rail
would pass through the contacts to the StartPump coil and on to the right rail. This means
that the circuit is complete and the StartPump coil is put into effect.

By default, each rail on the Ladder Diagram is 'true'. In ClearSCADA, you can set the state
of a rail to be dependent on another value. This allows you to associate Ladder Diagrams
with other Ladder Diagrams or other Logic programs. For example, you can set the left rail
of a Ladder Diagram to be 'false' except when a Function Block Diagram has an output of
'true'. This means that the Ladder Diagram only runs when the Function Block Diagram
has been executed and returned a 'true' valuethe output of the Function Block Diagram
program is written to the state of the left rail.

130

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Ladder Diagram Components


ClearSCADA uses the following symbols to represent the various parts of a Ladder
Diagram:

Symbol

Description
Direct contact. This type of contact allows the power to flow from the left rail
to the right rail when the value is 1.

Inverted contact.This type of contact allows the power to flow from the left
rail to the right rail when the value is 0.

Positive sensing contact.This type of contact acts as a pulse. When there is


power from the left rail, the contact value momentarily switches to 1. When
there is no power, the contact value is 0.

A negative sensing contact acts as a pulse. It has the reverse effect of the
Positive sensing contact. When there is power, the contact value is 0. When
there is no power, the contact value momentarily switches to 1.

A direct coil writes a value to a database item. If there is power from the left
rail, it writes a 1 value. If there is no power from the left rail, it writes a 0
value.

Inverted coil. This output writes a value to a database item. It has the reverse
effect of a direct coil. If there is power from the left rail, it writes a 0 value. If
there is no power from the left rail, it writes a 1 value.

Set coil. This output is set to 1 when there is power from the left rail. Set Coil
works in a similar way to an 'On' switchwhen it is set to On by the power
from the left rail, it remains On until it is specifically set to Off (by a reset).

Reset coil. This output is set to 0 when there is power from the left rail. Set
Coil works in a similar way to an 'Off' switchwhen it is set to Off by the
power from the left rail, it remains Off until it is specifically set to On (by a
Set).
Positive sensing coil. This output acts as a pulse. When the input from the
left rail changes from 0 to 1, the coil outputs a 1 value. When the next rung of
the Ladder Diagram is executed, the positive sensing coil reverts to having a
0 output.
Negative sensing coil. This output acts as a pulse. When the input from the
left rail changes from 1 to 0, the coil outputs a 1 value. When the next rung of
the Ladder Diagram is executed, the positive sensing coil reverts to having a
0 output.

Ladder Diagrams can also contain Constants, Connection Blocks, Functions, Function
Blocks, and Conversions (see Controlling the Flow of a Ladder Diagram, on page 150).

PD-6017 07/2012

131

Chapter 5 - Ladder Diagrams

Create a Ladder Diagram Database Item


Each Ladder Diagram needs to be represented in the ClearSCADA database by a Ladder
Diagram item. When you have created a Ladder Diagram item, you can access its Edit
feature which allows you to create the Ladder Diagram program.
To create a Ladder Diagram database item:
1.

In the Database Bar, right-click on a system, Group, or Group Template to display a


context sensitive menu.

2.

Select the New option, then the Logic option, then the Ladder Diagram option from the
context sensitive menu.

A new Ladder Diagram item is added to the system, Group, or Group Template. It is
selected automatically, ready for you to enter its name.
3.

Enter a suitable name for the Ladder Diagram then press the Enter key or select another
part of the interface.

Ladder Diagram database item (shown in a Group).

Now that you have created a Ladder Diagram database item, you can edit it (see Edit a
Ladder Diagram, on page 132).

Edit a Ladder Diagram


You can display a Ladder Diagram in Design mode by double-clicking on a Ladder
Diagram item in the Database Bar. In Design mode, you can edit the Ladder Diagram by
adding or removing contacts and coils and making connections.
To edit a Ladder Diagram, either:

Double-click on a Ladder Diagram item in the Database Bar.

Or:

Right-click on a Ladder Diagram item in the Database Bar, then select the Edit option
from the context sensitive menu.

The Ladder Diagram is displayed in the ViewX Application window (see Ladder Diagram
Display, on page 133).

132

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Ladder Diagram Display


When you double-click on a Ladder Diagram item or select its Edit option, the Ladder
Diagram display is shown.
The Ladder Diagram display consists of:
Database Bar. You can drag items such Direct and Internal Variables. These tabs contain lists of the
as points from the Database Bar onto properties and values that are included in the Ladder
the Ladder Diagram.
Diagram.

The Ladder Diagram.


You can design the Ladder
Diagram by adding
contacts, coils, etc.

The compiler display. Compiling


and debugging information is
shown here.

Database BarThe Database Bar contains a hierarchical view of the ClearSCADA


database. You can drag an item from the Database Bar onto the Ladder Diagram to
create a contact or coil for the item.

Direct and Internal VariablesThe variables tabs contain a list of the values that are
included in the Ladder Diagram. The Direct tab contains the values that are associated
with database items, and the Internal tab contains a list of internal variables such as
function blocks.

Ladder DiagramThe Ladder Diagram contains the rails, contacts, coils, functions,
function blocks, and connections that form the Ladder Diagram. This is where you
create the Logic of the Ladder Diagram.

Compiler DisplayThe compiler display is where ClearSCADA displays diagnostic


information for your Ladder Diagram. Any messages associated with compiling and
debugging are shown here.

PD-6017 07/2012

133

Chapter 5 - Ladder Diagrams

Add Variables to a Ladder Diagram


Each value that is read or written by your Ladder Diagram is represented by a variable or
a constant. Constant values are fixed values and are described in Add a Constant Value to
a Ladder Diagram (see page 145). Variable values change according to the data that is
stored in your system and the calculations that are performed on it.
There are 2 types of variable:

Internal variables are values that are used by the program but are not written to an item
in the database. For example, values that are used in a conversion.

Direct variables are values that are stored in the database, for example, a point value.

The following sections explain how to add variables to your Ladder Diagram:

Add a Direct Variable to a Ladder Diagram (see page 134)

Add an Internal Variable to a Ladder Diagram (see page 139).

Add a Direct Variable to a Ladder Diagram


The method that you use to add a direct variable to your Ladder Diagram will vary
depending on whether the diagram already contains an instance of the value.
If your diagram does not already contain an instance of the direct variable that you want
to add, refer to Add the First Instance of a Direct Variable to a Ladder Diagram (see page
135).
If your diagram already contains an instance of the direct variable that you want to add,
refer to Add Another Instance of a Direct Variable to a Ladder Diagram (see page 137).

134

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add the First Instance of a Direct Variable to a Ladder Diagram


To add the first or only instance of a direct variable to a Ladder Diagram:
1.

2.

In the Database Bar, select the database item that represents the direct variable that
you want to add to the Ladder diagram. For example, if you want to add the value of a
point named 'INT 1', select the 'INT 1' point item. When you select the item, keep the
left-hand mouse button pressed down.
Drag and drop the database item onto the Ladder Diagram.

The Add Direct Variable window is displayed.

3.

Use the Add Direct Variable window to define the settings for the direct variable:

NameEnter the name for the direct variable. This name will be used to refer to the
variable within the program. A name is entered automatically when you drag a direct
variable onto the Ladder Diagram, but you can change it as required.

Tag TypeChoose the type of direct variable tag. This can be:

Read/Write (%M)The Ladder Diagram can both read the value and overwrite
it with a new value.

Read Only (%I)The Ladder Diagram can only read the value and cannot
change it.

Write Only (%Q)The Ladder Diagram cannot read the variable but can write a
new value to it.

TagThis is the name of the OPC property that represents the variable that you
want to add to the Ladder Diagram. The tag can be an OPC tag (for normal, direct
variable values) or an OPC Historic tag (see Add Processed Historic Values to
Ladder Diagrams, on page 141).

TypeChoose the type of value. The value type needs to be appropriate to the
value that is represented by the selected tag. For more information, please refer to
Built-In Data Types (see page 63).

InsertChoose the type of variable tag that you are adding to the Ladder Diagram.
Choose the required type of contact or coil from the combo box (see Ladder
Diagram Components, on page 131).

RetainedThe Retained feature is designed to be used with internal variables.


When selected, it allows the internal variable to be stored and transferred to other
servers (in a multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

PD-6017 07/2012

135

Chapter 5 - Ladder Diagrams

No CacheUse the No Cache check box to determine whether the program uses
the latest value or the initial value for a variable on each execution. If you check the
No Cache check box, the program will use the latest value for the variable rather
than the default value. If you clear the No Cache check box, the program will use
the default value for the variable on each execution.
The No Cache feature is especially useful with variables that are used as counts.
For more information on the No Cache feature, please refer to Using VAR
NOCACHE to Prevent Cached Values Being Used in an ST Program (see page 46).

4.

Select the OK button to confirm.

A direct variable tag is added to the Ladder Diagram. You can then draw connections to
or from it (see Controlling the Flow of a Ladder Diagram, on page 150).
If you need to add another instance of the direct variable to your Ladder Diagram, see
Add Another Instance of a Direct Variable to a Ladder Diagram, on page 137.

136

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add Another Instance of a Direct Variable to a Ladder Diagram


You can use the Variables list to add multiple instances of the same direct variable to a
Ladder Diagram. You can add the first instance of the direct variable by dragging the
corresponding database item from the Database Bar onto the Ladder diagram and then
configuring the variable settings. For subsequent instances of the direct variable, you can
use the Add option that is available from the Direct tab of the Variables list:
To add another instance of a direct variable:
1.

In the Variables list (above the Ladder Diagram in the ladder display), select the Direct
tab.

A list of the Ladder Diagram's direct variables is shown.


2.

Click anywhere on the Variables pane.

A context sensitive menu is displayed.


3.

Select the Add option.

The Add Direct Variable window is displayed.


NOTE: As an alternative to steps 1-3 inclusive, you can drag and drop the same item
onto the Ladder Diagram twice. When you add a direct variable, the Add Direct Variable
window is displayed. You will need to rename the second instance of the item by using
the Add Direct Variable window's Name field.
4.

Use the Add Direct Variable window to define the new instance of the variable:

Enter a Name for the direct variable. The name has to be unique. It cannot have the
same name as any variables that are already included in the Ladder diagram.

Use the Tag Type combo box to define whether the variable is Read Only, Write
Only, or Read/Write.

Use the browse button feature of the Tag field to select the database property that
is the source of the variable's value. The tag can be an OPC tag (for normal, direct
variable values) or an OPC Historic tag (see Add Processed Historic Values to
Ladder Diagrams, on page 141).

Use the Type combo box to choose the type of value. The value type needs to be
appropriate to the value that is represented by the selected tag. For more
information, please refer to Built-In Data Types (see page 63).

The Retained feature is designed to be used with internal variables. When selected,
it allows the internal variable to be stored and transferred to other servers (in a
multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

PD-6017 07/2012

137

Chapter 5 - Ladder Diagrams

Use the No Cache check box to determine whether the program uses the latest
value or the initial value for a variable on each execution. If you check the No Cache
check box, the program will use the latest value for the variable rather than the
default value. If you clear the No Cache check box, the program will use the default
value for the variable on each execution.
The No Cache feature is especially useful with variables that are used as counts.
For more information on the No Cache feature, please refer to Using VAR
NOCACHE to Prevent Cached Values Being Used in an ST Program (see page 46).

5.

Select the OK button to confirm your selection.

The Add Direct Variable window is closed.


6.

Select the new variable in the Variables list and keep the left-hand mouse button
pressed down.

7.

Drag the new variable from the Variables list onto the Ladder diagram.

A context sensitive menu is displayed.


8.

Select the option that corresponds with the type of variable that you are adding to the
Ladder diagram (see Ladder Diagram Components, on page 131).

A new contact or coil is added to the Ladder diagram, depending on the option you
selected. The contact or coil represents the new instance of the variable.

138

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add an Internal Variable to a Ladder Diagram


Internal variables are values that are used by the program but are not written to an item in
the database. They are used for:

Conversions

Separating long, complex calculations into smaller sets of calculations

Storing program states.

To add an internal variable to a Ladder Diagram:


1.

On the Ladder diagram display, select the Internal tab on the Variables list.

2.

Right-click in an empty row on the Variables list to display a context sensitive menu.

3.

Select the Add option to display the Add Internal Variable window.

4.

Use the Add Internal Variable window to define the settings for the internal variable:

PD-6017 07/2012

Enter a Name for the direct variable. The name has to be unique. It cannot have the
same name as any variables that are already included in the Ladder diagram.

Use the Type combo box to choose the type of value. The value type needs to be
appropriate to the internal variable. For more information, please refer to Built-In
Data Types (see page 63).

In the Initial Value field, enter the default value for the internal variable. This is the
first value of the internal variable. The internal variable will reset to this value for
each execution of the Ladder Diagram executes unless the Retained feature is used
(see below).

Use the Retained check box to determine whether the internal variable is stored
and transferred to other servers. For more information on the Retain feature, see
Using the RETAIN Keyword in an ST Program, on page 42.

Check the Retained check box to allows the internal variable to be stored and
transferred to other servers (in a multi-server setup).

Clear the Retained check box to prevent the internal variable from being stored
and transferred to other servers. This will result in the internal variable being
reset to its initial value each time the Ladder Diagram executes.

139

Chapter 5 - Ladder Diagrams

5.

Select the OK button to confirm the settings and close the Add Internal Variable
window.

6.

Select the internal variable in the Variables list and keep the left-hand mouse button
pressed down.

7.

Drag the internal variable from the Variables list onto the Ladder diagram.

A context sensitive menu is displayed.


8.

Select the option that corresponds with the type of internal variable that you are adding
to the Ladder diagram (see Ladder Diagram Components, on page 131).

A new contact or coil is added to the Ladder diagram, depending on the option you
selected. The contact or coil represents the internal variable.

140

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add Processed Historic Values to Ladder Diagrams


You can add processed historic values (historic values that have been calculated using a
historic algorithm) to your Ladder Diagrams. This may be useful if you need to use a daily
average or some other calculated value as part of the ladder Logic.
To add a processed historic value to a Ladder Diagram:
1.

Display the Add Direct Variable window by performing one of these procedures:
Either:
i.

In the Variables list (above the Ladder Diagram in the ladder display), select the
Direct tab.

A list of the Ladder Diagram's direct variables is shown.


ii. Right-click on the direct variable that you want to use again.

A context sensitive menu is displayed.


iii. Select the Add option.

The Add Direct Variable window is displayed.


Or:
i.

In the Variables list (above the Ladder Diagram in the ladder display), select the
Direct tab.

A list of the Ladder Diagram's direct variables is shown.


ii. Right-click on the direct variable that you want to use again.

A context sensitive menu is displayed.


iii. Select the Add option.

The Add Direct Variable window is displayed.


2.

In the Name field, enter a suitable name for the variable.

3.

Use the Tag Type combo box to define whether the variable is Read Only, Write Only, or
Read/Write.

4.

Select the browse button next to the Tag field.

A context sensitive menu is displayed.

PD-6017 07/2012

141

Chapter 5 - Ladder Diagrams

5.

Select the OPC Historic Tag option to display the Select Historic Tag window.

6.

Expand a Root Group folder. Each Root Group folder represents a system.

7.

Expand the group folders until you locate the item that has the required historic data.

This is the item that has the historic data that you want to use as a value on your Ladder
Diagram.
8.

Expand the item. A historic icon is shown.

9.

Select the historic icon. This will associate the variable tag with the historic data of the
selected database item.

10. Use the check box and combo boxes at the bottom of the Select Historic Tag window
to define the time span and historic algorithm:

142

RelativeUse to determine whether a relative or absolute reference is used to


reference the item's historic tag.

Check the check box to use a relative reference to the item's historic tag. The
reference will work as long as the location of the selected database item
remains the same in relation to the Ladder Diagram.

Clear the check box to use an absolute reference. The reference will only work
when the selected database item remains in the current location.

AlgorithmChoose the type of historic calculation that ClearSCADA uses to


process the historic data.

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Start DateChoose or enter the start time for the range of historic values. The
Ladder Diagram can only use historic values that have been recorded after the
selected date.
You can choose from the following default options or you can enter a start time:

MThe time period starts at the beginning of the current minute.

M-1MThe time period starts at the beginning of the previous minute.

HThe time period starts at the beginning of the current hour.

H-1HThe time period starts at the beginning of the previous hour.

DThe time period starts at the beginning of the current day.

D-1DThe time period starts at the beginning of the previous day.

WThe time period starts at the beginning of the current week.

W-1WThe time period starts at the beginning of the previous week.

To enter a start date, simply enter the time in the OPC format. For example, if you
want the start date to be 3 weeks prior to the start of the current week, enter W-3W.

IntervalEnter or choose the duration of the time period. The Ladder Diagram will
only use those historic values that were recorded after the start date and within the
specified interval. For example, if the Start Date is H and the Interval is 30M, the
time period is 30 minutes after the start of the current hour. Any historic values that
were recorded for the item outside of this time period are disregarded.
As with the Start Date, you can choose from the list of default intervals, or you can
enter your own interval in the OPC time format. If the Interval is set to 0, the
program cannot be executed.

11. Select the OK button to confirm your selection and close the Select Historic Tag
window.
12. On the Add Direct Variable window, use the Type combo box to choose the type of
value for the historic variable. The type of value that you select has to be appropriate for
the type of database item. For more information, see Built-In Data Types, on page 63.
13. Leave the Retained check box clear. The Retained feature is designed to be used with
internal variables. When selected, it allows the internal variable to be stored and
transferred to other servers (in a multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.
14. Use the No Cache check box to determine whether the program uses the latest value or
the initial value for a variable on each execution. If you check the No Cache check box,
the program will use the latest value for the variable rather than the default value. If you
clear the No Cache check box, the program will use the default value for the variable on
each execution.
The No Cache feature is especially useful with variables that are used as counts. For
more information on the No Cache feature, please refer to Using VAR NOCACHE to
Prevent Cached Values Being Used in an ST Program (see page 46).
15. Select the OK button to confirm your selections and close the Add Direct Variable
window.

PD-6017 07/2012

143

Chapter 5 - Ladder Diagrams

16. Select the historic variable in the Variables list (Direct tab) and keep the left-hand mouse
button pressed down.
17. Drag the historic variable from the Variables list onto the Ladder diagram.

A context sensitive menu is displayed.


18. Select the option that corresponds with the type of internal variable that you are adding
to the Ladder diagram (see Ladder Diagram Components, on page 131).

A new contact or coil is added to the Ladder diagram, depending on the option you
selected. The contact or coil represents the internal variable.

144

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add a Constant Value to a Ladder Diagram


Constant values are values that remain the same each time the program executes, such
as pi, time intervals, fixed text string etc. For example, if a program needs a point to
change state after a 2 minute pause, a constant can be used to define the 2 minute time
period. Although the time period does decrease from 120 seconds to 0 seconds as the
program executes, it is still represented by a constant as the time value is 120 seconds
when the program is executed.
To add a constant value to a Ladder Diagram:
1.

Right-click on the background of the Ladder diagram.

A context sensitive menu is displayed.


2.

Select the Add Constant option.

The Set Constant window is displayed.

3.

Enter the Constant value. The value needs to include any code characters. For more
information, see Built-In Data Types, on page 63.

4.

Select the OK button to confirm the entry and close the Set Constant window.

A constant tag is added to the Ladder Diagram. Constant tags are coloured blue, and
can be connected to other parts of the diagram.

NOTE: Unlike internal and direct variables, constants can only be of a certain data type. Each
constant value has to be one of the Built-In Data Types (see page 63).

PD-6017 07/2012

145

Chapter 5 - Ladder Diagrams

Add a Function to a Ladder Diagram


Functions are single calculations that can be applied to a value. Each function reads an
input, performs a calculation, and outputs the result of the calculation as a value. There
are many types of function (each function type performs a different type of calculation).
Functions are useful for converting values, adding values, etc.
To add a function to a Ladder Diagram:
1.

Right-click on the background of the Ladder Diagram.

A context sensitive menu is displayed.


2.

Select the Functions option to display another menu.

3.

Select the option for the type of function that you want to add to the Ladder Diagram.

A further menu is displayed.

4.

Select the function that you require.

The function is added to the Ladder Diagram.


For more information on the available functions, see Built-In Functions, on page 226.

146

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add a Function Block to a Ladder Diagram


Function blocks are blocks of code that define a type of Logic behavior or calculation. You
can use them in your Ladder Diagrams to provide the Logic or calculations that you
require in your program. There are several types of function block available, and you can
also create custom function blocks if required.
To add a function block to a Ladder Diagram:
1.

Right-click on the background of the Ladder Diagram.

A context sensitive menu is displayed.


2.

Select the Function Blocks option to display another menu.

3.

Select the option for the type of function block that you want to add to the Ladder
Diagram.

The function block is added to the Ladder Diagram.


For more information on the available function blocks, see Built-In Function Blocks, on
page 319.
NOTE: You can also add User Function Blocks to your Ladder Diagrams (see User Function
Blocks, on page 349).

PD-6017 07/2012

147

Chapter 5 - Ladder Diagrams

Add a Conversion to a Ladder Diagram


Conversions are built-in features that convert the data type of one value into a different
data type. For example, the BYTE_TO_BOOL conversion turns a byte value into a boolean
value. Typically, the conversions are needed when an input value of one data type needs
to be converted into another data type for the Logic program to work.
To add a conversion to a Ladder Diagram:
1.

Right-click on the background of the Ladder Diagram.

A context sensitive menu is displayed.


2.

Select the Conversions option to display another menu.

3.

Select the option for the data type that you want to convert on the Ladder Diagram.
A further menu is displayed.

4.

Select the option that describes the type of conversion. For example, to convert a
boolean value into a string value, select the BOOL_TO_STRING option.

The conversion is added to the Ladder Diagram.


For more information on the data types, see Built-In Data Types, on page 63.

148

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Add a Comment to a Ladder Diagram


When you are designing a Ladder Diagram, you can add comments that can be read by
other users. You can use the comments to add any text, but typically they are used to
explain the purpose of various parts of the Ladder Diagram.
To add a comment to a Ladder Diagram:
1.

Right-click on the background of the Ladder Diagram.

A context sensitive menu is displayed.


2.

Select the Add Comment option to display the add comment window.

3.

Enter your comment.

4.

Select the OK button to confirm your entry and close the Add Comment window.

The comment is added to the Ladder Diagram.

You can move the comment around on the Ladder Diagram in the same way as other
items.
You can edit the comment by double-clicking on itthis will display the Edit Comment
window which works in the same way as the Add Comment window.

PD-6017 07/2012

149

Chapter 5 - Ladder Diagrams

Controlling the Flow of a Ladder Diagram


When you have added the various conversions, functions, function blocks etc. that form
your Ladder Diagram, you need to make connections. The connections define how the
various components relate to one another.
When making connections, you may need to move items around the diagram. To do this,
simply select the item, then drag it to the required location before releasing the left-hand
mouse button.
For more information on connections, refer to:

Make a Connection on a Ladder Diagram (see page 150)

Add a Connection Block to a Ladder Diagram (see page 150).

Make a Connection on a Ladder Diagram


To make a connection on a Ladder Diagram:
1.

Select a connection box on one of the items you want to connect. Keep the left-hand
mouse button pressed down.

2.

Drag the cursor to a connection box on the other item (the item to which you are
connecting the item in step 1).

3.

Release the left-hand mouse button.

A connection line is drawn (if the connection is valid).

Add a Connection Block to a Ladder Diagram


You can use connection blocks to group multiple connection lines. The connection blocks
work in a similar way to the OR function blockif any of the inputs from the connection
block are true, the output of the connection block is true. Connection blocks are designed
to reduce the clutter on your Logic diagrams.
To add a connection block to a Ladder Diagram:
1.

Right-click on the background of the diagram to display a context sensitive menu.

2.

Select the Add Connection Block option.

A new connection block is added to the diagram.

You can connect single or multiple connection lines to the input and output connection
boxes on the connection block. The system will group the lines automatically so that the
diagram is clear and uncluttered.

150

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Edit a Variable on a Ladder Diagram


You can edit any variable that you have added to your Ladder Diagram. This is useful
when you have made a mistake or when you need to make a small adjustment to the
program.
To edit a variable on a Ladder Diagram:
1.

In the Variables list above the Ladder Diagram, right-click on the variable you want to
edit (on the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Edit option.

The Edit Direct Variable window or Edit Internal Variable window is displayed,
Depending on which type of variable you selected.
3.

Use the Edit Direct Variable window or Edit Internal Variable window to alter the settings
for the variable. The settings work in the same way as on the Add Direct Variable
window and the Add Internal Variable window (see Add Variables to a Ladder Diagram,
on page 134).

Rename a Variable on a Ladder Diagram


As you need to allocate a different name to each variable, you may need to rename the
variables you have on your Ladder Diagram.
To rename a variable on a Ladder Diagram:
1.

In the Variables list above the Ladder Diagram, right-click on the variable you want to
rename (on the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Rename option.

The name of the variable is selected. You can alter or overwrite the name as required
simply use the keyboard to enter the new name for the variable.
3.

PD-6017 07/2012

Press the Enter key or select another part of the interface to confirm the name entry.

151

Chapter 5 - Ladder Diagrams

Delete a Variable on a Ladder Diagram


You can use the Delete option to remove unwanted variables from your Ladder Diagram.
To delete a variable on a Ladder Diagram:
1.

In the Variables list above the Ladder Diagram, right-click on the variable you want to
delete (on the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Delete option.

A confirmation window is displayed.


3.

Select the OK button to confirm the deletion and close the confirmation window.

The variable is removed from the Ladder Diagram.

152

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Compiling a Ladder Diagram


You can use the Build menu options to compile your Ladder Diagram. The compilation
feature is useful as it checks that your Ladder Diagram has the correct syntax.
There are 2 compile options:

CompileCompiles the diagram. If the program is invalid, the compiler display


provides a message with a brief explanation of any syntax errors. If the syntax is
correct, the compiler displays a success message.

Compile with DiagnosticsCompiles the Ladder Diagram and provides detailed


diagnostic information. As with the Compile option, there are messages for any errors in
the syntax. If the syntax is correct, the compiler displays a success message.
NOTE: The Compile with Diagnostics tool is useful when you want to use a Ladder
Diagram as an ST programs. For example, you may find it easier to create a Ladder
Diagram and then use the Compile with Diagnostics tool to access the ST code for the
Ladder Diagram. You can then copy this code into an ST program (you have to remove
the $ signs in the code).

To compile a Ladder Diagram:


1.

Display the Ladder Diagram in Design mode.

2.

Select the Build menu, then select the Compile option or the Compile with Diagnostics
option as required.

The Ladder Diagram is compiled and the compile messages are shown in the Compiler
display.
If there are errors, you will need to alter the Ladder Diagram. Typically, the causes of
invalid syntax are minor, such as the wrong type of value being specified or a missing
connection.

PD-6017 07/2012

153

Chapter 5 - Ladder Diagrams

Viewing the Variables in your Ladder Diagram


When you display a Ladder Diagram in Run mode, you can view a list of the variables it
uses. The list shows the current values for the variables. The variables window is useful as
it allows you to view the variables that are produced by part of the diagram.
To display the variables window:
1.

Display the Ladder Diagram in Run mode (right-click on it in the Database Bar then
select the Display option).

2.

Select the Run menu, then select the Variables option.

The variables window is displayed.

The variables window contains expandible lists of the variables in your Ladder Diagram.
For each variable, it lists the Name of the variable, the Type (which shows the data type),
and the Value (which shows the current value of the variable).

154

PD-6017 07/2012

Chapter 5 - Ladder Diagrams

Changing the Update Interval for a Ladder Diagram


You can use the Update Interval feature to define how often your ClearSCADA client PC
requests updates for a Ladder Diagram. By default, ClearSCADA clients request an
update from a ClearSCADA server for the latest variable values every second.
By using the Update Interval feature, you can set your ClearSCADA client PC to request
variable updates at a slower rate.
To change the update interval for a Ladder Diagram:
1.

Display the Ladder Diagram in Run mode (right-click on it in the Database Bar then
select the Display option).

2.

Select the Run menu, then select the Update Interval option.

A further menu is displayed.

3.

PD-6017 07/2012

Select the required interval from the list of options. The intervals range from 1 second to
60 seconds.

155

Chapter 5 - Ladder Diagrams

156

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

6 Function Block Diagrams

Function Block Diagrams are graphical programs that allow you to define a series of
processes that are dependent on a flow. The flow of a signal from one function block to
another means that you can create complex relationships between values, functions etc.
to define the Logic behavior of your program.
To familiarize yourself with the concepts and features for Function Block Diagrams, refer
to these sections:

How Function Block Diagrams Work (see page 158)

Function Block Diagram Components (see page 159)

Create a Function Block Diagram Database Item (see page 160)

Edit a Function Block Diagram (see page 160)

Function Block Diagram Display (see page 161)

Add Variables to a Function Block Diagram (see page 162)

Add Processed Historic Values to Function Block Diagrams (see page 169)

Add a Constant Value to a Function Block Diagram (see page 174)

Add a Function to a Function Block Diagram (see page 175)

Add a Function to a Function Block Diagram (see page 175)

Add a Conversion to a Function Block Diagram (see page 177)

Add a Comment to a Function Block Diagram (see page 178)

Create a Ladder Diagram within a Function Block Diagram (see page 179)

Controlling the Flow of a Function Block Diagram (see page 180)

Edit a Variable on a Function Block Diagram (see page 181)

Rename a Variable on a Function Block Diagram (see page 182)

Delete a Variable on a Function Block Diagram (see page 183)

Compiling a Function Block Diagram or Function Block Library (see page 184)

Viewing the Variables in your Function Block Diagram (see page 185)

Changing the Update Interval for a Function Block Diagram (see page 186)

Viewing the Values on a Function Block Diagram (see page 187).

For information on the properties of the Function Block Diagram database items, see
Logic Program Properties and Values, on page 359.

PD-6017 07/2012

157

Chapter 6 - Function Block Diagrams

How Function Block Diagrams Work


Function Block Diagrams have inputs and outputs, and also contain functions, function
blocks, conversions etc. Each Function Block Diagram uses its functions, function blocks
etc. to determine outputs based on the values for its inputs.
By creating connections between the various function block components, you can create
complex behavior Logic. For example, the following Function Block Diagram is used to
control a pump in the water industry:

In this example, the states of the four input points (StartPump, StopPump, ResetLockOut,
and FlowPresent) are used to determine whether the pump starts, stops, or is reset. The
connections between the various functions and function blocks define the behavior that is
provided by the Function Block Diagram:

If the StartPump input is true, the pump will start (PumpStart output is true) as long as
the FlowPresent value is true and the pump is not locked out (LockedOut value is false).

If the pump is locked out (LockedOut value is true), the PumpStart output will not
change in response to the StartPump or StopPump inputsit will only change after the
ResetLockOut input has become true and the LockedOut output is false.

The PumpState output can only be true if the StartPump input is true, and the
FlowPresent input is true, and the LockedOut output is false. This means that the pump
will only be switched on when

it has a start signal

can detect a flow

is not locked out

There is a time delay between the StartPump and StopPump signals affecting the state
of the PumpState output. This means that fleeting state changes will not affect the
outputs.

158

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Function Block Diagram Components


Function Block Diagrams can consist of the following items:

Ladder Diagram components such as railssee Create a Ladder Diagram within a


Function Block Diagram, on page 179.

Connection Boxessee Add a Connection Block to a Function Block Diagram, on page


181.

Built-in Function Blockssee Add a Function Block to a Function Block Diagram, on


page 176.

Built-in Functionssee Add a Function to a Function Block Diagram, on page 175.

Constantssee Add a Constant Value to a Function Block Diagram, on page 174.

Conversionssee Add a Conversion to a Function Block Diagram, on page 177.

Direct Variablessee Add Variables to a Function Block Diagram, on page 162.

Internal Variablessee Add Variables to a Function Block Diagram, on page 162.

User Function Blockssee User Function Blocks, on page 349.

The various components of a Function Block Diagram are connected via connection lines,
which you can draw to link the connection box of one component to a connection box on
another component. These connections allow you to control the flow of the Function
Block Diagram (see Edit a Variable on a Function Block Diagram, on page 181).

PD-6017 07/2012

159

Chapter 6 - Function Block Diagrams

Create a Function Block Diagram Database Item


Each Function Block Diagram needs to be represented in the ClearSCADA database by a
Function Block Diagram item. When you have created a Function Block Diagram item,
you can access its Edit feature which allows you to create the Function Block Diagram
program.
To create a Function Block Diagram database item:
1.

In the Database Bar, right-click on a system, Group, or Group Template to display a


context sensitive menu.

2.

Select the New option, then the Logic option, then the Function Block Diagram option
from the context sensitive menu.

A new Function Block Diagram item is added to the system, Group, or Group Template.
It is selected automatically, ready for you to enter its name.
3.

Enter a suitable name for the Function Block Diagram then press the Enter key or select
another part of the interface.

Function Block Diagram database item


(shown in a Group).

Now that you have created a Function Block Diagram database item, you can edit it (see
Edit a Function Block Diagram, on page 160).

Edit a Function Block Diagram


You can display a Function Block Diagram in Design mode by double-clicking on a
Function Block Diagram item in the Database Bar. In Design mode, you can edit the
Function Block Diagram by adding or removing values and components such as
functions.
To edit a Function Block Diagram, either:

Double-click on a Function Block Diagram item in the Database Bar.

Or:

Right-click on a Function Block Diagram item in the Database Bar, then select the Edit
option from the context sensitive menu.

The Function Block Diagram is displayed in the ViewX Application window (see Function
Block Diagram Display, on page 161).

160

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Function Block Diagram Display


When you double-click on a Function Block Diagram item or select its Edit option, the
Function Block Diagram display is shown.
The Function Block Diagram display consists of:
Database Bar. You can drag items such Direct and Internal Variables. These tabs contain lists of the
as points from the Database Bar onto properties and values that are included in the Function
the Function Block Diagram.
Block Diagram.

The Function Block Diagram.


You can design the Function Block Diagram
by adding values, functions, etc.

The compiler display. Compiling


and debugging information is
shown here.

Database BarThe Database Bar contains a hierarchical view of the ClearSCADA


database. You can drag an item from the Database Bar onto the Function Block
Diagram to create a variable for the item.

Direct and Internal VariablesThe variables tabs contain a list of the values that are
included in the Function Block Diagram. The Direct tab contains the values that are
associated with database items, and the Internal tab contains a list of internal variables
such as function blocks.

Function Block DiagramThe Function Block Diagram contains the functions, function
blocks, variables, constants, etc. form the Function Block Diagram. This is where you
create the Logic of the Function Block Diagram.

Compiler DisplayThe compiler display is where ClearSCADA displays diagnostic


information for your Function Block Diagram. Messages associated with compiling and
debugging are shown here.

PD-6017 07/2012

161

Chapter 6 - Function Block Diagrams

Add Variables to a Function Block Diagram


Each value that is read or written by your Function Block Diagram is represented by a
variable or a constant. Constant values are values that are fixed and are described in Add
a Constant Value to a Function Block Diagram (see page 174). Variable values change
according to the data that is stored in your system and the calculations that are
performed on it.
There are 2 types of variable:

Internal variables are values that are used by the program but are not written to an item
in the database. For example, values that are used in a conversion.

Direct variables are values that are stored in the database, for example, a point value.

The following sections explain how to add variables to your Function Block Diagram:

Add a Direct Variable to a Function Block Diagram (see page 162)

Add an Internal Variable to a Function Block Diagram (see page 167).

Add a Direct Variable to a Function Block Diagram


The method that you use to add a direct variable to your Function Block Diagram will vary
depending on whether the diagram already contains an instance of the value.
If your diagram does not already contain an instance of the direct variable that you want
to add, refer to Add the First Instance of a Direct Variable to a Function Block Diagram
(see page 163).
If your diagram already contains an instance of the direct variable that you want to add,
refer to Add Another Instance of a Direct Variable to a Function Block Diagram (see page
165).

162

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add the First Instance of a Direct Variable to a Function Block Diagram


To add the first or only instance of a direct variable to a Function Block Diagram:
1.

In the Database Bar, select the database item that represents the direct variable that
you want to add to the Function Block Diagram. For example, if you want to add the
value of a point named 'INT 1', select the 'INT 1' point item. When you select the item,
keep the left-hand mouse button pressed down.

2.

With the left-hand mouse button still pressed down, drag the item onto the Function
Block Diagram display.
The Add Direct Variable window is displayed.

3.

Use the Add Direct Variable window to define the settings for the direct variable:

NameEnter the name for the direct variable. This name will be used to refer to the
variable within the program. A name is entered automatically when you drag a direct
variable onto the Function Block Diagram, but you can change it as required.

Tag TypeChoose the type of direct variable tag. This can be:

Read/Write (%M)The Function Block Diagram can both read the value and
overwrite it with a new value.

Read Only (%I)The Function Block Diagram can only read the value and
cannot change it.

Write Only (%Q)The Function Block Diagram cannot read the variable but
can write a new value to it.

TagThis is the name of the OPC property that represents the variable that you
want to add to the Function Block Diagram. The tag can be an OPC tag (for normal,
direct variable values) or an OPC Historic tag (see Add Processed Historic Values to
Function Block Diagrams, on page 169).

TypeChoose the type of value. The value type needs to be appropriate to the
value that is represented by the selected tag. For more information, please refer to
Built-In Data Types (see page 63).

InsertChoose the type of variable tag that you are adding to the Function Block
Diagram. Choose the required type of variable from the combo box (see Function
Block Diagram Components, on page 159).

RetainedThe Retained feature is designed to be used with internal variables.


When selected, it allows the internal variable to be stored and transferred to other
servers (in a multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

PD-6017 07/2012

163

Chapter 6 - Function Block Diagrams

No CacheUse the No Cache check box to determine whether the program uses
the latest value or the initial value for a variable on each execution. If you check the
No Cache check box, the program will use the latest value for the variable rather
than the default value. If you clear the No Cache check box, the program will use
the default value for the variable on each execution.
The No Cache feature is especially useful with variables that are used as counts.
For more information on the No Cache feature, please refer to Using VAR
NOCACHE to Prevent Cached Values Being Used in an ST Program (see page 46).

4.

Select the OK button to confirm.

A direct variable tag is added to the Function Block Diagram. You can then draw
connections to or from it (see Controlling the Flow of a Function Block Diagram, on
page 180).
If you need to add another instance of the direct variable to your Function Block Diagram,
see Add Another Instance of a Direct Variable to a Function Block Diagram, on page 165.

164

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add Another Instance of a Direct Variable to a Function Block Diagram


You need to use the Variables list to add multiple instances of the same direct variable to
a Function Block Diagram. You can add the first instance of the direct variable by
dragging the corresponding database item from the Database Bar onto the Function
Block Diagram and then configuring the variable settings. For subsequent instances of
the direct variable, you need to use the Add option that is available from the Direct tab of
the Variables list:
1.

In the Variables list (above the Function Block Diagram Display), select the Direct tab.

A list of the Ladder Diagram's direct variables is shown.


2.

Right-click on the direct variable that you want to use again.

A context sensitive menu is displayed.


3.

Select the Add option.

The Add Direct Variable window is displayed.


4.

Use the Add Direct Variable window to define the new instance of the variable:

Enter a Name for the direct variable. The name has to be unique. It cannot have the
same name as any variables that are already included in the Function Block
Diagram.

Use the Tag Type combo box to define whether the variable is Read Only, Write
Only, or Read/Write.

Use the browse button feature of the Tag field to select the database property that
is the source of the variable's value. The tag can be an OPC tag (for normal, direct
variable values) or an OPC Historic tag (see Add Processed Historic Values to
Function Block Diagrams, on page 169).

Use the Type combo box to choose the type of value. The value type needs to be
appropriate to the value that is represented by the selected tag. For more
information, please refer to Built-In Data Types (see page 63).

The Retained feature is designed to be used with internal variables. When selected,
it allows the internal variable to be stored and transferred to other servers (in a
multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

PD-6017 07/2012

165

Chapter 6 - Function Block Diagrams

Use the No Cache check box to determine whether the program uses the latest
value or the initial value for a variable on each execution. If you check the No Cache
check box, the program will use the latest value for the variable rather than the
default value. If you clear the No Cache check box, the program will use the default
value for the variable on each execution.
The No Cache feature is especially useful with variables that are used as counts.
For more information on the No Cache feature, please refer to Using VAR
NOCACHE to Prevent Cached Values Being Used in an ST Program (see page 46).

5.

Select the OK button to confirm your selection.

The Add Direct Variable window is closed.


6.

Select the new variable in the Variables list. Keep the left-hand mouse button pressed
down.

7.

Drag the new variable from the Variables list onto the Function Block Diagram.

A context sensitive menu is displayed.


8.

Select the option that corresponds with the type of variable that you are adding to the
Function Block Diagram (see Function Block Diagram Components, on page 159).

A new variable is added to the Function Block Diagram, depending on the option you
selected.

166

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add an Internal Variable to a Function Block Diagram


Internal variables are values that are used by the program but are not written to an item in
the database. They are used for:

Conversions

Separating long, complex calculations into smaller sets of calculations

Storing program states.

To add an internal variable to a Function Block Diagram:


1.

On the Function Block Diagram display, select the Internal tab on the Variables list.

2.

Right-click in an empty row on the Variables list to display a context sensitive menu.

3.

Select the Add option to display the Add Internal Variable window.

4.

Use the Add Internal Variable window to define the settings for the internal variable:

PD-6017 07/2012

Enter a Name for the direct variable. The name has to be unique. It cannot have the
same name as any variables that are already included in the Function Block
Diagram.

Use the Type combo box to choose the type of value. The value type needs to be
appropriate to the internal variable. For more information, please refer to Built-In
Data Types (see page 63).

In the Initial Value field, enter the default value for the internal variable. This is the
first value of the internal variable. The internal variable will reset to this value for
each execution of the Ladder Diagram executes unless the Retained feature is used
(see below).

Use the Retained check box to determine whether the internal variable is stored
and transferred to other servers. For more information on the Retain feature, see
Using the RETAIN Keyword in an ST Program, on page 42.

Check the Retained check box to allows the internal variable to be stored and
transferred to other servers (in a multi-server setup).

Clear the Retained check box to prevent the internal variable from being stored
and transferred to other servers. This will result in the internal variable being
reset to its initial value each time the Function Block Diagram executes.

167

Chapter 6 - Function Block Diagrams

5.

Select the OK button to confirm the settings and close the Add Internal Variable
window.

6.

Select the internal variable in the Variables list. Keep the left-hand mouse button
pressed down.

7.

Drag the internal variable from the Variables list onto the Function Block Diagram.

A context sensitive menu is displayed.


8.

Select the option that corresponds with the type of internal variable that you are adding
to the Function Block Diagram (see Function Block Diagram Components, on page
159).

A new variable item is added to the Function Block Diagram.

168

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add Processed Historic Values to Function Block Diagrams


You can add processed historic values (historic values that have been calculated using a
historic algorithm) to your Function Block Diagrams. This may be useful if you need to use
a daily average or some other calculated value as part of the Function Block Diagram
Logic.
To add a processed historic value to a Function Block Diagram:
1.

Display the Add Direct Variable window by performing one of these procedures:
Either:
i.

In the Variables list (above the Function Block Diagram display), select the Direct
tab.

A list of the Function Block Diagram's direct variables is shown.


ii. Right-click on the direct variable that you want to use again.

A context sensitive menu is displayed.


iii. Select the Add option.

The Add Direct Variable window is displayed.


Or:
i.

In the Variables list (above the Function Block Diagram display), select the Direct
tab.

A list of the Function Block Diagram's direct variables is shown.


ii. Right-click on the direct variable that you want to use again.

A context sensitive menu is displayed.


iii. Select the Add option.

The Add Direct Variable window is displayed.


2.

In the Name field, enter a suitable name for the variable.

3.

Use the Tag Type combo box to define whether the variable is Read Only, Write Only, or
Read/Write.

4.

Select the browse button next to the Tag field.

A context sensitive menu is displayed.

PD-6017 07/2012

169

Chapter 6 - Function Block Diagrams

5.

Select the OPC Historic Tag option to display the Select Historic Tag window.

6.

Expand a Root Group folder. Each Root Group folder represents a system.

7.

Expand the group folders until you locate the item that has the required historic data.

This is the item that has the historic data that you want to use as a value on your
Function Block Diagram.

170

8.

Expand the item. A historic icon is shown.

9.

Select the historic icon. This will associate the variable tag with the historic data of the
selected database item.

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

10. Use the check box and combo boxes at the bottom of the Select Historic Tag window
to define the time span and algorithm:

RelativeUse to determine whether a relative or absolute reference is used to


reference the item's historic tag.

Check the check box to use a relative reference to the item's historic tag. The
reference will work as long as the location of the selected database item
remains the same in relation to the Function Block Diagram.

Clear the check box to use an absolute reference. The reference will only work
when the selected database item remains in the current location.

AlgorithmChoose the type of historic algorithm that ClearSCADA uses to process


the historic data .

Start DateChoose or enter the start time for the range of historic values. The
Function Block Diagram can only use historic values that have been recorded after
the selected date.
You can choose from the following default options or you can enter a start time:

MThe time period starts at the beginning of the current minute.

M-1MThe time period starts at the beginning of the previous minute.

HThe time period starts at the beginning of the current hour.

H-1HThe time period starts at the beginning of the previous hour.

DThe time period starts at the beginning of the current day.

D-1DThe time period starts at the beginning of the previous day.

WThe time period starts at the beginning of the current week.

W-1WThe time period starts at the beginning of the previous week.

To enter a start date, simply enter the time in the OPC format. For example, if you
want the start date to be 3 weeks prior to the start of the current week, enter W-3W.

IntervalEnter or choose the duration of the time period. The Function Block
Diagram will only use those historic values that were recorded after the start date
and within the specified interval. For example, if the Start Date is H and the Interval
is 30M, the time period is 30 minutes after the start of the current hour. Any historic
values that were recorded for the item outside of this time period are disregarded.
As with the Start Date, you can choose from the list of default intervals, or you can
enter your own interval in the OPC time format. If you set the interval to 0, the
program cannot be executed.

11. Select the OK button to confirm your selection and close the Select Historic Tag
window.
12. On the Add Direct Variable window, use the Type combo box to choose the type of
value for the historic variable. The type of value that you select has to be appropriate for
the type of database item. For more information, see Built-In Data Types, on page 63.
13. Leave the Retained check box clear. The Retained feature is designed to be used with
internal variables. When selected, it allows the internal variable to be stored and
transferred to other servers (in a multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

PD-6017 07/2012

171

Chapter 6 - Function Block Diagrams

14. Use the No Cache check box to determine whether the program uses the latest value or
the initial value for a variable on each execution. If you check the No Cache check box,
the program will use the latest value for the variable rather than the default value. If you
clear the No Cache check box, the program will use the default value for the variable on
each execution.
The No Cache feature is especially useful with variables that are used as counts. For
more information on the No Cache feature, please refer to Using VAR NOCACHE to
Prevent Cached Values Being Used in an ST Program (see page 46).
15. Select the OK button to confirm your selections and close the Add Direct Variable
window.
16. Select the historic variable in the Variables list (Direct tab). Keep the left-hand mouse
button pressed down.
17. Drag the historic variable from the Variables list onto the Function Block Diagram.

A context sensitive menu is displayed.


18. Select the option that corresponds with the type of internal variable that you are adding
to the Function Block Diagram (see Function Block Diagram Components, on page
159).

A new variable is added to the Function Block Diagram.

172

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add Raw Historic Values to Function Block Diagrams


To use raw historic values in Function Block Diagrams, you will need to have an
appreciation of how historic values are used in ST programs (see Add Raw Historic Values
to Function Block Diagrams, on page 173).
When you add a raw historic value to a Function Block Diagram, you need to enter its
function and arguments as part of the variable tag:
1.

Edit your Function Block Diagram (see Edit an ST Program, on page 32).

2.

In the Database Bar, select the point that has historic data that is to be used in your
Function Block Diagram.

3.

Drag the point onto the Function Block Diagram to display the Add Variable window.

4.

In the Tag field, add the following after the path of the point:
Historic.<historic function> (<arguments required by function>)
Where <historic function> is the name of the historic function that you need to use, and
<arguments required by function> are the times and values needed by the historic
function. For example:
Analog Input.Historic.RawValue ('D-1H', 'H+1H', 0, TRUE)
You have to enter this information manuallyit cannot be selected from a browse list.

5.

Define the other settings for the variable (see Add Variables to a Function Block
Diagram, on page 162).

6.

Select the OK button to confirm.

Further Information
Historic Functions and Arguments: See page 62.

PD-6017 07/2012

173

Chapter 6 - Function Block Diagrams

Add a Constant Value to a Function Block Diagram


Constant values are values that remain the same each time the program executes, such
as pi, time intervals, fixed text string etc. For example, if a program needs a point to
change state after a 2 minute pause, a constant can be used to define the 2 minute time
period. Although the time period does decrease from 120 seconds to 0 seconds as the
program executes, it is still represented by a constant as the time value is 120 seconds
when the program is executed.
To add a constant value to a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select the Add Constant option.

The Set Constant window is displayed.

3.

Enter the Constant value. The value needs to include any code characters. For more
information, see Built-In Data Types, on page 63.

4.

Select the OK button to confirm the entry and close the Set Constant window.

A constant tag is added to the Function Block Diagram. Constant tags are coloured
blue, and can be connected to other parts of the diagram.

NOTE: Unlike internal and direct variables, constants can only be of a certain data type. Each
constant value has to be one of the Built-In Data Types (see page 63).

174

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add a Function to a Function Block Diagram


Functions are single calculations that can be applied to a value. Each function reads an
input, performs a calculation, and outputs the result of the calculation as a value. There
are many types of function (each function type performs a different type of calculation).
Functions are useful for converting values, adding values, etc.
To add a function to a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select the Functions option to display another menu.

3.

Select the option for the type of function that you want to add to the Function Block
Diagram.

A further menu is displayed.

4.

Select the function that you require.

The function is added to the Function Block Diagram.


For more information on the available functions, see Built-In Functions, on page 226.

PD-6017 07/2012

175

Chapter 6 - Function Block Diagrams

Add a Function Block to a Function Block Diagram


Function blocks are blocks of code that define a type of Logic behavior or calculation. You
can use them in your Function Block Diagrams to provide the Logic or calculations that
you require in your program. There are several types of function block available, and you
can also create custom function blocks if required.
To add a function block to a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select the Function Blocks option to display another menu.

3.

Select the option for the type of function block that you want to add to the diagram.

The function block is added to the Function Block Diagram.


For more information on the available function blocks, see Built-In Function Blocks, on
page 319.

176

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add a Conversion to a Function Block Diagram


Conversions are built-in features that convert the data type of one value into a different
data type. For example, the BYTE_TO_BOOL conversion turns a byte value into a boolean
value. Typically, the conversions are needed when an input value of one data type needs
to be converted into another data type for the Logic program to work.
To add a conversion to a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select the Conversions option to display another menu.

3.

Select the option for the data type that you want to convert on the Function Block
Diagram.
A further menu is displayed.

4.

Select the option that describes the type of conversion. For example, to convert a
boolean value into a string value, select the BOOL_TO_STRING option.

The conversion is added to the Function Block Diagram.


For more information on the data types, see Built-In Data Types, on page 63.

PD-6017 07/2012

177

Chapter 6 - Function Block Diagrams

Add a Comment to a Function Block Diagram


When you are designing a Function Block Diagram, you can add comments that can be
read by other users. You can use the comments to add any text, but typically they are
used to explain the purpose of various parts of the diagram.
To add a comment to a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select the Add Comment option to display the add comment window.

3.

Enter your comment.

4.

Select the OK button to confirm your entry and close the Add Comment window.

The comment is added to the Function Block Diagram.

You can move the comment around on the Function Block Diagram in the same way as
other items.
You can edit the comment by double-clicking on itthis will display the Edit Comment
window which works in the same way as the Add Comment window.

178

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Create a Ladder Diagram within a Function Block Diagram


ClearSCADA allows you to use Ladder Diagrams within Function Block Diagrams. This is
useful as it allows you to create Logic sequences that are more appropriate to Ladder
Logic and connect them to the Logic in a Function Block Diagram.
Before you create a Ladder Diagram in a Function Block Diagram, you should familiarize
yourself with the concepts and design of Ladder Logic (see Ladder Diagrams, on page
129).
To create a Ladder Diagram in a Function Block Diagram:
1.

Right-click on the background of the Function Block Diagram.

A context sensitive menu is displayed.


2.

Select one of these options:

Add Left Power RailAdds a left power rail to the diagram. The left power rail is the
source of the values (i.e. needs to be connected to inputs).

Add Right Power RailAdds a right power rail to the diagram. The right power rail
is the result of the Ladder Diagram (i.e. needs to be connected to outputs).

The rail is added to the diagram.

You can add coils and contacts to the diagram and connect them to the rails. This is done
in exactly the same way as when you add contacts and coils to a Ladder Diagram.
You can then connect the rails to other Logic components in your Function Block
Diagram. Connect the rails via the connection boxes on the outside of the rails:

Connect left-hand rails


to your Function Block
Diagram via this
connection box.

PD-6017 07/2012

Connect right-hand rails to your


Function Block Diagram via this
connection box.

179

Chapter 6 - Function Block Diagrams

Controlling the Flow of a Function Block Diagram


When you have added the various conversions, functions, function blocks etc. that form
your Function Block Diagram, you need to make connections. The connections define
how the various components relate to one another.
When making connections, you may need to move items around the diagram. To do this,
simply select the item, then drag it to the required location before releasing the left-hand
mouse button.
For more information on connections, refer to:

Make a Connection on a Function Block Diagram (see page 180)

Add a Connection Block to a Function Block Diagram (see page 181).

Make a Connection on a Function Block Diagram


To make a connection on a Function Block Diagram:
1.

Select a connection box on one of the items you want to connect. Keep the left-hand
mouse button pressed down.

2.

Drag the cursor to a connection box on the other item (the item to which you are
connecting the item in step 1).

3.

Release the left-hand mouse button.

A connection line is drawn (if the connection is valid).


If the connection lines on your Function Block Diagram are cluttered and overlap, you can
reposition them manually. To do this, simply double-click on the line you want to
reposition. This will cause a new connection box to appear on the line. You can then drag
the selection box to a different, more appropriate position as required.

Double-click on a connection line to add a connection box. You can then drag the connection
box to reposition the entire line. You can add further connection boxes by double-clicking on
the line between any of the existing connection boxes.

180

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Add a Connection Block to a Function Block Diagram


You can use connection blocks to group multiple connection lines. The connection blocks
work in a similar way to the OR function blockif any of the inputs from the connection
block are true, the output of the connection block is true. Connection blocks are designed
to reduce the clutter on your Logic diagrams.
To add a connection block to a Function Block Diagram:
1.

Right-click on the background of the diagram to display a context sensitive menu.

2.

Select the Add Connection Block option.

A new connection block is added to the diagram.

You can connect single or multiple connection lines to the input and output connection
boxes on the connection block. The system will group the lines automatically so that the
lines are clear and the diagram is uncluttered.

Edit a Variable on a Function Block Diagram


You can edit any variable that you have added to your Function Block Diagram. This is
useful when you have made a mistake or when you need to make a small adjustment to
the program.
To edit a variable on a Function Block Diagram:
1.

In the Variables list above the diagram, right-click on the variable you want to edit (on
the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Edit option.

The Edit Direct Variable window or Edit Internal Variable window is displayed,
Depending on which type of variable you selected.
3.

PD-6017 07/2012

Use the Edit Direct Variable window or Edit Internal Variable window to alter the settings
for the variable. The settings work in the same way as on the Add Direct Variable
window and the Add Internal Variable window (see Add Variables to a Function Block
Diagram, on page 162).

181

Chapter 6 - Function Block Diagrams

Rename a Variable on a Function Block Diagram


As you need to allocate a different name to each variable, you may need to rename the
variables you have on your Function Block Diagram.
To rename a variable on a Function Block Diagram:
1.

In the Variables list above the diagram, right-click on the variable you want to rename
(on the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Rename option.

The name of the variable is selected. You can alter or overwrite the name as required
simply use the keyboard to enter the new name for the variable.
3.

182

Press the Enter key or select another part of the interface to confirm the name entry.

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Delete a Variable on a Function Block Diagram


You can use the Delete option to remove unwanted variables from your Function Block
Diagram.
To delete a variable on a diagram:
1.

In the Variables list above the diagram, right-click on the variable you want to delete (on
the Direct tab or Internal tab as appropriate).

A context sensitive menu is displayed.

2.

Select the Delete option.

A confirmation window is displayed.


3.

Select the OK button to confirm the deletion and close the confirmation window.

The variable is removed from the diagram.

PD-6017 07/2012

183

Chapter 6 - Function Block Diagrams

Compiling a Function Block Diagram or Function Block Library


You can use the Build menu options to compile your Function Block Diagram or Function
Block Library (see User Function Blocks, on page 349). The compilation feature is useful
as it checks that your Function Block Diagram has the correct syntax.
There are 2 compile options:

CompileCompiles the diagram. If the diagram is invalid, the compiler display provides
a message that describes the reason for the syntax error. If the syntax is correct, the
compiler displays a success message.

Compile with DiagnosticsCompiles the Function Block Diagram and provides


detailed diagnostic information. As with the Compile option, there are messages for any
errors in the syntax. If the syntax is correct, the compiler displays a success message.
NOTE: The Compile with Diagnostics tool is useful when you want to use a Function
Block Diagram to form the basis of an ST program. For example, you may find it easier
to create a Function Block Diagram and then use the Compile with Diagnostics tool to
access the ST code for the diagram. You can then copy this code into an ST program
(you have to remove the $ signs in the code).

To compile a Function Block Diagram:


1.

Display the Function Block Diagram or Function Block Library in Design mode.

2.

Select the Build menu, then select the Compile option or the Compile with Diagnostics
option as required.

The Function Block Diagram is compiled and the compile messages are shown in the
Compiler display.

Compiler display

If the program is invalid, you will need to alter the Function Block Diagram. Typically, the
causes of syntax errors are minor, such as the wrong type of value being specified or a
missing connection.

184

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Viewing the Variables in your Function Block Diagram


When you display a Function Block Diagram in Run mode, you can view a list of the
variables it uses. The list shows the current values for the variables. The variables window
is useful as it allows you to view the variables that are produced by part of the diagram.
To display the variables window:
1.

Display the Function Block Diagram in Run mode (right-click on it in the Database Bar
then select the Display option).

2.

Select the Run menu, then select the Variables option.

The variables window is displayed.

The variables window contains expandible lists of the variables in your Function Block
Diagram. For each variable, it lists the Name of the variable, the Type (which shows the
data type), and the Value (which shows the current value of the variable).

PD-6017 07/2012

185

Chapter 6 - Function Block Diagrams

Changing the Update Interval for a Function Block Diagram


You can use the Update Interval feature to define how often your ClearSCADA client PC
requests updates for a Function Block Diagram. By default, ClearSCADA clients request
an update from a ClearSCADA server for the latest variable values every second.
By using the Update Interval feature, you can set your ClearSCADA client PC to request
variable updates at a slower rate.
To change the update interval for a Function Block Diagram:
1.

Display the Function Block Diagram in Run mode (right-click on it in the Database Bar
then select the Display option).

2.

Select the Run menu, then select the Update Interval option.

A further menu is displayed.

3.

186

Select the required interval from the list of options. The intervals range from 1 second to
60 seconds.

PD-6017 07/2012

Chapter 6 - Function Block Diagrams

Viewing the Values on a Function Block Diagram


When you display a Function Block Diagram in Run mode, you can view the values at
each stage of the diagram. To display the value at a chosen stage, simply double-click on
the connection line for the value in which you are interestedthe value is shown in a
green box. For example, if you were interested in the value that is coming from an input
variable, just double-click on the connection line between the input variable and the Logic
item to which it connects.

Double-click on the connection line to display the value at


this stage of the Function Block Diagram.

Alternatively, you can right-click on the connection line and select the Display Value
option to display the value.
NOTE: You can only display the values when the Function Block Diagram is displayed in Run
mode.

PD-6017 07/2012

187

Chapter 6 - Function Block Diagrams

188

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

7 Sequential Function Charts

Sequential Function Charts represent a sequence of Logic. They allow you to create a
Logic program that defines system behavior that occurs in steps, depending on specified
conditions.
One of the main advantages of Sequential Function Charts (SFCs) is that only the active
parts of the SFCs are executed, and you can easily see which parts are inactive. This
means it is easy to determine what condition caused a step to occur.
The following sections explain the basic concepts of Sequential Function Charts and
explain how to set up an SFC:

Sequential Function Chart Components (see page 190)

How Sequential Function Charts Work (see page 194)

Simultaneous Sequences (see page 197)

Create a Sequential Function Chart Database Item (see page 200)

Display a Sequential Function Chart (see page 201)

Add Direct and Internal Variables to a Sequential Function Chart (see page 202)

Add a Step to a Sequential Function Chart (see page 204)

Define a Step as the First Step in a Sequential Function Chart (see page 204)

Add a Transition to a Sequential Function Chart (see page 205)

Edit a Transition (see page 206)

Display the Actions Window on a Sequential Function Chart (see page 207)

Add an Action to a Sequential Function Chart (see page 208)

Edit an Action on a Sequential Function Chart (see page 209)

Edit an Action Association (see page 210)

Add a Comment to a Sequential Function Chart (see page 213)

Edit a Comment on a Sequential Function Chart (see page 213)

Add a Method Variable to a Sequential Function Chart (see page 214)

Initiate a Method on a Sequential Function Chart (see page 216)

Insert a Breakpoint on a Step in a Sequential Function Chart (see page 218)

Delete Sequential Function Chart Components (see page 218)

Rename Sequential Function Chart Components (see page 218)

Compiling a Sequential Function Chart (see page 219)

Viewing the Variables in your Sequential Function Chart (see page 220)

Changing the Update Interval for a Sequential Function Chart (see page 221).

For information on the properties of the Sequential Function Chart database items, see
Logic Program Properties and Values, on page 359.

PD-6017 07/2012

189

Chapter 7 - Sequential Function Charts

Sequential Function Chart Components


Sequential Function Charts represent a sequence of Logic. The sequence consists of a
collection of the following components:

Steps (see page 190)

Transitions (see page 191)

Actions (see page 191)

Action Associations (see page 192)

Comments (see page 192).

Steps
Each step represents a state that the program is to monitor. For example, a step could
represent a check for the state of a particular point.
The Start step is the initial step. The
second step is CheckLevel.
The CheckLevel step only becomes
active if the condition defined by the
PipeAlarm transition is true.
When the CheckLevel step is active, the
Start step becomes inactive.

The arrangement of the steps in your Sequential Function Chart determines the order in
which the various actions and conditions are read. The system begins with a step that is
marked as being the initial step, and proceeds to the next step via a transition. Transitions
define specific conditions (see Transitions, on page 191). When the system reaches a
step, the step becomes active. The system can only proceed to the next step (or steps) if
the transition between the steps defines a condition that is true. For example, if Step 3 is
active, Step 4 will only become active if the condition for the transition that connects Step
3 to Step 4 is true.
Steps cannot be connected directly to other stepseach step has to be connected to
one or more transitions. However, steps can be connected to Actions (see page 191).
You can associate multiple steps with a single transition. This is useful when you want
several branches of steps and actions to occur at the same time as a result of a specific
condition. For more information, see Simultaneous Sequences, on page 197.

190

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Transitions
Transitions represent a condition such as an item being in a specific state, or a value
being in a specific range. The step that follows the transition is only activated if the
condition defined in the transition is true.
For example, a transition could be configured to represent this condition:
Value>50
When a the value of the point that is associated with the transition is greater than 50, the
condition is truethe step after the transition will become active. If the point's value is
less than 50, the transition's condition is false and the next step will not become active.

Actions
Actions are used to associate a step with a specific response. The response can be
change the state or value of one of the Sequential Function Block's variables, or can be to
initiate a method for any database item. For example, an action can be used to associate
a step with the EnableAlarms method for a point. When the step is active, the action will
initiate the EnableAlarms method for the relevant point.

2 actions associated with a single


'Stop' step.

To use an action on an SFC, you need to use the Actions window to add an action (see
Add an Action to a Sequential Function Chart, on page 208). When you have added an
action, you need to configure it (see Edit an Action on a Sequential Function Chart, on
page 209).
If you are using an action to perform a method, you will need to add a method to the SFC
(see Add a Method Variable to a Sequential Function Chart, on page 214), and then
configure the action to refer to the method (see Initiate a Method on a Sequential Function
Chart, on page 216).
When you use an action on an SFC, you will also need to configure an action association
(see Action Associations, on page 192). The action association defines when the action is
initiated.

PD-6017 07/2012

191

Chapter 7 - Sequential Function Charts

Action Associations
You can configure an action association for each action. The settings for an action
association define:

The type of action and when the action occurs upon becoming active. For example, you
can set an action to only occur once when the action is activated, or you can set an
action to occur repeatedly after a specified time delay. The type of action and time for
the action are defined via the Qualifier and Duration settings on the Edit Action
Association window.

The name for the action. This is the name that is used to reference the action on the
Sequential Function Chart.

Indicator variables. These are text entries that can be displayed next to the action. The
indicator variables are optional and are used to provide information about the
completion of an action.
You can use an indicator variable to display the name(s) of the direct or internal
variables that are affected by an action. This is useful as it allows operators to see
which variables are affected by each action.

Comments
As with the other types of graphical Logic programs, Sequential Function Charts allow
you to add comments. The comments are for annotation purposes and have no effect on
the system. They are useful as they allow you to add textual information for use by
operators (explanations of sections of the SFC, etc.).
Comments are
displayed in green
comment boxes and
can be positioned
anywhere on your
Sequential Function
Charts.

192

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Connections
The components on a Sequential Function Chart (except comments) are connected by
connection lines. These lines connect the connection boxes of steps to those of
transitions, and they also connect steps to actions.
To create a connection line, simply select a connection box, then drag the cursor to
another connection box. When you release the left-hand mouse button, the connection is
drawn.
NOTE: An invalid symbol is displayed in place of the cursor if the connection you are
attempting to make is invalid (for example, if you are trying to connect a step to another
step).

PD-6017 07/2012

193

Chapter 7 - Sequential Function Charts

How Sequential Function Charts Work


Sequential Function Charts depict a sequence of steps. Each step represents a state that
the program is to monitor. For example, a step could represent a check for the state of a
particular point.
Steps cannot be connected directly to other stepseach step has to be connected to
one or more transitions.
Transitions represent a condition such as a point value or state. For example, a transition
could represent the value of an analog point being greater than 50. When a transition's
condition is true, the step before the transition is deactivated and the step that follows the
transition is activated. This allows you to design a flow of Logic.

Typically, the flow starts at the top and proceeds downwards.


However, you can design your SFCs to have a sequence that flows
in any direction.

ClearSCADA begins executing a Sequential Function Chart (SFC) from the step that is
defined as the initial step. When the condition of the transition between the initial step and
the second step is true, the system will proceed to the second step. When the second
steps becomes active, the initial step becomes inactive. Similarly, when the condition for
the transition between the second step and third step is true, the system will proceed to
the third step and the second step becomes inactive. This process continues throughout
the Sequential Function Diagram.
Transitions can be connected to multiple steps. This allows you to create multiple
branches of steps and transitions that work independently and simultaneously (see
Simultaneous Sequences, on page 197).
Steps can be associated with an action. This means that a specified action occurs when
the step becomes active. The configuration for the action includes ST code that defines
the result of the action, for example, Value:=TRUE; could be used to set a variable named
Value to state 1 (True).
Actions can also be configured to reference method variables. The method variables are
associated with a specific method, such as Enable Alarms or Override, and a specific
database item. If an action references a method, the action will cause that method to be
performed on the database item that is associated with the method when the action
becomes active. For example, if an action references a method named Alarms, the Alarms
method will be performed when the action becomes active. The configuration of the
method associates the method with a database item and a specific method for that item.

194

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Example:
The following SFC shows how the sequence can be structured from top to bottom:

1.

S1 is step 1. The system begins executing the SFC from this step.

2.

If the condition for the DoReset transition is true, the S1 step is deactivated and the
Check step is activated.

3.

If the TRUE transition has a condition that is true, the Check step is deactivated and the
OpenTP step is activated.

4.

If the OpenTP step is activated, the DoOpenTP action is performed. The configuration
for the action defines what happens when the action is performedit could write a
value or state or could execute a method.

5.

If the OpenTP.T variable value is greater than 2 seconds, the OpenTP step is
deactivated and the Close CB step is activated.

PD-6017 07/2012

195

Chapter 7 - Sequential Function Charts

6.

If the CloseCB step is activated, the DoCloseCB action is performed.

7.

If the CloseCB.T variable value is greater than 2 seconds, the CloseCB step is
deactivated and the Close MP step is activated.

8.

If the CloseMP step is activated, the DoCloseMP action is performed.

9.

If the CloseMP.T variable value is greater than 2 seconds, the CloseMP step is
deactivated and the S6 step is activated.

10. If the S6 step is activated, the ResetAll action is performed.


11. If the condition for the transition that follows S6 is true, the whole sequence repeats
itself, starting from S1.

196

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Simultaneous Sequences
In How Sequential Function Charts Work (see page 194), we explained the basic
principles of a Sequential Function Chart. However, the SFC in the example only had a
single branch (or path). You can connect multiple steps to a transition so that there are
multiple brancheseach branch is independent of the other branches but is executed at
the same time. This allows you to create an SFC that has several processes that occur
simultaneously as a result of a specific condition.
To create simultaneous sequences, simply create steps and transitions in the same way
as you would for a single branched sequence, then connect the first steps of the
simultaneous branches to the transition. When the selected transition is true, the
simultaneous branches will occur at the same time.
You can bring the simultaneous branches back into a single sequence by connecting the
final steps in the branches to a single transition that occurs after the branches.
Example:
The following Sequential Function Chart shows a basic program that could be used to
control a drain and pump when there is a high level of fluid in a pipeline:

PD-6017 07/2012

197

Chapter 7 - Sequential Function Charts

The sequence begins with the Start step, and the first condition that has to be met is that
the PipeAlarm transition has to be true. The PipeAlarm transition corresponds to the state
of a point that monitors the alarm status of the pipe. So, if ClearSCADA detects an alarm
condition at the pipe, the Start step is deactivated and the next step (CheckLevel) is
activated.
For the CheckLevel step, the system checks the value of a point that monitors the level of
fluid in the pipe. The transition defines that the next steps (CheckFlow and OpenDrain) will
only be executed if the value for the level is higher than 70.
If the level is higher than 70, the system executes the next steps simultaneously. The
OpenDrain step and its sub-steps are executed at the same time as the CheckFlow step
and its sub-steps. The conditions in the two paths are independentthe OpenDrain
sub-steps and transitions are not affected by the CheckFlow sub-steps and transitions
and vice-versa.

The steps after the Level>70


transition occur at the same
time.

When the OpenDrain step is active, it triggers the Drain action. The Drain action has been
configured on the Actions window for the SFC to change the state of a point. The point is
used to control a drain cover in the pipewhen the point is in state 0, the drain is closed;
when it is in state 1, the drain is open. The qualifier of the Drain action association defines
that the action only occurs once, when the action first becomes active.
When the Drain action has been executed, this branch of the SFC will continue with the
Level<50 transition. However, the Level<50 transition will only be performed if the Drain
action has been executed and the CheckLevelAgain step in the CheckFlow branch of the
SFC is active. The branches that occur simultaneously have to be complete so that their
last step is active before the next transition (Level<50) becomes active.
When the CheckFlow step is active, the system checks for another condition (defined by
the Flow<25 and Flow>25 transitions). If the value of the Flow point is less than 25, the
system proceeds to the PumpOn step. If the value is more than 25, the system will
proceeds to the CheckLevelAgain (as the OpenDrain step is also occurring, and there is a
flow in the pipe, the fluid level will drop eventually).

198

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

When the PumpOn step is active, it triggers the Pump action. The Pump action has been
configured on the Actions window for the SFC to change the state of a point. The point is
used to turn a pump on and offwhen the point is in state 0, the pump is off; when it is in
state 1, the pump is on. The qualifier of the Pump action association defines that the
action only occurs once, when the action first becomes active.
When the pump is turned on, the flow of fluid in the pipe will increase. This is also aided
by the open drain (the drain is opened at the same time as the CheckFlow step). So, the
next part of this branch is to determine whether the flow is greater than 25 (Flow>25).

When the flow is greater than 25, the CheckLevelAgain step becomes active. If the Drain
action has been executed and the CheckLevelAgain step is active, the system will
proceed to the Level<50 transition.
If the level is lower than 50, the amount of fluid in the pipe is normal and so the SFC can
be stoppedthe system proceeds to the Stop step and performs the CloseDrain action
and the StopPump action.

If the level is higher than 50, the drain remains open and the pump remains on. They will
only be closed and turned off when the level drops below 50.

PD-6017 07/2012

199

Chapter 7 - Sequential Function Charts

Create a Sequential Function Chart Database Item


Each Sequential Function Chart needs to be represented in the ClearSCADA database by
a Sequential Function Chart item. When you have created a Sequential Function Chart
item, you can access its Edit feature which allows you to create the Sequential Function
Chart program.
To create a Sequential Function Chart database item:
1.

In the Database Bar, right-click on a system, Group, or Group Template to display a


context sensitive menu.

2.

Select the New option, then the Logic option, then the Sequential Function Chart option
from the context sensitive menu.

A new Sequential Function Chart item is added to the system, Group, or Group
Template. It is selected automatically, ready for you to enter its name.
3.

Enter a suitable name for the Sequential Function Chart then press the Enter key or
select another part of the interface.

Sequential Function Chart database item


(shown in a Group).

Now that you have created a Sequential Function Chart database item, you can display it
and edit it as required.

200

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Display a Sequential Function Chart


You can display an SFC in Design mode or Run mode. In Design mode you can create
and edit the program, whereas in Run mode, you can interact with the program in the
same way that an operator (i./e. you cannot edit the program).

To display an SFC in Run mode:


i.

In the Database Bar, right-click on the SFC that you want to display.

A context sensitive menu is displayed.


ii. Select the Display option.

To display an SFC in Design mode:


i.

In the Database Bar, right-click on the SFC that you want to display.

A context sensitive menu is displayed.


ii. Select the Edit option.

The grid is shown when


the SFC is in Design
mode.

You can also toggle between Run mode and Design mode by selecting and de-selecting
the Design mode button.
Mimics can also be configured to contain links to Logic displays such as SFCs.

PD-6017 07/2012

201

Chapter 7 - Sequential Function Charts

Add Direct and Internal Variables to a Sequential Function Chart


You need to add variables to your Sequential Function Charts. There are 3 types of
variable:

Internal variables represent values that are not stored in the ClearSCADA database.
Internal variables are used for calculations etc. within the SFC.

Direct variables represent values that are stored in the ClearSCADA database. Direct
variables are used for the SFC's inputs and outputs.

Method variables represent method actions such as Override and Enable Alarms (see
Add a Method Variable to a Sequential Function Chart, on page 214).

In this section, we explain how to add a direct variable and an internal variable:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Either:
i.

Right-click in a row on the Direct tab or the Internal tab (as appropriate) to display a
context sensitive menu.

ii. Select the Add option to display the Add Direct Variable window or the Add Internal
Variable window.
Or:
i.

In the Database Bar, select the database item that has the direct variable that you
want to add to the SFC. Keep the left-hand mouse button pressed.

ii. Drag the database item onto the SFC. Release the left-hand mouse button to
display the Add Direct Variable window.
3.

202

Use the Add Direct Variable window or Add Internal Variable window to define the
settings for the new variable. The windows contain a selection of these settings (the
settings vary according to whether the variable is direct or internal):

NameEnter the name for the variable. This name will be used to refer to the
variable within the program. A name is entered automatically when you drag a
variable onto the Sequential Function Chart, but you can change it as required.

Tag TypeChoose the type of variable tag. This can be:

Read/Write (%M)The Sequential Function Chart can both read the value and
overwrite it with a new value.

Read Only (%I)The Sequential Function Chart can only read the value and
cannot change it.

Write Only (%Q)The Sequential Function Chart cannot read the variable but
can write a new value to it.

TagThis is the name of the OPC property that represents the variable that you
want to add to the Sequential Function Chart.

TypeChoose the type of value. The value type needs to be appropriate to the
value that is represented by the selected tag (see Built-In Data Types, on page 63).

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

InsertChoose the type of variable tag that you are adding to the Sequential
Function Chart. Choose the required type of variable from the combo-box (see
Sequential Function Chart Components, on page 190).

RetainedThe Retained feature is designed to be used with internal variables.


When selected, it allows the internal variable to be stored and transferred to other
servers (in a multi-server setup).
For more information on the Retain feature, see Using the RETAIN Keyword in an ST
Program, on page 42.

No CacheUse the No Cache check box to determine whether the program uses
the latest value or the initial value for a variable on each execution. If you check the
No Cache check box, the program will use the latest value for the variable rather
than the default value. If you clear the No Cache check box, the program will use
the default value for the variable on each execution.
The No Cache feature is especially useful with variables that are used as counts.
For more information on the No Cache feature, please refer to Using VAR
NOCACHE to Prevent Cached Values Being Used in an ST Program (see page 46).

4.

Select the OK button to confirm the selections and close the Add Direct Variable or Add
Internal Variable window.

The new variable is added to the SFCit is listed on the Direct or Internal tab (as
appropriate).
You can now reference the direct or internal variable in the conditions for the transitions
and in the ST code for any actions.

PD-6017 07/2012

203

Chapter 7 - Sequential Function Charts

Add a Step to a Sequential Function Chart


Steps represent states that the program is to monitor. For example, a step could
represent a check for value of a specific point. For more information, see Steps, on page
190.
A step is only performed if it is active. It becomes active when the condition for the
transition that connects it to the previous step is true. The initial step does not have a
transition to a previous stepit is performed whenever the system executes the
Sequential Function Chart.
A step becomes inactive when the condition for the transition that connects the step to
the next step is true.
To add a step to an SFC:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Right-click on the background of the SFC.

A context sensitive menu is displayed.


3.

Select the Add Step option.

A new step is added to the SFC.

Define a Step as the First Step in a Sequential Function Chart


You need to define a step as the initial step so that the Sequential Function Chart (SFC)
can determine which step it needs to perform first. To do this, you have to use the Initial
Step feature.
To define a step as the first step in an SFC:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Right-click on the step that is to be the first step in the SFC.

A context sensitive menu is displayed.


3.

Select the Initial Step option.

The step is set to be the first step. Two vertical lines are added to the step to indicate it
is the first step in a sequence

204

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Add a Transition to a Sequential Function Chart


Transitions represent a condition such as an item being in a specific state, or a value
being in a specific range. The step that follows the transition is only activated if the
condition defined in the transition is true.
For more information, see Transitions, on page 191.
To add a transition to a Sequential Function Chart:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Right-click on the background of the SFC.

A context sensitive menu is displayed.


3.

Select the Add Transition option.

The transition is added to the SFC

You can edit the transition by right-clicking on it and selecting the Edit option from the
context sensitive menu (see Edit a Transition, on page 206).

PD-6017 07/2012

205

Chapter 7 - Sequential Function Charts

Edit a Transition
When you add a transition to a Sequential Function Chart (SFC), you need to edit it so that
it has a condition. The next step on the SFC will only become active if the transition's
condition is true.
The condition that you enter should be similar to the conditions for IF statements in ST.
For example, if the condition is only to be true when a variable named Level has a value
greater than 10, the condition would be:
Level>10

To edit a transition:
1.

On the Sequential Function Chart, right-click on the transition that you want to
configure.

A context sensitive menu is displayed.


2.

Select the Edit option to display the Edit Transition window.

3.

Enter a new condition for the transition. The condition should be an ST expression of
the type that would be entered in an IF statement. For example, PumpValue:=10 would
mean the transition is true if the variable named PumpValue has a value of 10.

4.

Select the OK button to confirm the entry and close the Edit Transition window.

Further Information
Transitions (see page 191).
IF - THEN - ELSE (see page 100).

206

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Display the Actions Window on a Sequential Function Chart


You should display the Actions window on a Sequential Function Chart if you need to:

Add an action to your SFC

View the actions that are already on your SFC

Edit an action on your SFC.

To display the Actions window:


1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Either:
i.

Select the Edit menu.

ii. Select the Actions option.


Or:
i.

Right-click on the background of the SFC.

A context sensitive menu is displayed.


ii. Select the Actions option.

The Actions window is displayed.

The Actions window contains a list of the actions that have been created for use in the
SFC program. The names of each action are listed under the Name column, and the
Type column indicates the Logic language that the system uses to identify and perform
the relevant action.
You can use the Actions window to add new actions, edit actions, rename actions, and
delete actions.

PD-6017 07/2012

207

Chapter 7 - Sequential Function Charts

Add an Action to a Sequential Function Chart


You need to add an action to your Sequential Function Chart for each action that is
performed by the program, for example, for each output that writes a value to a point.
To add an action to an SFC:
1.

Display the Actions Window on a Sequential Function Chart (see page 207).

2.

Right-click on a row in the Actions window.

A context sensitive menu is displayed.


3.

Select the Add option.

The Add Action window is displayed.

4.

Enter the name for the new action. We recommend that you enter a name that indicates
the purpose of the action.

5.

Select the OK button to confirm the entry. The Add Action window is closed and the
action is added to the list in the Action window.

6.

Select the action in the Actions window. Keep the left-hand mouse button pressed
down.

7.

Drag the action onto a Step or Action that is to be associated with the action on the
SFC, then release the left-hand mouse button.

The action is added to the SFC.


You can define the configuration of the action by right-clicking on it and selecting the Edit
option from the context sensitive menu (see Edit an Action on a Sequential Function
Chart, on page 209).

208

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Edit an Action on a Sequential Function Chart


You need to edit each action that you add to a Sequential Function Chart (SFC). By
editing an action, you can associate it with a ClearSCADA action such as a control.
Alternatively, you can enter any Structured Text code so that the action runs a Logic
program.
To edit an action on an SFC:
1.

Right-click on an action in the Actions window.

A context sensitive menu is displayed.


2.

Select the Edit option.

The Action Program window is displayed.

3.

Enter the ST code for the action. For more information on ST, see ST Programs, on
page 29.
Common codes for actions include setting a point value or point state. For example,
PumpState :=True; sets an action to change the state of a variable named PumpState
to state 1 (True).

When you have configured an action, you will need to configure an action association (see
Edit an Action Association, on page 210). The action association configuration defines the
type of action and when the action occurs.

PD-6017 07/2012

209

Chapter 7 - Sequential Function Charts

Edit an Action Association


When you have added an action to your SFC, you need to configure an action
association. The settings in the action configuration define when the action takes place,
and whether it is repeated, works as a pulse etc.
The action association configuration also allows you to create indicator variables for your
actions. These are indicators that can be shown on the SFC to show operators which
variables are affected by an action.
To configure an action association:
1.

On the Sequential Function Chart, right-click on the action that you want to configure.
A context sensitive menu is displayed.
NOTE: You have to right-click on the action on the SFCif you right-click on the action
in the Actions window, a different context sensitive menu is displayed.

2.

Select the Edit option to display the Edit Action Association window.

Use the Qualifier combo-box to define when the action is to be performed. The available
options include:

NThe action is executed repeatedly while the step is active. This means that the
action will occur again and again until the program proceeds to the next step in the
sequence.

RThe action resets another instance of the same action. This is used in
conjunction with actions that use an S qualifier.
Actions that use an S qualifier are executed repeatedly until they are reset. They are
reset when another instance of the same action is executed (the other instance of
the action has to have an R qualifier).

210

SActions that use an S qualifier are executed repeatedly until they are reset. They
are reset by an action with an R qualifier (see above).

PThe action is a pulse action. It is executed once when the step is first activated
and then once again when the step is deactivated.

P0The action is a pulse action. It is executed once when the step is deactivated.

P1The action is a pulse action. It is executed once when the step is first
activated.

LThe action is time limited. It executes repeatedly for a defined time period.

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

DThe action is time delayed. It is executed after a defined time period has
passed.

SDThe action is stored and time delayed. The action is executed repeatedly after
a defined time period has expired. The action is executed even if the associated
step is deactivated before the start of the time period.

DSThe action is time delayed and stored. The action is executed repeatedly after
a defined time period has expired. The action is not executed if the associated step
is deactivated before the start of the time period.

SLThe action is time limited and stored. The action is executed repeatedly for
defined time period.

3.

Use the Duration field to define the time period for time delayed and time limited
qualifiers. You have to enter the time period in the OPC time format, for example, T#30s
for 30 seconds.

4.

Use the Name field to define a name for the action association. The name has to be
exactly the same as the name of the action that the action association affects. For
example, if an action named PowerOff is used to write a value to a point that controls
the power supply, the action association for that action also has to be named PowerOff.

5.

Use the Indicator Variables section to define any indicators. The indicator variables are
optional and are used to provide information about the completion of an action.
You can use an indicator variable to display the name(s) of the direct or internal
variables that are affected by an action. This is useful as it allows operators to see
which variables are affected by each action. For example, if a Stop action affects the
state of a 'PowerStatus' variable, an indicator variable could be used to show
'PowerStatus' next to the Stop action on the SFC.

Qualifier

Action

Indicator Variable

To create an indicator variable:


i.

Select the Add button on the Edit Action Association window to display the Add
Variable window.

ii. In the Add Variable window, enter the name of a variable that is affected by the
action with which the indicator variable will be associated. The name has to be
identical to the name of the selected variable. For example, if a Start action affects a
RunState direct variable, the indicator variable for the Start action also has to be
named RunState.
iii. Select the OK button or press the Enter key to confirm the name.

PD-6017 07/2012

211

Chapter 7 - Sequential Function Charts

If an action affects more than one variable, you can add more indicator variables by
repeating steps i-iii inclusive. The additional indicator variables will be listed after the
first indicator variable in comma separated format.
You can rename an indicator variable, by selecting an indicator variable in the list, then
selecting the Rename button. You can then enter a new name for the indicator variable.
You can also remove an indicator variable by selecting an indicator variable in the list,
then selecting the Delete button.
4.

Select the OK button to confirm your selections.

The Edit Action Association window is closed and the action association is configured
according to your selections.

212

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Add a Comment to a Sequential Function Chart


You can add comments to your Sequential Function Charts. The comments have no effect
on the way an SFC works, but they can be used to provide information to other users. For
example, you can add a comment that explains what happens when a certain action is
performed.
To add a comment to an SFC:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Right-click on the background of the SFC.

A context sensitive menu is displayed.


3.

Select the Add Comment option.

The Add Comment window is displayed.

4.

Enter the required comment. (Overwrite the default entry of <<comment>>).

5.

Select the OK button to confirm your entry and close the Add Comment window.

The comment is added to the SFC. It will be visible to the users that access the SFC.

Edit a Comment on a Sequential Function Chart


You can alter a comment that has been added to a Sequential Function Chart by
right-clicking on the comment and selecting the Edit option from the context sensitive
menu. This displays the Edit Comment window which you can use in the same way as the
Add Comment window (see Add a Comment to a Sequential Function Chart, on page
213).

PD-6017 07/2012

213

Chapter 7 - Sequential Function Charts

Add a Method Variable to a Sequential Function Chart


If your Sequential Function Chart contains actions that are to initiate ClearSCADA
methods (controls such as Override, Enable Alarms etc.), you need to add method
variables.
Each method variable declares a method for use in your Sequential Function Chart (SFC).
The configuration of the method variable corresponds to the METHOD declaration in ST
(see Executing Methods on Database Items, on page 90).
To add a method variable to an SFC:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Select the Method tab.

3.

Right-click in the list on the Method tab to display a context sensitive menu.

4.

Select the Add option to display the Add Method Variable window.

5.

Use the Add Method Variable window to define the settings for the method declaration:

NameEnter the name for the method variable. This is the name that will be used
to reference the variable within the ST code.

ObjectUse the browse button feature to select the database item that has the
method that you want to use. For example, if you want to add the EnableAlarms
method for a point named 'Power', use the browse button feature to select the
'Power' point.

MethodUse the Method combo-box to select the method that you want to add to
the SFC. The list contains the methods that are available for the selected database
item. The Hand Control method is unavailable as it does not work in the same way
as other methods. If you need to write a current value, you should use add a direct
variable and write to it instead.

PrototypeThe Prototype field is only available for methods that set a specific
value, for example, methods that override an analog point so that the point has a
value of 50.
Use the Prototype field to define the type of value(s) that will be written by the
method. The actual values that will be written are defined in the configuration of the
actions that will be associated with the method.
If the Prototype field is available, it will display at least one value type that is
appropriate to the method. Typically, you will not need to change the value type(s). If
you do decide to change them, you need to enter value types that are appropriate
for the type of database item to which the value is written (see Built-In Data Types,
on page 63).

214

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

6.

Select the OK button to confirm your choices.

You can now include the method in the ST code for one of the actions on the SFC (see
Edit an Action on a Sequential Function Chart, on page 209). When you associate the
action with a step, the defined method will be performed when the step takes place (see
Edit an Action Association, on page 210).

PD-6017 07/2012

215

Chapter 7 - Sequential Function Charts

Initiate a Method on a Sequential Function Chart


If you want your Sequential Function Chart to contain a step that initiates a method
(control for a specific item), you need to follow this procedure:
1.

Display the SFC in Design mode (see Display a Sequential Function Chart, on page
201).

2.

Locate the step that you want to associate with the method. If the SFC does not
contain a suitable step, create a step (see Add a Step to a Sequential Function Chart,
on page 204) and link it to the SFC by drawing connection lines.

3.

Add a method variable (see Add a Method Variable to a Sequential Function Chart, on
page 214). You will need to configure the method variable so that it is associated with
the relevant database item and the required method.

4.

Add an action (see Add an Action to a Sequential Function Chart, on page 208). You will
need to configure the action so that it has ST code that it references the method and
defines the value or state that the method will set (where appropriate).

5.

Configure an action association (see Edit an Action Association, on page 210) that
defines when the method will be initiated.
You need to configure the action association so that:

6.

The method configuration defines the correct method and database item that is to
be initiated.

The step is associated with the action that initiates the method.

The action is associated with the correct step, and has ST code that references the
method (and defines any values or states that are set by the method).

The action association defines the correct settings for the action.

Save the SFC.

Example:
A point named 'Valve' is to have its state overridden by a condition on a Sequential Function
Chart (SFC). When the OPENVALVE step of the SFC is reached, the program will cause
ClearSCADA to change the 'Valve' point's state to state 1 (True).
On the SFC, a new step is created. The step is named OPENVALVE.
An action named Override is created. This is the action that will be associated with the
OPENVALVE step.
A new method is created with these settings:

NameValveOverride

Object.Valve

MethodOverride

PrototypeUSINT

The action is configured so that its ST code references the ValueOverride method and
defines the state that is to be set:

216

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

ValueOverride (True);
When the OPENVALVE step takes place, the Override action is initiated.
The Override action causes the 'Valve' point to change to state 1 (True). The configuration of
the 'Valve' point defines that state 1 corresponds to the valve being opened.
The action item on the SFC is connected to the OPENVALVE step.
Finally, an action association is edited so that a ValveOpen indicator variable is shown for the
action, and the qualifier is set to N (the override will repeat automatically when the step is
True).

PD-6017 07/2012

217

Chapter 7 - Sequential Function Charts

Insert a Breakpoint on a Step in a Sequential Function Chart


You can insert a breakpoint on a step so that the Sequential Function Chart only executes
up to the selected stepit does not perform the steps after it. This is useful for testing
that sections of your SFC work correctly (debugging).
To insert a breakpoint on a step in an SFC:
1.

On the SFC, right-click on the step on which you want to insert the breakpoint.

A context sensitive menu is displayed.


2.

Select the Insert Breakpoint option.

A breakpoint is set on the step. A red dot appears on the step to indicate that a
breakpoint has been inserted.

The program will only execute up to the selected step.


To cancel the breakpoint, right-click on the step to display a context sensitive menu, then
select:

Remove BreakpointDeletes the breakpoint.

Disable BreakpointLeaves the breakpoint in place, but disables it so that the


program can execute beyond the selected step.

Delete Sequential Function Chart Components


You can delete steps, transitions, comments, variables and actions by right-clicking on
the relevant item on the SFC, Direct tab, Indirect tab, Methods tab, or in the Actions
window, then selecting the Delete option from the context sensitive menu.

Rename Sequential Function Chart Components


You can rename steps, transitions, and actions by right-clicking on the relevant item on
the SFC, Direct tab, Indirect tab, Methods tab, or in the Actions window, then selecting
the Rename option from the context sensitive menu. To rename the item, simply enter a
new name that overwrites the existing name, then press the Enter key or select another
part of the interface to confirm your selection.

218

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Compiling a Sequential Function Chart


You can use the Build menu options to compile your Sequential Function Chart (SFC). The
compilation feature is useful as it checks that your Sequential Function Chart has the
correct syntax.
There are 2 compile options:

CompileCompiles the chart. If the chart is invalid, the compiler display provides an
message with a brief explanation of the cause of the syntax error. If the syntax is
correct, the compiler displays a success message.

Compile with DiagnosticsCompiles the SFC and provides detailed diagnostic


information. As with the Compile option, there are messages for any errors in the
syntax. If the syntax is correct, the compiler displays a success message.

To compile a Sequential Function Chart:


1.

Display the Sequential Function Chart in Design mode.

2.

Select the Build menu, then select the Compile option or the Compile with Diagnostics
option as required.

The Sequential Function Chart is compiled and the compile messages are shown in the
Compiler display.

Compiler display

If the chart has invalid syntax, you will need to alter the SFC. Typically, the causes of
errors are minor, such as the wrong type of value being specified or a missing connection.

PD-6017 07/2012

219

Chapter 7 - Sequential Function Charts

Viewing the Variables in your Sequential Function Chart


When you display a Sequential Function Chart in Run mode, you can view a list of the
variables it uses. The list shows the current values for the variables. The variables window
is useful as it allows you to view the variables that are produced by part of the chart.
To display the variables window:
1.

Display the Sequential Function Chart in Run mode (right-click on it in the Database Bar
then select the Display option).

2.

Select the Debug menu, then select the Variables option.

The variables window is displayed.

The variables window contains expandible lists of the variables in your Ladder Diagram.
For each variable, it lists the Name of the variable, the Type (which shows the data type),
and the Value (which shows the current value of the variable).

220

PD-6017 07/2012

Chapter 7 - Sequential Function Charts

Changing the Update Interval for a Sequential Function Chart


You can use the Update Interval feature to define how often your ClearSCADA client PC
requests updates for a Sequential Function Chart (SFC). By default, ClearSCADA clients
request an update from a ClearSCADA server for the latest variable values every second.
By using the Update Interval feature, you can set your ClearSCADA client PC to request
variable updates at a slower rate.
To change the update interval for an SFC:
1.
2.

Display the Sequential Function Chart in Run mode (right-click on it in the Database Bar
then select the Display option).
Select the Run menu, then select the Update Interval option.

A further menu is displayed.

3.

PD-6017 07/2012

Select the required interval from the list of options. The intervals range from 1 second to
60 seconds.

221

Chapter 7 - Sequential Function Charts

222

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

8 Built-in Functions, Function Blocks, and Conversions

ClearSCADA provides a set of built-in functions, function blocks, and conversions that
you can use in your Logic programs. They provide common industrial control system
functionality and are especially useful on Function Block Diagrams and Ladder Diagrams
as you can add them to your programs via context sensitive menus.
For information on the 'extra' EN and ENO function connections, the built-in functions,
built-in function blocks, and built-in conversions, please refer to the following sections:

Using EN and ENO to Control when a Function is Performed (see page 224)

Built-In Functions (see page 226)

Built-In Function Blocks (see page 319)

Conversions (see page 346).

You can access all of the built-in options from the context sensitive menu that is displayed
when you right-click on the background of a Function Block Diagram or Ladder Diagram.
You can also include them in your ST program code.
Right-click on the
background of a Function
Block Diagram or Ladder
Diagram to display the
context sensitive menu. The
menu provides access to
the built-in functions,
function blocks, and
conversions.
You can only access the
context sensitive menu
when the diagram is
displayed in Design mode.

NOTE: When using functions and function blocks, you need to configure an appropriate
output data type; the output data type has to be suitable for storing the result. If the output
data type is inappropriate, the output may cause an overflow and the value will be
inaccurate. For example, if you set an EXPT function to have constant inputs of 10 and 6, the
result is 64 as the actual result of 100000 is converted to binary and so results in 64. To store
the actual result, the input values have to be converted to DINT or UDINT.

PD-6017 07/2012

223

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Using EN and ENO to Control when a Function is Performed


Functions used in Ladder Diagrams and Function Block Diagrams have an extra input and
output. The extra input is EN and the extra output is ENO:

ENThe EN input represents ENABLED and it is used to control whether the function is
performed. When the EN input is used, the function is only performed if the EN input is
true. For example, if the EN input is used on an ADD function, the output of the ADD
function will only be the sum total of its two normal inputs if its EN input is true. If the EN
input is false, the output of the ADD function will be 0, irrespective of its inputs.
The output of the ADD function is 0, despite the
inputs being 2 and 5. The output is 0 instead of 7 as
the ADD function is not performed due to the
PumpAlarm direct variable being in state 0 (false).
If the PumpAlarm direct variable changes to state 1
(true) the output of the ADD function will be 7 (2+5).

ENOThe ENO output represents ENABLED OUTPUT and it is used to show that a
function has executed successfully. If the ENO value is True, the function has executed
successfully; if the ENO value is False, the function has not executed successfully and
there is an error such as an arithmetic overflow.

You can set a function to be both EN and ENO at the same time. This allows you to
control whether the function is performed and to determine whether it is executed
successfully. By chaining the ENO output of one function to the EN input of another, you
can create a flow of functions that are only executed if the previous function was
successful.
In ST, you can refer to the EN and ENO input and outputs in the same way as other
variables. For example:
VAR_INPUT
EN: BOOL := 0;
END_VAR
VAR_OUTPUT
ENO : BOOL;
END_VAR

224

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Combining Functions with other Functions


You can combine functions so that the outputs of one function are the inputs of another
function. This allows you to create complex Logic programs where the results of one
function affect the results of other functions.
In a Function Block Diagram, you can connect the output of one function to an input of
another function by drawing the connection in the same way as you would connect a tag
to an input.

In an ST Program, you need to declare a function and then include the second function
(and its arguments) as one of the arguments for the first function. For example, to use the
output of a DIV function as one of the inputs for an ADD function, you need to use this
syntax:
Output := ADD (DIV (A, B), C)
Where Output is a variable defined earlier in the program, A and B are the arguments for
the DIV function, and C is the second argument for the ADD function. So the ADD function
uses the output of A/B as Input 1 and C as Input 2:
Output := ADD (DIV (10, 5), 20)
In this case, ADD uses 2 as Input 1 (10/5=2) and 20 as Input 2, so the ADD function
outputs 22.
The only limitation with combining inputs and outputs is that the output from one function
needs to be of the data type that is required by the input of another function. So, if a
function outputs a Boolean value, it can only be used as the input for a function that
requires a Boolean input (unless a conversion is used).

PD-6017 07/2012

225

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Built-In Functions
ClearSCADA provides 9 categories of built-in function:

Arithmetic (see page 226)

Bit String (see page 234)

Bitwise/Boolean (see page 239)

Comparison (see page 244)

Date and Time (see page 251)

Numerical (see page 278)

Selection (see page 291)

String (see page 297)

Misc (see page 310)

Arithmetic
The Arithmetic menu provides access to functions that perform an arithmetic calculation.
They perform arithmetic on the inputs to determine the value of an output.
The following arithmetic options are available:

ADD (see page 227)

DIV (see page 228)

EXPT (see page 229)

MOD (see page 230)

MOVE (see page 231)

MUL (see page 232)

SUB (see page 233).

NOTE: When using arithmetic functions in ST Programs, you should use the available
operators when performing a function on 2 values. For example, Output := Input 1 + Input 2
is more efficient than Output := Add (Input 1, Input 2). However, for functions that have
multiple arguments, you should use the comma separated format, for example, Output :=
Add (Input 1, Input 2, Input 3, Input 4).

226

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ADD
Function Name

ADD

ST Operator

Description

Provides a sum total of the 2 inputs.

Arguments

Input 1 - Input n {ANY_MAGNITUDE}


The ADD function can have 2 or more inputs and these can be of any
type within the ANY_MAGNITUDE category (see Data Type Hierarchy,
on page 392).

Returns

Total {Same type as input}


The total value of the inputs combined (Input 1 + Input 2 + Input 3 and
so on). The type of output is dependent on the inputs.

Examples:
Function Block Diagram - ADD:
The ADD function is used to provide a total of 2 inputs. In this case, Input 1 is 2 and Input 2
is 5. The ADD function returns 7 (2+5=7)

ST Program - ADD:
The ADD function is used to provide the total value of 3 inputs. In this case, Input 1 is 2,
Input 2 is 5, and Input 3 is 17. The ADD function returns 24 (2+5+17=24):
Output := ADD (Input 1, Input 2, Input 3);
Where Output, Input 1, Input 2 and Input 3 are defined as variables earlier in the ST program.
Alternatively, the same calculation can be made by using the following syntax:
Output := Input 1 + Input 2 + Input 3;
Again, where Output, Input 1, Input 2 and Input 3 are defined as variables earlier in the ST
Program.

PD-6017 07/2012

227

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

DIV
Function Name

DIV

ST Operator

Description

The output is the result of Input 1 divided by Input 2. On a Function


Block Diagram, Input 1 is the top input and Input 2 is the bottom
input.

Arguments

Input 1 {ANY_NUM}
Input 2 {ANY_NUM}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {Same data type as Input 1}


The value of Input 1 divided by Input 2. The type of output is
dependent on the inputs.

NOTE: For integer inputs, the output is the same as Input 1 except that the fractional part of
the value is discarded.
Examples:
Function Block Diagram - DIV:
Input 1 is 10 (the top input) and Input 2 is 5 (the bottom input). The output is 5 as 10 divided
by 5 is 2.

ST Program - DIV:
The DIV function is used to provide the result of Input 1 divided by Input 2.
Output := Input 1 / Input 2;
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. In this
case, let's assume Input 1 is 60 and Input 2 is 10. The DIV function returns 6 as 60/10=6.
Alternatively, the same calculation can be made by using the following syntax:
Output := DIV (Input 1, Input 2);

228

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXPT
Function Name

EXPT (Exponential)

ST Operator

**

Description

The output is Input 1 to the power of Input 2. On Function Block


Diagrams, the top input is Input 1 and the bottom input is Input 2.

Arguments

Input 1 {ANY_NUM}
Input 2 {ANY_NUM}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as Input 1}


The Output = Input 1 to the power of Input 2.

Examples:
Function Block Diagram - EXPT:
The output is the top input to the power of the bottom input. So, if the top input is 3 and the
bottom input is 2, the output is 32 (3X3=9).

ST Program - EXPT:
The EXPT function outputs Input 1 to the power of Input 2.
Output := EXPT (Input 1, Input 2);
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. In this
case, let's assume Input 1 is 10 and Input 2 is 6. The Expt function returns 1000000 as
106=1000000.

PD-6017 07/2012

229

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MOD
Function Name

MOD (Modulo)

ST Operator

MOD

Description

The output is the modulo result of a division (the remainder of a


division). For the MOD function, Input 1 is divided by Input 2 and the
remainder is the output. In Function Block Diagrams, Input 1 is the
top input and Input 2 is the bottom input.

Arguments

Input 1 {ANY_INT}
Input 2 {ANY_INT}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {INT}
The Output = The remainder of Input 1 / Input 2

Examples:

Function Block Diagram - MOD:


Input 1 is 5 and Input 2 is 2. This means that the MOD function provides an output of 1 as 5/
2 = 2 with 1 remaining.

ST Program - MOD:
The MOD function outputs the remainder from Input 1 divided by Input 2.
Output := MOD (Input 1, Input 2);
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. In this
case, let's assume Input 1 is 10 and Input 2 is 3. The MOD function returns 1 as 10/3=3 with
1 remaining.

230

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MOVE
Function Name

MOVE

ST Operator

:=

Description

The input is moved to the output. This is especially useful when used
with the EN and ENO expressions as it allows the input to be moved
to the output depending on the state of a boolean input (see Using
EN and ENO to Control when a Function is Performed, on page 224).

Arguments

Input 1 {ANY}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {ANY}
The Output = Input 1

Example:

Function Block Diagram - MOD:


A MOVE function is used to output a specific value when a defined input is True. To achieve
this, an EN expression is used with the MOVE function. The EN expression uses a Boolean
input from a direct input variable (PumpAlarm). The 'normal' input for the MOVE function has
a constant input of 3. When the direct input variable is in State 1 (True), the constant value is
moved to the output (so the output is 3). When the input variable is in State 0 (false), the
output is 0.

In an ST Program there is no need to use a MOVE function as the same result can be
achieved by using an IF-THEN statement.

PD-6017 07/2012

231

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MUL
Function Name

MUL (Multiply)

ST Operator

Description

Multiplies the inputs to provide the output.

Arguments

Input 1 - Input n {ANY_NUM}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {Same data type as input}


The Output = Input 1 x Input 2 x Input 3 and so on.

Examples:
Function Block Diagram - MUL:
The output is the result of the top input multiplied by the bottom input. So, if the top input is
2 and the bottom input is 19, the output is 38 (2 x 19=38).

ST Program - MUL:
The MUL function is used to provide the result of Input 1 divided by Input 2:
Output := Input 1 * Input 2;
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. In this
case, let's assume Input 1 is 60 and Input 2 is 10. The DIV function returns 600 as 60 x
10=600 (the asterisk * represents the MUL function).
When there are more than 2 inputs, it is more efficient to use the following syntax:
Output := MUL (Input 1, Input 2, Input 3, Input 4 and so on);
For example:
Output := MUL (12, 4, 32, 6);
This would return 9126 as this is the result of 12 x 4 x 32 x 6.

232

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB
Function Name

SUB (Subtract)

ST Operator

Description

Outputs the result of Input 1 minus Input 2.

Arguments

Input 1 {ANY_MAGNITUDE}
Input 2 {ANY_MAGNITUDE}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}


The Output = Input 1 - Input 2.

Examples:
Function Block Diagram - SUB:
The output is the result of the top input minus the bottom input. So, if the top input is 7 and
the bottom input is 5, the output is 2 (7-5=2).

ST Program - SUB:
The SUB function is used to provide the result of Input 1 minus Input 2:
Output := Input 1 - Input 2;
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. In this
case, let's assume Input 1 is 17 and Input 2 is 10. The SUB function returns 7 as 17 -10 = 7.
The same effect can be achieved by using the following syntax:
Output := SUB (Input 1, Input 2);

PD-6017 07/2012

233

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Bit String
Bit String functions allow you to manipulate the bits of binary inputs. The Bit String
functions include:

ROL (see page 234)

ROR (see page 236)

SHL (see page 237)

SHR (see page 238).

ROL
Function Name

ROL (Rotate Left)

Description

Rotates each bit n positions to the left. So, rotating by 1 means the
first bit in the string becomes the last bit in the string, the second bit
becomes the new first bit and so on.

Arguments

IN {ANY_BIT}
IN is a bit string.
N {ANY_INT}
N is an integer that defines the number of positions the ROL function
will move the characters.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}


The Output is the number that represents the new binary string.

Examples:
Function Block Diagram - ROL:
The ROL function has two inputs. The top input (IN) is 146 which corresponds to the binary
string of 10010010. The bottom input (N) is 3 which instructs the function to rotate the bits
left by 3 positions. The output is 148 which corresponds to the binary string 10010100. So,
the ROL function has rotated the bits 3 positions to the left:

234

Input String

10010010

Rotation Left x3

10010100

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ST Program - ROL:
The ROL function is used to rotate the positions of the bits in the Input string to the left:
Output := ROL (IN, N);
Where Output, IN and N are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := ROL (IN:= 146, N:= 3);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example).

PD-6017 07/2012

235

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ROR
Function Name

ROR (Rotate Right)

Description

Rotates each bit n positions to the right. So, rotating by 1 means the
first bit in the string becomes the second bit in the string, the second
bit becomes the third bit and so on. The last bit becomes the new first
bit in the string.

Arguments

IN {ANY_BIT}
IN is a bit string.
N {ANY_INT}
N is an integer that defines the number of positions the ROR function
will move the characters.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}


The Output is the number that represents the new binary string.

Examples:
Function Block Diagram - ROR:
The ROR function has two inputs. The top input (IN) is 146 which corresponds to the binary
string of 10010010. The bottom input (N) is 3 which instructs the function to rotate the bits
right by 3 positions. The output is 84 which corresponds to the binary string 10010100.
So, the rotate right function has rotated the bits 3 positions to the right:
Input String

10010010

Rotation Right x3

10100100

The binary string that results from 3 rotations right is 01010010 which corresponds to the
decimal value of 84. So the value of the output is 84.
ST Program - ROR:
The ROR function is used to rotate the positions of the bits in the Input string to the right:
Output := ROR (IN, N);
Where Output, IN, and N are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := ROR (IN:= 146, N:= 3);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example).

236

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SHL
Function Name

SHL (Shift Left)

Description

Moves each bit n positions to the left, losing any characters that are
moved from the start of the string and replacing them with 0s at the
end. So, if the string is shifted 2 positions to the left, the first two bits
are removed and two extra 0s are added to the end of the string to
replace them.

Arguments

IN {ANY_BIT}
Input 1 is a bit string.
N {ANY_INT}
N is an integer that defines the number of positions the SHL function
will move the characters.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}


The Output is the number that represents the new binary string.

Examples:
Function Block Diagram - SHL:
The SHL function has two inputs. The top input (IN) is 146 which corresponds to the binary
string of 10010010. The bottom input (N) is 3 which instructs the function to shift the bits left
by 3 positions. The output is 144 which corresponds to the binary string 10010000.
So, the shift left function has deleted the first 3 bits and added 3 zeros to the end of the
string:
Input String

10010010

Shift Left x3

10010000

The binary string that results from 3 shifts left is 10010000 which corresponds to the decimal
value of 84. So the value of the output is 84.
ST Program - SHL:
The SHL function is used to shift the positions of the bits in the Input string to the left, losing
any characters that are shifted from the start of the string and replacing them with zeros at
the end of the string:
Output := SHL (IN, N);
Where Output, IN, and N are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := SHL (IN:= 146, N:= 3);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example).

PD-6017 07/2012

237

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SHR
Function Name

SHR (Shift Right)

Description

Moves each bit n positions to the right, losing any characters that are
moved from the end of the string and replacing them with 0s at the
start. So, if the string is shifted 2 positions to the right, the last two
bits are removed and two extra 0s are added to the start of the string
to replace them.

Arguments

IN {ANY_BIT}
IN is a bit string.
N {ANY_INT}
N is an integer that defines the number of positions the SHR function
will move the characters.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}


The Output is the number that represents the new binary string.

Examples:
Function Block Diagram - SHR:
The SHR function has two inputs. The top input (IN) is 146 which corresponds to the binary
string of 10010010. The bottom input (N) is 3 which instructs the function to shift the bits
right by 3 positions. The output is 18 which corresponds to the binary string 10010.
So, the shift right function has deleted the last 3 bits and added 3 zeros to the start of the
string:
Input String

10010010

Shift Right x3

00010010

The leading zeros are ignored and so the binary string that results from 3 shifts left is 10010
which corresponds to the decimal value of 18. So the value of the output is 18.
ST Program - SHR:
The SHR function is used to shift the positions of the bits in the Input string to the right,
losing any characters that are shifted from the end of the string and replacing them with
zeros at the start of the string:
Output := SHR (IN, N);
Where Output, IN and N are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := SHR (IN:= 146, N:= 3);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example).

238

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Bitwise/Boolean
The Bitwise/Boolean functions allow you to manipulate boolean values. You can use the
functions to create conditions that affect the flow of the Logic program.
The Bitwise/Boolean functions are used to determine an output based on 2 inputs (except
for the NOT function, which has a single input). The Bitwise/Boolean functions are:

AND (see page 240)

NOT (see page 241)

OR (see page 242)

XOR (see page 243).

For Bitwise, the functions are applied to the inputs. The function is applied to the two
corresponding bits. For example, if the AND function is used with the following inputs:
Input 1: 011011
Input 2: 101101
The result is 001001. This works by applying the AND function to the corresponding bits. So,
as the last two bits on each line are both 1, the result of adding those bits is 1 (true). The last
but one bits on each line are 1 and 0, so the result is 0 (false) as both inputs are not true.

PD-6017 07/2012

239

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

AND
Function Name

AND

Description

Outputs a Boolean value. The output is True if both inputs are true; if
either input is False, the AND function has a False output.

Arguments

Input 1 to Input n {ANY_BIT}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {Same data type as input}


If any of the inputs is False, the output is False. The output is only
True if each of the inputs is True.

Examples:
Function Block Diagram - AND:
A Function Block Diagram has two Boolean inputs: FlowPresent and StopPump. The AND
function only outputs a True value if both the FlowPresent and StopPump values are True. If
either of the input values are False, the AND function outputs a False value.

ST Program - AND:
The AND function is used to provide a Boolean value that is only True if both inputs are True.
The syntax for an AND function in an ST Program is:
Output := AND (Input 1, Input 2);
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Both
Input 1 and Input 2 are Boolean inputs.

240

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

NOT
Function Name

NOT

Description

Outputs the opposite value to the input.

Arguments

Input 1 {BOOL}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {BOOL}
If Input 1 is True, the Output is False
If Input 1 is False, the Output is True.

Examples:
Function Block Diagram - NOT:
An input named 'FlowPresent' provides a Boolean value. When True, it means that a sensor
has detected a flow; when False, the sensor has not detected a flow.
The NOT function returns the opposite value to the input, so if the 'FlowPresent' input is
True, the NOT function returns a False value. If the 'FlowPresent' input is False, the NOT
function returns a True value.

ST Program - NOT:
The NOT function is used to provide a Boolean value that is True if the input is False, and
False if the input is True. The syntax for a NOT function in an ST Program is:
Output := NOT (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. Input 1 is a
Boolean input and Output is also a Boolean value.

PD-6017 07/2012

241

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

OR
Function Name

OR

Description

Outputs a True value when any of its inputs are True.

Arguments

Input 1 to Input n {ANY_BIT}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {BOOL}
If any of the inputs is True, the output is True. The output is only False
if each of the inputs is False.

Examples:
Function Block Diagram - OR:
An OR function has 2 inputs - Input 1 is from a flow sensor and is named 'FlowPresent' and
Input 2 is from a Pump control and is named 'StopPump'. When the function receives a True
input from either 'FlowPresent' or 'StopPump' it outputs a True value. The output is only
False if all of its inputs are False

ST Program - OR:
The OR function is used to provide a Boolean value that is True if any of its inputs are True.
The syntax for an OR function in an ST Program is:
Output := OR (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.

242

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

XOR
Function Name

XOR

Description

Outputs a True value when its inputs are not the same i.e. it has True
and False inputs.

Arguments

Input 1 to Input n {ANY_BIT}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {BOOL}
The output is True if it has different inputs. It is only False if its inputs
are all True or all False.

Examples:
Function Block Diagram - XOR:
An XOR function has 2 inputs - Input 1 is from a flow sensor and is named 'FlowPresent' and
Input 2 is from a Pump control and is named 'StopPump'. When the function receives a True
input from 'FlowPresent' and a False input from 'StopPump' it outputs a True value (as it has
different input values). Similarly, when it receives a False value from 'FlowPresent' and a True
value from 'StopPump' it outputs a True value.
If the 'FlowPresent' value is True and the 'StopPump' value is True, the output is False as the
XOR function does not have different inputs. Similarly, if both of the input values are False,
the output is False. The output is only True when the XOR function has both True and False
inputs.

ST Program - XOR:
The XOR function is used to provide a Boolean value that is True only when the function has
True and False inputs. If the inputs are the same (all True or all False), the output is False. The
syntax for an XOR function in an ST Program is:
Output := XOR (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can also use this syntax:
Output := Input 1 XOR Input 2;

PD-6017 07/2012

243

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Comparison
You can use the COMPARISON functions to manipulate the flow of a program. For
example, you can use an EQ function set a part of a program to be performed only if both
of its input values are the same. This means that you can control whether the program, or
parts of the program, run in different situations.
The available COMPARISON functions are:

EQ (see page 244)

LE (see page 246)

LT (see page 247)

GE (see page 248)

GT (see page 249)

NE (see page 250).

EQ
Function Name

EQ (Equal To)

Description

Outputs a True value when its inputs are equal in value.

Arguments

Input 1 to Input n {ANY}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {BOOL}
The output is True only if the input values are equal in value.

Examples:
Function Block Diagram - EQ:
An EQ function has 2 inputs (in this case, 2 constant values). Both of the constants are set to
2, and so are equal. As the EQ's inputs are the same, its output is True.

If the top input was changed to 4, the EQ function would output a False valueit can only
output a True value if all of its inputs are exactly the same.

244

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ST Program - EQ:
The syntax for an EQ function in an ST Program is:
Output := EQ (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can use an operator:
Output := (Input 1=Input n);
This syntax is more commonly used with IF statements, for example, IIF (Input 1 = Input 2).

PD-6017 07/2012

245

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LE
Function Name

LE (Less Than or Equal To)

Description

Outputs a True value when Input 1 is less than or equal to the other
inputs.

Arguments

Input 1 to Input n {ANY}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {BOOL}
The output is True only if Input 1 is less than or equal to the other
input values. If Input 1 is greater than any of the other inputs, the LE
function outputs a False value.

Examples:
Function Block Diagram - LE:
An LE function has 2 inputs (in this case, 2 constant values). Input 1 is has a value of 2 and
Input 2 has a value of 4. The LE function outputs a True value as Input 1 is less than or equal
to the other inputs.

If Input 1 was changed to have a value of 4, the LE would still output a True value as Input 1
would be equal to Input 2. It is only when Input 1 is greater than the other Inputs that the LE
function outputs a False value.
ST Program - LE:
The syntax for an LE function in an ST Program is:
Output := LE (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can use an operator:
Output := (Input 1 <= Input n);

246

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LT
Function Name

LT (Less Than)

Description

Outputs a True value when Input 1 is less than the other inputs.

Arguments

Input 1 to Input n {ANY}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {BOOL}
The output is True only if Input 1 is less than the other input values. If
Input 1 is greater than or equal to any of the other inputs, the LT
function outputs a False value.

Examples:
Function Block Diagram - LT:
An LT function has 2 inputs (in this case, 2 constant values). Input 1 is has a value of 2 and
Input 2 has a value of 4. The LT function outputs a True value as Input 1 is less than the other
inputs.

If Input 1 was changed to have a value of 4, the LE function would output a False value as
Input 1 would be equal to Input 2; it would not be less than Input 2. It is only when Input 1 is
less than the other Inputs that the LT function outputs a True value.
ST Program - LT:
The syntax for an LT function in an ST Program is:
Output := LT (Input 1, Input n)
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can use an operator:
Output := (Input 1 < Input n);

PD-6017 07/2012

247

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

GE
Function Name

GE (Greater Than or Equal To)

Description

Outputs a True value when Input 1 is greater than or equal to the


other inputs.

Arguments

Input 1 to Input n {ANY}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {BOOL}
The output is True only if Input 1 is greater than or equal to the other
input values. If Input 1 is less than any of the other inputs, the GE
function outputs a False value.

Examples:
Function Block Diagram - GE:
A GE function has 2 inputs (in this case, 2 constant values). Input 1 is has a value of 4 and
Input 2 has a value of 2. The GE function outputs a True value as Input 1 is greater than the
other inputs.

If Input 2 was changed to have a value of 4, the GE function would output a True value as
Input 1 would be equal to Input 2. If Input 2 was changed to 5 instead of 4, the GE function
would output a False value as it would not be greater than or equal to Input 2.
ST Program - GE:
The syntax for a GE function in an ST Program is:
Output := GE (Input 1, Input n)
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can use an operator:
Output := (Input 1 >= Input n);

248

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

GT
Function Name

GT (Greater Than)

Description

Outputs a True value when Input 1 is greater than the other inputs.

Arguments

Input 1 to Input n {ANY}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {BOOL}
The output is True only if Input 1 is greater than the other input values.
If Input 1 is less than or equal to any of the other inputs, the GT
function outputs a False value.

Examples:
Function Block Diagram - GT:
A GT function has 2 inputs (in this case, 2 constant values). Input 1 is has a value of 4 and
Input 2 has a value of 2. The GT function outputs a True value as Input 1 is greater than the
other inputs.

If Input 2 was changed to have a value of 4, the GT function would output a False value as
Input 1 would be equal to Input 2; it would not be greater than Input 2. It is only when Input
1 is greater than the other Inputs that the GT function outputs a True value.
ST Program - GT:
The syntax for a GT function in an ST Program is:
Output := GT (Input 1, Input n)
Where Output, Input 1 and Input n are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.
Alternatively, you can use an operator:
Output := (Input 1 > Input n);

PD-6017 07/2012

249

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

NE
Function Name

NE (Not Equals)

Description

Outputs a True value when Input 1 is different to Input 2.

Arguments

Input 1 {ANY}
Input 2 {ANY}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {BOOL}
The output is True only if Input 1 is different to Input 2. If Input 2 has
the same value as Input 1, the NE function outputs a False value.

Examples:
Function Block Diagram - NE:
An NE function has 2 inputs (in this case, 2 constant values). Input 1 is has a value of 4 and
Input 2 has a value of 2. The NE function outputs a True value as Input 1 is different to Input
2.

If Input 2 was changed to have a value of 4, the NE function would output a False value as
Input 1 would be equal to Input 2. It is only when Input 1 is different to Input 2 that the NE
function outputs a True value.
ST Program - NE:
The syntax for a NE function in an ST Program is:
Output := NE (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Each
input is separated by a comma and is a Boolean. The Output value is also a Boolean.

250

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Date and Time


You can use the Date and Time functions to manipulate date and time values, for
example, you can create an output that consists of separate date and time inputs.
The available Date and Time functions are:

ADD_DT_TIME (see page 252)

ADD_TOD_TIME (see page 253)

CONCAT_D_TOD (see page 254)

DIVTIME (see page 255)

DT_TO_DATE (see page 256)

DT_TO_TOD (see page 257)

EXTRACT_DT_YEAR (see page 257)

EXTRACT_DT_MONTH (see page 258)

EXTRACT_DT_DAY (see page 258)

EXTRACT_DT_HOUR (see page 259)

EXTRACT_DT_MINUTE (see page 259)

EXTRACT_DT_SECOND (see page 260)

EXTRACT_DT_MILLISECOND (see page 260)

MULTIME (see page 261)

NOW (see page 262)

SUB_DATE_DATE (see page 263)

SUB_DT_DT (see page 264)

SUB_DT_TIME (see page 265)

SUB_TOD_TIME (see page 266)

SUB_TOD_TOD (see page 267)

MAKE_DATE_AND_TIME (see page 268)

MAKE_DATE (see page 270)

MAKE_TIME_OF_DAY (see page 271)

MAKE_TIME (see page 272)

MAKE_DATE_AND_TIME_FROM_OPC (see page 274)

MAKE_TIME_FROM_OPC (see page 275)

UTC_TO_LOCAL (see page 276)

LOCAL_TO_UTC (see page 277).

PD-6017 07/2012

251

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ADD_DT_TIME
Function Name

ADD_DT_TIME

Description

Adds a date and time input to a time interval input and outputs the
result.

Arguments

Input 1 {DATE_AND_TIME}
Input 2 {TIME}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {DATE_AND_TIME}

Examples:
Function Block Diagram - ADD_DT_TIME:
An ADD_DT_TIME function has two inputs:

Input 1 is a date and time value (in this case, a NOW function which provides the current
date and time)

Input 2 is a constant with a time value of T#10m (10 minutes).

NOTE: You can use the UTC_TO_LOCAL function to convert the NOW input from UTC time
to Local time.
The ADD_DT_TIME function adds the time interval defined by Input 2 (10 minutes) to the
NOW time, and outputs the result. So, if the NOW time is 2006-03-21-09:27.31.546, the
ADD_DT_TIME function adds 10 minutes to that time and outputs
2006-03-21-09:37.31.546.
ST Program - ADD_DT_TIME:
The syntax for an ADD_DT_TIME function in an ST Program is:
Output := ADD_DT_TIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Each
input is separated by a comma. Output and Input 1 are Date and Time values and Input 2 is
a Time value (it defines an interval).
Further Information
Time Zones: see Time Zone Support in ClearSCADA, on page 189 in the ClearSCADA Guide
to Core Configuration.

252

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ADD_TOD_TIME
Function Name

ADD_TOD_TIME

Description

Adds a time interval to a specified time of day.

Arguments

Input 1 {TIME_OF_DAY}
Input 2 {TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME_OF_DAY}
The output is the Time of Day provided by Input 1 + the Time interval
provided by Input 2.

Examples:
Function Block Diagram - ADD_TOD_TIME:
An ADD_TOD_TIME function has 2 inputs (in this case, the inputs are constants):

Input 1 defines 10:10:00 as a Time of Day value (TOD#)

Input 2 defines 10 minutes as a Time interval value (T#).

The ADD_TOD_TIME function adds the 10 minute time interval to the 10:10:00 time of day
value and outputs the result: 10:20:00.000

ST Program - ADD_TOD_TIME:
The syntax for an ADD_TOD_TIME function in an ST Program is:
Output := ADD_TOD_TIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Each
input is separated by a comma. Output and Input 1 are Time of Day values and Input 2 is a
Time value (it defines an interval).

PD-6017 07/2012

253

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

CONCAT_D_TOD
Function Name

CONCAT_D_TOD

Description

Combines a date input with a time of day input to provide a date time
output.

Arguments

Input 1 {DATE}
Input 2 {TIME_OF_DAY}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {DATE_AND_TIME}
The output is the Date provided by Input 1 + the Time of Day provided
by Input 2.

Examples:
Function Block Diagram - CONCAT_D_TOD:
A CONCAT_D_TOD function has 2 inputs (in this case, the inputs are constants):

Input 1 defines 2006-03-11 as a Date value (D#)

Input 2 defines 10:10:00 as a Time of Day value (TOD#).

The CONCAT function concatenates the date value and time of day value. The result is a
Date and Time output of 2006-03-11-10:10:00.000

ST Program - CONCAT_D_TOD:
The syntax for a CONCAT_D_TOD function in an ST Program is:
Output := CONCAT_D_TOD (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Each
input is separated by a comma. Input 1 is a Date value, Input 2 is a Time of Day value and the
Output is a Date and Time value.

254

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

DIVTIME
Function Name

DIVTIME

Description

Provides a time interval output that is the result of a time interval input
divided by an integer input.

Arguments

Input 1 {TIME}
Input 2 {INT}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}
The output is the result of Input 1/Input 2.

Examples:
Function Block Diagram - DIVTIME:
A DIVTIME function has 2 inputs (in this case, the inputs are constants):

Input 1 is a time value and is set to 59h (59 hours)

Input 2 is an integer and is set to 4.

The DIVTIME function divides 59 hours by 4 to provide the output of 14h45m (14 hours and
45 minutes).

ST Program - DIVTIME:
The syntax for a DIVTIME function in an ST Program is:
Output := DIVTIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Each
input is separated by a comma. Input 1 is a Time value, Input 2 is an integer value and the
Output is a Time value.

PD-6017 07/2012

255

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

DT_TO_DATE
Function Name

DT_TO_DATE

Description

Converts a Date and Time input into a Date output (the output will not
include a time).

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {DATE}
The output is the result of Input 1 - the Time supplied by Input 1.

Examples:
Function Block Diagram - DT_TO_DATE:
A DT_TO_DATE function has an input of NOW. This sets the input to be the current date and
time. The DT_TO_DATE function returns the date part of the input as its output.

ST Program - DT_TO_DATE:
The syntax for a DT_TO_DATE function in an ST Program is:
Output := DT_TO_DATE (Input 1)
Where Output is a Date value and Input 1 is a Date and Time value.

256

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

DT_TO_TOD
Function Name

DT_TO_TOD

Description

Converts a Date and Time input into a Time of Day output (the output
will not include a date).

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME_OF_DAY}
The output is the result of Input 1 - the Date supplied by Input 1.

The DT_TO_TOD function works in a similar way to the DT_TO_DATE (see page 256)
function except that it determines its output by using Time part of the Date and Time input
instead of the Date part. For ST Programs, a similar syntax is used:
Output := DT_TO_TOD (Input 1)

EXTRACT_DT_YEAR
Function Name

EXTRACT_DT_YEAR

Description

Converts a Date and Time input into an integer output for the year.

Arguments

Input 1 {DATE_AND_TIME}

Returns

Output {INT}
The output is the year part of the Date and Time input.

Examples:
Function Block Diagram - EXTRACT_DT_YEAR:
An EXTRACT_DT_YEAR function has an input of NOW. This sets the input to be the current
date and time. The EXTRACT_DT_YEAR function returns the year part of the date in the Date
and Time input as its output. So, if the date and time value of the input was
2006-03-21-10:25:00.000, the EXTRACT_DT_YEAR function would return 2006 (the year
part of the Date and Time input).

ST Program - EXTRACT_DT_YEAR:
The syntax for an EXTRACT_DT_YEAR function in an ST Program is:
Output := EXTRACT_DT_YEAR (Input 1)
Where Output is an integer value and Input 1 is a Date and Time value.

PD-6017 07/2012

257

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXTRACT_DT_MONTH
Function Name

EXTRACT_DT_MONTH

Description

Converts a Date and Time input into an integer output for the month.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the month part of the Date and Time input.

The EXTRACT_DT_MONTH function works in the same way as the EXTRACT_DT_YEAR


(see page 257) function except that it returns an integer that is formed from the month part
of the Date and Time input instead of the year part. For ST Programs, a similar syntax is
used:
Output := EXTRACT_DT_MONTH (Input 1)

EXTRACT_DT_DAY
Function Name

EXTRACT_DT_DAY

Description

Converts a Date and Time input into an integer output for the day.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {INT}
The output is the day part of the Date and Time input.

The EXTRACT_DT_DAY function works in the same way as the EXTRACT_DT_YEAR (see
page 257) function except that it returns an integer that is formed from the day part of the
Date and Time input instead of the year part. For ST Programs, a similar syntax is used:
Output := EXTRACT_DT_DAY (Input 1)

258

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXTRACT_DT_HOUR
Function Name

EXTRACT_DT_HOUR

Description

Converts a Date and Time input into an integer output for the hour.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the hour part of the Date and Time input.

The EXTRACT_DT_HOUR function works in the same way as the EXTRACT_DT_YEAR (see
page 257) function except that it returns an integer that is formed from the hour part of the
Date and Time input instead of the year part. For ST Programs, a similar syntax is used:
Output := EXTRACT_DT_HOUR (Input 1)

EXTRACT_DT_MINUTE
Function Name

EXTRACT_DT_MINUTE

Description

Converts a Date and Time input into an integer output for the minute.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the minute part of the Date and Time input.

The EXTRACT_DT_MINUTE function works in the same way as the EXTRACT_DT_YEAR


(see page 257) function except that it returns an integer that is formed from the minute part
of the Date and Time input instead of the year part. For ST Programs, a similar syntax is
used:
Output := EXTRACT_DT_MINUTE (Input 1)

PD-6017 07/2012

259

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXTRACT_DT_SECOND
Function Name

EXTRACT_DT_SECOND

Description

Converts a Date and Time input into an integer output for the second.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the second part of the Date and Time input.

The EXTRACT_DT_SECOND function works in the same way as the EXTRACT_DT_YEAR


(see page 257) function except that it returns an integer that is formed from the second part
of the Date and Time input instead of the year part. For ST Programs, a similar syntax is
used:
Output := EXTRACT_DT_SECOND (Input 1)

EXTRACT_DT_MILLISECOND
Function Name

EXTRACT_DT_MILLISECOND

Description

Converts a Date and Time input into an integer output for the
millisecond.

Arguments

Input 1 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the millisecond part of the Date and Time input.

The EXTRACT_DT_MILLISECOND function works in the same way as the


EXTRACT_DT_YEAR (see page 257) function except that it returns an integer that is formed
from the milliseconds part of the Date and Time input instead of the year part. For ST
Programs, a similar syntax is used:
Output := EXTRACT_DT_MILLISECOND (Input 1)

260

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MULTIME
Function Name

MULTIME

Description

Outputs a time interval value that is the result of a time interval value
multiplied by an integer value.

Arguments

Input 1 {TIME}
Input 2 {INT}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}

Examples:
Function Block Diagram - MULTIME:
A GT function has 2 inputs (in this case, 2 constant values). Input 1 is has a time value of 59
hours (TIME#59h) and Input 2 has an integer value of 4. The MULTIME function outputs a
time value of 9d20h as this is the result of 59 hours multiplied by 4.

ST Program - MULTIME:
The syntax for a MULTIME function in an ST Program is:
Output := MULTIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
is a time value, Input 2 is an integer value, and the Output is a time value.

PD-6017 07/2012

261

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

NOW
Function Name

NOW

Description

Outputs the current date and time (taken from the server when the
Logic program executes)

Arguments

None.

Returns

Output {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Examples:
Function Block Diagram - NOW:
A NOW function can be used as an input for other functions, for example, as an input for an
ADD_DT_TIME function. The NOW function provides the current date and time.

ST Program - NOW:
The syntax for a NOW function in an ST Program is:
Output := NOW()
The NOW function can also be used in place of a Date and Time Input in an ST Program:
Output := ADD_DT_TIME (NOW, Input 2)
Where Output and Input 2 are defined as variables earlier in the ST program. The NOW
function replaces Input 1 (it provides the current date and time for Input 1).

262

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB_DATE_DATE
Function Name

SUB_DATE_DATE

Description

Subtracts an date input from another date input to provide a time


output.

Arguments

Input 1 {DATE}
Input 2 {DATE}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}
The Output is the result of Input 1 - Input 2

Examples:
Function Block Diagram - SUB_DATE_DATE:
A SUB_DATE_DATE function has 2 inputs (in this case, 2 constants):

Input 1 is set to D#2006-03-30

Input 2 is set to D#2005-03-21.

The SUB_DATE_DATE function returns a time value of 374d as 2006-03-30 minus


2005-03-21 = 374 days.

ST Program - SUB_DATE_DATE:
The syntax for a SUB_DATE_DATE function in an ST Program is:
Output := SUB_DATE_DATE (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
and Input 2 are date and time values and the Output is a time value.

PD-6017 07/2012

263

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB_DT_DT
Function Name

SUB_DT_DT

Description

Subtracts a date time input from another date time input to provide a
time output. (It outputs the time difference between the two input
dates and times).

Arguments

Input 1 {DATE_AND_TIME}
Input 2 {DATE_AND_TIME}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {TIME}
The Output is the result of Input 1 - Input 2

Examples:
Function Block Diagram - SUB_DT_DT:
A SUB_DT_DT function has 2 inputs (in this case, a NOW function and a constant):

Input 1 is connected to a NOW function

Input 2 is set to DT#2002-03-11-10:00:25.431.

The SUB_DATE_DATE function returns a time value that is the result of the current date and
time - 2002-03-11-10:00:25.431.

ST Program - SUB_DT_DT:
The syntax for a SUB_DT_DT function in an ST Program is:
Output := SUB_DT_DT (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
and Input 2 are date and time values and the Output is a time value.

264

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB_DT_TIME
Function Name

SUB_DT_TIME

Description

Subtracts a time input from a date time input to provide a date time
output.

Arguments

Input 1 {DATE_AND_TIME}
Input 2 {TIME}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE_AND_TIME}
The Output is the result of Input 1 - Input 2

Examples:
Function Block Diagram - SUB_DT_TIME:
A SUB_DT_TIME function has 2 inputs (in this case, a NOW function and a constant):

Input 1 is connected to a NOW function

Input 2 is set to T#45m.

The SUB_DT_TIME function returns a date time value that is the result of the current date
and time - 45 minutes.

ST Program - SUB_DT_TIME:
The syntax for a SUB_DT_TIME function in an ST Program is:
Output := SUB_DT_TIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
is a date time value, Input 2 is a time value, and the Output is a date and time value.

PD-6017 07/2012

265

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB_TOD_TIME
Function Name

SUB_TOD_TIME

Description

Subtracts a time input from a time of day input to provide a time of


day output.

Arguments

Input 1 {TIME_OF_DAY}
Input 2 {TIME}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {TIME_OF_DAY}
The Output is the result of Input 1 - Input 2

Examples:
Function Block Diagram - SUB_TOD_TIME:
A NOW function is used to provide the current time for a SUB_TOD_TIME function. As the
NOW function provides a date time value, a DT_TO_TOD function has to be used to convert
the NOW output into a TOD value that can be used as an input by the SUB_TOD_TIME
function.
For its other input, the SUB_TOD_TIME function has a constant that is set to T#35m (35
minutes):

The SUB_TOD_TIME function returns a time value that is the result of the current time - 35
minutes.
ST Program - SUB_TOD_TIME:
The syntax for a SUB_TOD_TIME function in an ST Program is:
Output := SUB_TOD_TIME (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
is a time of day value, Input 2 is a time value, and the Output is a time of day value.

266

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SUB_TOD_TOD
Function Name

SUB_TOD_TOD

Description

Subtracts a time of day input from a time of day input to provide a


time output.

Arguments

Input 1 {TIME_OF_DAY}
Input 2 {TIME_OF_DAY}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}
The Output is the result of Input 1 - Input 2

Examples:
Function Block Diagram - SUB_TOD_TOD:
A NOW function is used to provide the current time for a SUB_TOD_TOD function. As the
NOW function provides a date time value, a DT_TO_TOD function has to be used to convert
the NOW output into a TOD value that can be used as an input by the SUB_TOD_TOD
function.
For its other input, the SUB_TOD_TIME function has a constant that is set to
TOD#16:00:23.144:

The SUB_TOD_TIME function returns a time value that is the result of the current time 16:0023:144 i.e the difference in time between the current time and 16:0023:144.
ST Program - SUB_TOD_TOD:
The syntax for a SUB_TOD_TOD function in an ST Program is:
Output := SUB_TOD_TOD (Input 1, Input 2)
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program. Input 1
is a time of day value, Input 2 is a time of day value, and the Output is a time value.

PD-6017 07/2012

267

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_DATE_AND_TIME
Function Name

MAKE_DATE_AND_TIME

Description

Provides a date and time output that is made up from the


components supplied via the inputs.

Arguments

Y {INT}
Y provides the year.
MO {SINT}
MO provides the month.
D {SINT}
D provides the day.
H {SINT}
H provides the hour.
MI {SINT}
MI provides the minutes.
S {SINT}
S provides the seconds.
MS {INT}
MS provides the milliseconds.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE_AND_TIME}

Examples:
Function Block Diagram - MAKE_DATE_AND_TIME:

The MAKE_DATE_AND_TIME outputs a date time value that is made up from the
components supplied via its inputs (the year is taken from the Y input, month from the MO
input and so on). On a live system, the inputs for a MAKE_DATE_AND_TIME function are
often the results of a calculation, with the inputs being variable depending on the outputs of
other functions etc.

268

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ST Program - MAKE_DATE_AND_TIME:
The syntax for a MAKE_DATE_AND_TIME function in an ST Program is:
Output := MAKE_DATE_AND_TIME (Y, MO, D, H, MI, S, MS);
Where Output, Y, MO, D, H, MI, S, and MS are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := MAKE_TIME_AND_TIME (Y:= 2006, MO:= 02, D:= 14, H:= 12, MI:=
41, S:= 21, MS:= 17);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example).

PD-6017 07/2012

269

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_DATE
Function Name

MAKE_DATE

Description

Provides a date output that is made up from the components


supplied via the inputs.

Arguments

Y {INT}
Y provides the year.
MO {INT}
MO provides the month.
D {INT}
D provides the day.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE}

Examples:
Function Block Diagram - MAKE_DATE:

The MAKE_DATE outputs a date value that is made up from the components supplied via its
inputs (the year is taken from the Y input, month from the MO input, and the day from the D
input). On a live system, the inputs for a MAKE_DATE function are often the results of a
calculation, with the inputs being variable depending on the outputs of other functions etc.
ST Program - MAKE_DATE:
The syntax for a MAKE_DATE function in an ST Program is:
Output := MAKE_DATE (Y, MO, D);
Where Output, Y, MO, and D are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := MAKE_DATE (Y:= 2006, MO:= 02, D:= 14);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example above).

270

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_TIME_OF_DAY
Function Name

MAKE_TIME_OF_DAY

Description

Provides a time of day output that is made up from the components


supplied via the inputs.

Arguments

The arguments are (from top to bottom):


H {INT}
H provides the hour.
MI {INT}
MI provides the minutes.
S {INT}
S provides the seconds.
MS {INT}
MS provides the milliseconds.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME_OF_DAY}

Examples:
Function Block Diagram - MAKE_TIME_OF_DAY:

The MAKE_TIME_OF_DAY function outputs a time of day value that is made up from the
components supplied via its inputs (the hour is taken from the H input, minute from the MI
input, seconds from the S input and the milliseconds from the MS input). On a live system,
the inputs for a MAKE_TIME_OF_DAY function are often the results of a calculation, with the
inputs being variable depending on the outputs of other functions etc.
ST Program - MAKE_TIME_OF_DAY:
The syntax for a MAKE_TIME_OF_DAY function in an ST Program is:
Output := MAKE_TIME_OF_DAY (H, MI, S, MS);
Where Output, H, MI, S and MS are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := MAKE_TIME_OF_DAY (H:= 18, MI:= 25, S:= 13, MS:= 32);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example above).

PD-6017 07/2012

271

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_TIME
Function Name

MAKE_TIME

Description

Provides a time output that is made up from the components


supplied via the inputs.

Arguments

The arguments are (from top to bottom):


D {INT}
D provides the day.
H {INT}
H provides the hour.
MI {INT}
MI provides the minutes.
S {INT}
S provides the seconds.
MS {INT}
MS provides the milliseconds.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}

Examples:
Function Block Diagram - MAKE_TIME:

The MAKE_TIME function outputs a time value that is made up from the components
supplied via its inputs (the day is taken from the D input, hour from the H input, minute from
the MI input, seconds from the S input and the milliseconds from the MS input). On a live
system, the inputs for a MAKE_TIME function would most likely be the results of a
calculation, with the inputs being variable depending on the outputs of other functions etc.

272

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ST Program - MAKE_TIME:
The syntax for a MAKE_TIME function in an ST Program is:
Output := MAKE_TIME (D, H, MI, S, MS);
Where Output, D, H, MI, S and MS are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := MAKE_TIME (D:= 11, H:= 14, MI:= 32, S:= 21, MS:= 07);
Where the numbers are the input values (in this case, they are the same numbers as used in
the Function Block Diagram example above).

PD-6017 07/2012

273

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_DATE_AND_TIME_FROM_OPC
Function Name

MAKE_DATE_AND_TIME_FROM_OPC

Description

Provides a date and time output that is made up from the input string
(which defines a time in the OPC time format). Typically, this input is
provided by a value in the database, for example, the TrendOffset tag
of a point.

Arguments

Input 1 {STRING - OPC Time Format}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE_AND_TIME}

Examples:
Function Block Diagram - MAKE_DATE_AND_TIME_FROM_OPC:

The MAKE_DATE_AND_TIME_FROM_OPC function provides a date and time value. The


output is calculated by using the OPC time provided by the string input. In the example
shown above, the V1 input is a tag (the tag represents the TrendOffset configuration property
of a point. The TrendOffset is a time value defined in the OPC time format, in this case,
M-10M). The MAKE_DATE_AND_TIME_FROM_OPC function uses the OPC time defined in
the input string and the current time (on the server) to calculate its output. So, at
09:11:00.000 on April 3rd 2006, the MAKE_DATE_AND_TIME_FROM_OPC function outputs
2006-04-03-09:01:00.000 (the current time - ten minutes from the start of the current minute
as defined by the V1 input). Not that the date format used here is YYYY, MM, DD.
ST Program - MAKE_DATE_AND_TIME_FROM_OPC:
The syntax for a MAKE_DATE_AND_TIME_FROM_OPC function in an ST Program is:
Output := MAKE_DATE_AND_TIME_FROM_OPC (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a String that contains a time value in the OPC time format.

Further Information
OPC Time Format: see Using OPC Time Formats, on page 173 in the ClearSCADA Guide
to Core Configuration.

274

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAKE_TIME_FROM_OPC
Function Name

MAKE_TIME_FROM_OPC

Description

Provides a time output that is made up from the input string (which
defines a time in the OPC time format). The input may be a value in
the database, for example, the TrendUpdateRate tag of a point.

Arguments

Input 1 {STRING - OPC Time Format}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {TIME}

Examples:
Function Block Diagram - MAKE_TIME_FROM_OPC:

The MAKE_TIME_FROM_OPC function outputs a time value that is based on the OPC time
provided by the input. In the example shown above, the StringPoint input is a tag (the tag
represents the CurrentValueFormatted property of an internal string point). The
CurrentValueFormatted of the string point is 2D, so the MAKE_TIME_FROM_OPC function
converts the OPC time of the string point into a time value for the ST program: 2d.
ST Program - MAKE_TIME_FROM_OPC:
The syntax for a MAKE_TIME_FROM_OPC function in an ST Program is:
Output := MAKE_TIME_FROM_OPC (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a String that contains a time value in the OPC time format.

PD-6017 07/2012

275

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

UTC_TO_LOCAL
Function Name

UTC_TO_LOCAL

Description

Outputs the time provided by Input 1 in Local time format. This allows
the ST program to make adjustments according to local time changes
such as British Summer Time.
Local time settings are defined by the operating system.

Arguments

Input 1 {DATE_AND_TIME - UTC time format}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE_AND_TIME - Local time format}

Examples:
Function Block Diagram - UTC_TO_LOCAL:

The UTC_TO_LOCAL function converts a date and time input from Coordinated Universal
Time into local time. In the example shown above, the UTC_TO_LOCAL function applies the
local time settings to the input time and date. In this case, the UTC_TO_LOCAL function
takes the input time and adds 1 hour for the output (the local time settings are 1 hour in
advance).

ST Program - UTC_TO_LOCAL:
The syntax for a UTC_TO_LOCAL function in an ST Program is:
Output := UTC_TO_LOCAL (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a Date and Time value.

Further Information
Time Zones: see Time Zone Support in ClearSCADA, on page 189 in the ClearSCADA
Guide to Core Configuration.

276

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LOCAL_TO_UTC
Function Name

LOCAL_TO_UTC

Description

Outputs the local time provided by Input 1 in UTC time format.


Local time settings are defined by the operating system.

Arguments

Input 1 {DATE_AND_TIME - Local time format}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {DATE_AND_TIME - UTC time format}

Examples:
Function Block Diagram - LOCAL_TO_UTC:

The LOCAL_TO_UTC function converts a date and time input from local time into
Coordinated Universal Time. In the example shown above, the LOCAL_TO_UTC function
takes the local time input and removes the local time settings to provide an output in UTC. In
this case, the LOCAL_TO_UTC function takes the input time and removes 1 hour for the
output (the local time settings are 1 hour in advance).

ST Program - LOCAL_TO_UTC:
The syntax for a LOCAL_TO_UTC function in an ST Program is:
Output := LOCAL_TO_UTC (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a Date and Time value.
Further Information
Time Zones: see Time Zone Support in ClearSCADA, on page 189 in the ClearSCADA Guide
to Core Configuration.

PD-6017 07/2012

277

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Numerical
Numerical functions allow you to calculate values as absolute values, trigonometric
values, natural exponential values, base 10 logarithms, natural logarithms, or square root
values. You can also truncate a floating point value into an integer.
You should only use the Numerical functions if you have an understanding of the
mathematical principles associated with each of the available functions (the functions are
named after a mathematical principle).
The numerical functions are:

278

ABS (see page 279)

ACOS (see page 280)

ASIN (see page 281)

ATAN (see page 282)

COS (see page 283)

EXP (see page 284)

LOG (see page 285)

LN (see page 286)

SIN (see page 287)

SQRT (see page 288)

TAN (see page 289)

TRUNC (see page 290).

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ABS
Function Name

ABS

Description

Converts a numerical input into an absolute value. The absolute value


is the output and is also a REAL or LREAL value.

Arguments

Input 1 {ANY_NUM}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {Same data type as input}

Examples:
Function Block Diagram - ABS:

The ABS function converts values into positive values (if the input is positive, the output is
positive; if the input is negative, the output is positive). In this example, the constant input is
-324 so the ABS function outputs 324.
ST Program - ABS:
The syntax for an ABS function in an ST Program is:
Output := ABS (Input 1);

Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents any type of numerical value.

PD-6017 07/2012

279

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ACOS
Function Name

ACOS

Description

Converts a REAL or LREAL input into an arc cosine (inverse cosine).


The arc cosine value is the output and is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}. This value has to be between 0 and 1.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {REAL or LREAL}. This value is in radians.

Examples:
Function Block Diagram - ACOS:

In this example, the input of 0.431 is provided by the CurrentValueFormatted property of a


point. The ACOS function converts the value into an arc cosine value of 1.12519562771659
and this is used as the output.
ST Program - ACOS:
The syntax for an ACOS function in an ST Program is:
Output := ACOS (Input 1);

Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value
as Input 1).

280

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ASIN
Function Name

ASIN

Description

Converts a REAL or LREAL input into an arc sine (inverse sine). The
arc sine value is the output and is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}. This value has to be between 0 and 1.


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {REAL or LREAL}. This value is in radians.

Examples:
Function Block Diagram - ASIN:

In this example, the input of 0.431 is provided by the CurrentValueFormatted property of a


point. The ASIN function converts the value into an arc sine value of 0.445600699078308
and this is used as the output.
ST Program - ASIN:
The syntax for an ASIN function in an ST Program is:
Output := ASIN (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

PD-6017 07/2012

281

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ATAN
Function Name

ATAN

Description

Converts a REAL or LREAL input into an arc tangent (inverse


tangent). The arc sine value is the output and is also a REAL or
LREAL.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {REAL or LREAL}. This value is in radians.

Examples:
Function Block Diagram - ATAN:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The ATAN function converts the value into an arc tangent value of 1.37340076694502 and
this is used as the output.
ST Program - ATAN:
The syntax for an ATAN function in an ST Program is:
Output := ATAN (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

282

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

COS
Function Name

COS

Description

Converts a REAL or LREAL input into a cosine value that is the


output. The cosine value is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}. This value is in radians.


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - COS:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The COS function converts the value into a cosine value of 0.283662185463226 and this is
used as the output.
ST Program - COS:
The syntax for a COS function in an ST Program is:
Output := COS (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

PD-6017 07/2012

283

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXP
Function Name

EXP

Description

Converts a REAL or LREAL input into a natural exponential value that


is the output. The exponential value is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - EXP:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The EXP function converts the value into an exponential value of 148.413159102577 and this
is used as the output.
ST Program - EXP:
The syntax for an EXP function in an ST Program is:
Output := EXP (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

284

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LOG
Function Name

LOG

Description

Converts a REAL or LREAL input into a base 10 logarithm value that


is the output. The base 10 logarithm is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - LOG:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The LOG function converts the value into a base 10 logarithm value of 0.698970004336019
and this is used as the output.
ST Program - LOG:
The syntax for a LOG function in an ST Program is:
Output := LOG (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

PD-6017 07/2012

285

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LN
Function Name

LN

Description

Converts a REAL or LREAL input into a natural logarithm value that is


the output. The natural logarithm is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - LN:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The LN function converts the value into a natural logarithm value of 1.6094379124341 and
this is used as the output.
ST Program - LN:
The syntax for an LN function in an ST Program is:
Output := LN (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

286

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SIN
Function Name

SIN

Description

Converts a REAL or LREAL input into a sine value that is the output.
The sine value is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}. This value is in radians.


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {REAL or LREAL}.

Examples:
Function Block Diagram - SIN:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The SIN function converts the value into a sine value of -0.958924274663138 and this is
used as the output.
ST Program - SIN:
The syntax for a SIN function in an ST Program is:
Output := SIN (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

PD-6017 07/2012

287

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SQRT
Function Name

SQRT

Description

Outputs the square root value of the input value. Both the input and
output values are REAL or LREAL values.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - SQRT:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The SQRT function outputs the square root of 5 which is 2.23606797749979.
ST Program - SQRT:
The syntax for an SQRT function in an ST Program is:
Output := SQRT (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

288

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

TAN
Function Name

TAN

Description

Converts a REAL or LREAL input into a tangent value that is the


output. The tangent value is also a REAL or LREAL.

Arguments

Input 1 {REAL or LREAL}. This value is in radians.


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {REAL or LREAL}

Examples:
Function Block Diagram - TAN:

In this example, the input of 5 is provided by the CurrentValueFormatted property of a point.


The TAN function converts the value into a tangent value of -3.38051500624659.
ST Program - TAN:
The syntax for a TAN function in an ST Program is:
Output := TAN (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

PD-6017 07/2012

289

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

TRUNC
Function Name

TRUNC

Description

Truncates the floating value of the input into a double integer value.
The double integer value is used as the output.

Arguments

Input 1 {REAL or LREAL}.


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {DINT}

Examples:
Function Block Diagram - TRUNC:

In this example, the input of 5.75423 is provided by the CurrentValueFormatted property of a


point. The TRUNC function truncates the value into a double integer value of 5.
ST Program - TRUNC:
The syntax for a TRUNC function in an ST Program is:
Output := TRUNC (Input 1);
Where Output and Input 1 are defined as variables earlier in the ST program. The Input 1
variable represents a REAL or LREAL type of value (the output is the same type of value as
Input 1).

290

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Selection
You can use selection functions to provide a single output from a selection of inputs. One
of the inputs is used as the output for the functionthe type of function determines which
output is used. Selection functions are useful when you need a program to choose an
appropriate value from several inputs.
The selection functions are:

LIMIT (see page 291)

MAX (see page 293)

MIN (see page 294)

MUX (see page 295)

SEL (see page 296).

LIMIT
Function Name

LIMIT

Description

Outputs a value that is within the limits that are provided by the
inputs:

Arguments

If the IN input is less than the MIN input, the output is the same
as the MIN input.

If the IN input is greater than the MX input, the output is the


same as the MX input.

If the IN input is greater than the MIN input but less than the MX
input, the output is the same as the IN input.

MIN {ANY}.
The MIN input defines the minimum value that can be used as the
output. This is used as the output if the IN input is less
than the MIN input.
IN {ANY}
The IN input defines the input that is to be used as the output. It is
only used if it is greater than the MIN input and less than the MX
input.
MX {ANY}
The MX input defines the maximum value that can be used as the
output. This is used as the output if the IN input is greater than the
MX input.
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

PD-6017 07/2012

Output {ANY} The data type is of the same type as the inputs.

291

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Function Block Diagram - LIMIT:

In this example, the inputs are constant values. The IN input is greater than the MIN input
and less than the MX input and so is used as the output value. If the IN input was 1, it would
be less than the MIN input and so the MIN input would be used as the output instead.
Similarly, if the IN input was 10, it would be greater than the MX input and so the output
would be 8 as the LIMIT function would use the MX input instead of the IN input.
ST Program - LIMIT:
The syntax for a LIMIT function in an ST Program is:
Output := LIMIT (MIN, IN, MX);
Where Output, MIN, IN, and MX are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := LIMIT (MIN:= 2, IN:= 5, MX:= 8);

Where the numbers are the input values (in this case, they are the same numbers as used
in the Function Block Diagram example).

292

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MAX
Function Name

MAX

Description

Outputs the same value as its greatest input.

Arguments

Input 1 - Input n {ANY}


For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {ANY}.
The MAX function outputs the same value as its greatest input. The
output is of the same type as the input.

Examples:
Function Block Diagram - MAX:

In this example, the inputs are constant values. The MAX function outputs the same value as
its highest input. In this case, it has inputs of 2, 5, and 8 and so it outputs 8.
ST Program - MAX:
The syntax for a MAX function in an ST Program is:
Output := MAX (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program.

PD-6017 07/2012

293

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MIN
Function Name

MIN

Description

Outputs the same value as its lowest input.

Arguments

Input 1 - Input n {ANY}


For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {ANY}.
The MIN function outputs the same value as its lowest input. The
output is of the same type as the input.

Examples:
Function Block Diagram - MIN:

In this example, the inputs are constant values. The MIN function outputs the same value as
its lowest input. In this case, it has inputs of 4 and 5, so it outputs 5.
ST Program - MIN:
The syntax for a MIN function in an ST Program is:
Output := MIN (Input 1, Input n);
Where Output, Input 1 and Input n are defined as variables earlier in the ST program.

294

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MUX
Function Name

MUX

Description

The MUX function outputs the same number as one of its inputs. The
input that is chosen is dependent on the value of the K input.
The MUX function has a K input and 2 or more other inputs. The
unnamed inputs are recognized as being 0 for the first (top) input, 1
for the second input, 2 for the third input, 3 for the fourth input and so
on. The number of the K input is used to identify which of the other
inputs has the value that is to be used as the output.

Arguments

K {ANY_INT}.
The number for the K input is used to identify the input that is to be
used as the output for the MUX function.
Input 0 - Input n {ANY}
Each input is identified by a number, with the first (top) input being 0,
the second being 1, the third being 2 and so on.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {ANY}
The K input is a number. This number is used to identify the input that
has the value that is to be used as the output. The output value is of
the same type as the value provided by the designated input.

Examples:
Function Block Diagram - MUX:

In this example, the K value is provided by a tag that represents the CurrentValueFormatted
property of a point named 'FlowPresent'. As the 'FlowPresent' point is a digital, it provides a
Boolean value and this has to be converted into an integer by using a BOOL_TO_INT
conversion. The other inputs are provided by constant values, with Input 0 being 4 and Input
1 being 5.
As the current value of the 'FlowPresent' is True, the integer value for the K input is 1. This
means that the value for the MUX output is the same as the value for Input 1 which is 5.
ST Program - MUX:
The syntax for a MUX function in an ST Program is:
Output := MUX (K, Input 0, Input n);
Where Output, K, Input 0 and Input n are defined as variables earlier in the ST program.

PD-6017 07/2012

295

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SEL
Function Name

SEL

Description

The SEL function outputs the same number as one of its inputs. The
input that is chosen is dependent on the value of the G inputif G is
False, the IN0 value is used as the output; if G is True, the IN1 value is
used instead.

Arguments

G {BOOL}.
The value of the G input is used to determine whether the output
matches the IN0 input or the IN1 input. If the G input is False, the
output matches IN0; if the G input is True, the output matches IN1.
IN0 {ANY}
IN1 {ANY}
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {ANY}
The output value matches the input value of IN0 or IN1. The value of
the G input determines whether IN0 or IN1 is used.

Examples:
Function Block Diagram - SEL:

In this example, the Boolean value for G comes from a tag that references the
CurrentValueFormatted property of a digital point named 'FlowPresent'. The IN0 and IN1
values are provided by constants. As the 'FlowPresent' value is True (1), the SEL function
outputs the same value as IN1, which in this case is 5.
ST Program - SEL:
It is unlikely that you would use a SEL function in an ST program as the same functionality
can be provided by an IF statement. However, if you did choose to use a SEL function, you
would need to use this syntax:
Output := SEL (G, IN0, IN1);
Where Output, G, IN0 and IN1 are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := SEL (G:= True, IN0:= 4, IN1:= 5);
Where the True, 4 and 5 values are the input values (in this case, they are the same values as
used in the Function Block Diagram example above).

296

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

String
You can use the STRING functions to manipulate strings, for example, you can create a
string output that consists of 2 other strings.
The available STRING functions are:

CONCAT (see page 297)

DELETE (see page 299)

ELEMENT (see page 300)

FIND (see page 302)

INSERT (see page 303)

LEFT (see page 304)

LEN (see page 305)

MID (see page 306)

REPLACE (see page 307)

RIGHT (see page 309).

CONCAT
Function Name

CONCAT

Description

The CONCAT function concatenates its inputs. The inputs are strings
and the output is a combination of the input strings (the function
appends the strings into a single string).

Arguments

Input 1 {STRING}
Input n {STRING}
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a combination of the input strings.

PD-6017 07/2012

297

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Function Block Diagram - CONCAT:

In this example, the CONCAT function has a string input of 'POINT' and a string input of
'DESC'. The function concatenates the inputs to provide an output of POINTDESC.
ST Program - CONCAT:
To use a CONCAT function in an ST program, you need to use this syntax:
Output := CONCAT (Input 1, Input 2);
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program.

298

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

DELETE
Function Name

DELETE

Description

Removes a defined amount of characters from an input string and


outputs the remainder of the string.

Arguments

IN {STRING}
The IN input is a string input. It has a specified number of characters
removed by the DELETE function then its remaining characters are
used as the output.
L {INT}
The L input defines the number of characters that will be removed
from the IN input for the output string.
P {INT}
The P input defines the position of the character in the string where
the deletion starts (1 is the first character, 2 is the second character, 3
is the 3rd character and so on).
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is the characters remaining from the IN string (IN string - L
characters starting from P).

Examples:
Function Block Diagram - DELETE:

In this example, the IN is ALARMCONDITIONS, the L is 10, the P is 6 and so the output is
ALARM. 10 characters have been deleted from the 6th character (inclusive) onwards
CONDITIONS has been removed.
ST Program - DELETE:
To use a DELETE function in an ST program, you need to use this syntax:
Output := DELETE (IN, L, P);
Where Output, IN, L, and P are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := DELETE (IN:= 'ALARMCONDITIONS', L:= 10, P:= 6);
Where the 'ALARMCONDITIONS', 10 and 6 values are the input values (in this case, they are
the same values as used in the Function Block Diagram example above).

PD-6017 07/2012

299

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ELEMENT
Function Name

ELEMENT

Description

The ELEMENT function allows a Logic program to select parts of a


string and return the selected parts as a string value. For example, it
can be used to return the fourth value in a comma separated list.

Arguments

E {INTEGER}
E is the element number. This specifies the location of the string to be
extracted. 1 is the first string in the input string, 2 is the second string
in the input string and so on.
Input 1 {STRING}
Input 1 specifies the delimiter (the string that acts as the separator in
the full string input). For example, if the string input is a comma
separated list, Input 1 will be a comma character as the strings in the
input are separated by commas.
Input 2 {STRING}
Input 2 is the string input from which the ELEMENT output will be
taken. It consists of one or more values (each of which is also a string)
which are separated by a delimiter. Typically, the delimiter is a
comma, but it can be any character or characters.
D {INTEGER}
D is the Direction. This specifies the starting position - if D is 0, the
starting position is the left of the Input 2 string, which means that the
output will be calculated from the left-hand side of the string; if D is
any other number, the output is calculated from the right-hand side of
the string.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is the string that is at the defined position in the input
string (which contains many separated string values).

300

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Function Block Diagram - ELEMENT:

In this example, the ELEMENT function is used to return one string from a list of four. For the
example, the input string is a constant with four values, but you could just as easily map a
string containing values from a database to a string variable database item and use the string
variable as the source of the input.
The state of a digital point is used as the E input. An ADD function is used to add 1 to the
input as the digital point states begin at 0 whereas the element numbers begin at 1.
A string constant is used for IN1. It defines the delimiter as a comma.
A constant is used for the D input. As it is 0, the string position is calculated from the left of
the input string.
As the State direct variable is 1, the value for E is 2 (the ADD function adds an extra 1). This
means that the second string value in the string input will be returned. As D is 0, the second
string is counted from the left-hand side of the input string, and so the output of the
ELEMENT function is Slow.

PD-6017 07/2012

301

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

FIND
Function Name

FIND

Description

The FIND function searches for a specific string in a string input. If it


locates the specified string, it outputs a number that corresponds to
the starting position of the specified string within the input string. As
with the other string position numbers, 1 is the first character in the
string, 2 is the second, 3 is the third and so on.

Arguments

Input 1 {STRING}
This input is a string input. This is the string in which the FIND
function searches for the specified string.
Input 2 {STRING}
This input is also a string input and it is the specified string i.e. the
FIND function searches for an instance of the Input 2 string within the
Input 1 string.
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

Output {DINT}
The output is a number that identifies the starting position of the Input
2 string within the Input 1 string (1 is the first character in the string, 2
is the second, 3 is the third and so on). If the output is 0, the Input 2
string cannot be found within the Input 1 string.

Examples:
Function Block Diagram - FIND:

In this example, Input 1 is 'SENSOROVERRIDE' and Input 2 is 'OVERRIDE'. The FIND


function searches in the SENSOROVERIDE input for an instance of OVERRIDE. It locates an
instance of OVERRIDE starting at the seventh character in the SENSOROVERRIDE input,
and so the FIND function outputs 7.
ST Program - FIND:
To use a FIND function in an ST program, you need to use this syntax:
Output := FIND ('Input 1', 'Input 2');
Where Output, Input 1 and Input 2 are defined as variables earlier in the ST program.

302

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

INSERT
Function Name

INSERT

Description

Inserts one string into another string at a specified position, then


outputs the result.

Arguments

IN1 {STRING}
The IN1 string is the string that is used as the basis for the output.
The IN2 string is inserted into the string provided by the IN1 input.
IN2 {STRING}
The string that is inserted into the string provided by IN1.
P {INT}
Defines the insertion point in the IN1 string into which the IN2 string is
inserted. As with the other string position numbers, 1 is the first
character in the string, 2 is the second, 3 is the third and so on.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a string that is the result of the IN2 string being inserted
into the IN1 string at the position defined by P.

Examples:
Function Block Diagram - INSERT:

In this example, IN1 is 'ALARM', IN2 is 'OVERRIDDEN', and P is 6. The INSERT function
takes the 'ALARM' string and inserts the 'OVERRIDDEN' string into it at character 6. It then
outputs the resulting string which is ALARMOVERRIDDEN. In this case, the IN2 string has
been inserted at the end of the string by defining P as the number after the last character in
the IN1 string. If P had been set to 4, the output would have been 'ALAROVERRIDDENM'.
ST Program - INSERT:
To use an INSERT function in an ST program, you need to use this syntax:
Output := INSERT ('Input 1', 'Input 2', P);
Where Output, Input 1, Input 2, and P are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := INSERT (IN1:= 'ALARM', IN2:= 'OVERRIDDEN', P:= 6);
Where the 'ALARM', 'OVERRIDDEN', and 6 values are the input values (in this case, they are
the same values as used in the Function Block Diagram example above).

PD-6017 07/2012

303

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LEFT
Function Name

LEFT

Description

Outputs a specific number of characters taken from a string input.


The characters are taken from the left-hand side of the input string
(starting with the first character).

Arguments

IN {STRING}
The IN input is a string input. The LEFT function uses characters from
the IN input for its output.
L {INT}
Defines the number of characters in the IN input that are used for the
output. The output begins with the first character of the IN input and
continues for the L amount of characters.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a string that is the L number of characters from the IN
string, starting from the left.

Examples:
Function Block Diagram - LEFT:

In this example, the IN input is 'PIPELINE STRUCTURE FAILURE' and the L input is 18. This
means that the LEFT function will return 18 characters from the IN input, starting with the
left-most character (the first character). So, as the IN input is 'PIPELINE STRUCTURE
FAILURE', the LEFT function outputs 'PIPELINE STRUCTURE' (the first 18 characters from
the IN string).
ST Program - LEFT:
To use a LEFT function in an ST program, you need to use this syntax:
Output := LEFT ('IN', L);
Where Output, IN and L are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := LEFT (IN:= 'PIPELINE STRUCTURE FAILURE', L:= 18);
Where the 'PIPELINE STRUCTURE FAILURE' and 18 values are the input values (in this
case, they are the same values as used in the Function Block Diagram example above).

304

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

LEN
Function Name

LEN

Description

Outputs the total number of characters in the input string.

Arguments

Input 1 {STRING}
The input is a string input.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {INT}
The output is the total number of characters in the Input 1 string.

Examples:
Function Block Diagram - LEN:

In this example, the input is 'PIPELINE STRUCTURE FAILURE' and so the LEN output is 26
(there are 26 characters in the input string).
ST Program - LEN:
To use a LEN function in an ST program, you need to use this syntax:
Output := LEN ('Input 1');
Where Output and Input 1 are defined as variables earlier in the ST program.

PD-6017 07/2012

305

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

MID
Function Name

MID

Description

Outputs a specific number of characters taken from a string input.


The characters are taken from a specified position in the input string.

Arguments

IN {STRING}
The IN input is a string input. The MID function uses characters from
the IN input for its output.
L {INT}
Defines the number of characters in the IN input that are used for the
output.
P {INT}
Defines the starting point for the MID output. The starting point
corresponds to a character in the IN string and the MID output will
only include a specified number of characters from the starting point
onwards. As with the other string position numbers, 1 is the first
character in the string, 2 is the second, 3 is the third and so on.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a string that is the L number of characters taken from
the IN input from the P starting position.

Examples:
Function Block Diagram - MID:

In this example, the IN input is 'PIPELINE', the L input is 4 and the P input is 5. This means
that the MID function will return 4 characters from the IN input, starting from the fifth
character. So, as the IN input is 'PIPELINE', the MID function outputs 'LINE' (4 characters
from the IN input starting from the fifth character from the left).
ST Program - MID:
To use a MID function in an ST program, you need to use this syntax:
Output := MID ('IN', L, P);
Where Output, IN, L and P are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := MID (IN:= 'PIPELINE', L:= 4, P:=5);
Where the 'PIPELINE' 4 and 5 values are the input values (in this case, they are the same
values as used in the Function Block Diagram example above).

306

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

REPLACE
Function Name

REPLACE

Description

Outputs a specific number of characters taken from a string input.


The characters are taken from a specified position in the input string.

Arguments

IN1 {STRING}
The IN1 input is a string input. The REPLACE function uses
characters from the IN1 input for its output: it replaces characters
from the IN1 input with characters from the IN2 input.
IN2 {STRING}
The IN2 input is a string input. The REPLACE function uses
characters from the IN2 input for its output: it replaces characters
from the IN1 input with characters from the IN2 input.
L {INT}
Defines the number of characters in the IN1 input that are to be
replaced by the characters in the IN2 input.
P {INT}
Defines the starting point for the replacement i.e. the position in the
IN1 string where the IN2 characters will be inserted. As with the other
string position numbers, 1 is the first character in the string, 2 is the
second, 3 is the third and so on.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a string that is the IN1 string with a specified number of
its characters replaced by the characters in the IN2 string.

Examples:
Function Block Diagram - REPLACE:

In this example, the IN1 input is 'PIPELINE ALARM', IN2 is 'STATUS', L is 6 and P is 10. This
means that the REPLACE function will take the IN1 input, remove 6 characters from
character 10 onwards and replace them with 'STATUS'. This provides an output of
'PIPELINE STATUS'.

PD-6017 07/2012

307

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

ST Program - REPLACE:
To use a REPLACE function in an ST program, you need to use this syntax:
Output := REPLACE ('IN1','IN2', L, P);
Where Output, IN1, IN2, L and P are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := REPLACE (IN1:= 'PIPELINE ALARM', IN2:= 'STATUS' L:= 6,
P:=10);
Where the 'PIPELINE ALARM', 'STATUS', 6 and 10 values are the input values (in this case,
they are the same values as used in the Function Block Diagram example above).

308

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

RIGHT
Function Name

RIGHT

Description

Outputs a specific number of characters taken from a string input.


The characters are taken from the right-hand side of the input string
(ending with the last character).

Arguments

IN {STRING}
The IN input is a string input. The RIGHT function uses characters
from the IN input for its output.
L {INT}
Defines the number of characters in the IN input that are used for the
output. The output ends with the last character of the IN input and
starts the L number of characters prior to the end.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Output {STRING}
The output is a string that is the L number of characters from the IN
string, starting from the right.

Examples:
Function Block Diagram - RIGHT:

In this example, the IN input is 'PIPELINE STRUCTURE FAILURE' and the L input is 17. This
means that the RIGHT function will return 17 characters from the IN input, starting with the
right-most character (the last character). So, as the IN input is 'PIPELINE STRUCTURE
FAILURE', the RIGHT function outputs 'STRUCTURE FAILURE' (the last 17 characters from
the IN string).
ST Program - RIGHT:
To use a RIGHT function in an ST program, you need to use this syntax:
Output := RIGHT ('IN', L);
Where Output, IN and L are defined as variables earlier in the ST program.
Alternatively, you can use the following syntax:
Output := RIGHT (IN:= 'PIPELINE STRUCTURE FAILURE', L:= 17);
Where the 'PIPELINE STRUCTURE FAILURE' and 17 values are the input values (in this
case, they are the same values as used in the Function Block Diagram example above).

PD-6017 07/2012

309

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Misc
The following function blocks are categorized as miscellaneous:

SYSTEM (see page 311)

OPEN_PORT (see page 312)

OPEN_FILE (see page 313)

OPEN_FILE_EX (see page 314)

WRITE_FILE (see page 315)

WRITE_FILE_BYTE (see page 316)

CLOSE_FILE (see page 317)

EXECUTE_SQL (see page 318)

These function blocks are available from the Misc sub-menu on Function Block Diagrams.

310

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SYSTEM
Function Name

SYSTEM

Description

Allows an .exe file to be executed from a Logic program.


The SYSTEM function places each execute command in a list, with
the latest command being added to the bottom of the list. The
commands are executed in turn and can only be executed when the
previous command has been executed (if the command runs an
application, the application has to be closed before the next system
command is executed). For this reason, there can be delays between
the time a Logic program is run and the time the executable file is
executed (the command from the SYSTEM function is placed in a
queue).

Arguments

IN {STRING}
The IN input is a string that specifies the path to an executable file.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Executes the executable file at the location specified in the IN input. If


the .exe file cannot be found at the defined location, the SYSTEM
function will have no effect.

Examples:
Function Block Diagram - SYSTEM:

In this example, the IN input is 'C:\Windows\Nd.exe', so when the program executes, the Nd
application will run.
ATTENTION: Do not use SYSTEM to call interactive processes, such as running interactive
programs like Microsoft Notepad. Interactive processes only complete after the user closes
the application and so will prevent any other system commands from executing.
ST Program - SYSTEM:
To use a SYSTEM function in an ST program, you need to use this syntax:
VAR
A : DINT;
END_VAR
A := SYSTEM( 'C:\Windows\SetInstall.exe' );
The output of the SYSTEM function has to be stored as a variable (DINT). In this case, a
variable named A is used and the string for the SYSTEM's IN input is
'C:\Windows\SetInstall.exe'.

PD-6017 07/2012

311

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

OPEN_PORT
Function Name

OPEN_PORT

Description

Opens a serial port. When a port is open, data can be written to it by


using the WRITE_FILE function (see WRITE_FILE, on page 315).

Arguments

SPEC {STRING}
A string input that is a serial port specification, for example
'COM1,9600,8,N,1,NONE'.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

FileID {UDINT}
Returns the FileID of the file that is to be used when the port is writing
or closing.

Example:
ST Program - OPEN_PORT:
To use an OPEN_PORT function in an ST program, you need to use this syntax:
PORT := OPEN_PORT( 'COM1,9600,8,N,1,NONE' );

Where PORT is a variable declared earlier in the ST program.

312

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

OPEN_FILE
Function Name

OPEN_FILE

Description

Opens a file on disk in text mode. The file can be used to store a
value, text etc. When a file has been opened, data can be written to it
by using the WRITE_FILE function (see WRITE_FILE, on page 315).

Arguments

FILENAME {STRING}
The FILENAME string defines the name of the file that is to be
opened.
APPEND {BOOL}
Controls whether data is added to the end of the file (True) or the
existing data is overwritten (False).
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

FileID {UDINT}
Returns the FileID of the file. The FileID is used to identify the file
when writing and closing.

NOTE: You should only use the OPEN_FILE function in ST Programs.


Example:
ST Program - OPEN_FILE:
To use an OPEN_FILE function in an ST program, you need to use this syntax:
FileNumber := OPEN_FILE( FILENAME, APPEND );
Where FileNumber, FILENAME, and APPEND are variables that are declared earlier in the ST
program. The FILENAME variable has to be a string and the APPEND variable has to be a
Boolean. The FileNumber variable will be used to store the FileID that is returned when the
specified file is opened.

PD-6017 07/2012

313

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

OPEN_FILE_EX
Function Name

OPEN_FILE_EX

Description

Opens a file on disk in binary or text mode. The file can be used to
store a value, text etc. When a file has been opened, data can be
written to it by using the WRITE_FILE function (see WRITE_FILE, on
page 315) or WRITE_FILE_BYTE function (see WRITE_FILE_BYTE, on
page 316).

Arguments

FILENAME {STRING}
The FILENAME string defines the name of the file that is to be
opened.
APPEND {BOOL}
Controls whether data is added to the end of the file (True) or the
existing data is overwritten (False).
BINARY {BOOL}
Controls whether the file is opened in text mode (False) or binary
mode (True).
For more information on the data types for the inputs and outputs,

see Data Type Hierarchy, on page 392.


Returns

FileID {UDINT}
Returns the FileID of the file. The FileID is used to identify the file
when writing and closing.

NOTE: You should only use the OPEN_FILE_EX function in ST Programs.


Example:
ST Program - OPEN_FILE_EX:
To use an OPEN_FILE_EX function in an ST program, you need to use this syntax:
FileNumber := OPEN_FILE_EX( FILENAME, APPEND, BINARY );
Where FileNumber, FILENAME, APPEND, and BINARY are variables that are declared earlier
in the ST program. The FILENAME variable has to be a string, and the APPEND and BINARY
variables have to be Booleans. The FileNumber variable will be used to store the FileID that
is returned when the specified file is opened.

314

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

WRITE_FILE
Function Name

WRITE_FILE

Description

Allows data to be written to an open file or serial port. When the data
has been written, the file or port needs to be closed by using the
CLOSE_FILE function (see CLOSE_FILE, on page 317).
If the data needs to contain a 0 byte, you should use
WRITE_FILE_BYTE instead (see WRITE_FILE_BYTE, on page 316).

Arguments

FILEID {UDINT}
The FILEID is a number that identifies the file or port to which data is
to be written.
DATA {STRING}
The data that is to be written to the file or serial port.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Zero {UDINT}
The WRITE_FILE function returns zero.

NOTE: You should only use the WRITE_FILE function in ST Programs.


Example:
ST Program - WRITE_FILE:
To use a WRITE_FILE function in an ST program, you need to use this syntax:
WriteExport := WRITE_FILE( FILEID, DATA );

Where WriteExport, FILEID, and DATA are variables that are declared earlier in the ST
program. The FILEID variable has to be a UDINT and identifies the file or port to which the
data is to be written and the DATA string is the actual data that is written.The WriteExport
variable will store the value that is returned by the WRITE_FILE function.
A common use for the WRITE_FILE function is to provide a serial ASCII export process. To
achieve this, an OPEN_PORT function is used to open a serial port and then a WRITE_FILE
function is used to write data to the port:
FileId := OPEN_PORT('COM1,9600,8,N,1,NONE');
ErrorCode := WRITE_FILE(FileId, WriteString);
FileId := CLOSE_FILE(FileId);
In this code, the ST Program opens the defined COM port and then performs a WRITE_FILE
function. The WRITE_FILE function writes the string that is stored in the WriteString variable
to the port (the FileId in the WRITE_FILE function declaration corresponds to the FileId that
is returned by the OPEN_PORT function. When the string has been written to the port, the
CLOSE_FILE function is used to close the port. This allows data stored in a string to be
written to a serial port so that it can be accessed by other applications etc.

PD-6017 07/2012

315

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

WRITE_FILE_BYTE
Function Name

WRITE_FILE_BYTE

Description

Allows data (single byte) to be written to an open file or serial port.


When the data has been written, the file or port needs to be closed by
using the CLOSE_FILE function (see CLOSE_FILE, on page 317).
Unlike WRITE_FILE, WRITE_FILE_EX allows a single byte to be
written.

Arguments

FILEID {UDINT}
The FILEID is a number that identifies the file or port to which data is
to be written.
DATA {BYTE}
The data that is to be written to the file or serial port.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Zero {UDINT}
The WRITE_FILE_BYTE function returns zero.

NOTE: You should only use the WRITE_FILE_BYTE function in ST Programs.


Example:
ST Program - WRITE_FILE_BYTE:
To use a WRITE_FILE_BYTE function in an ST program, you need to use this syntax:
WriteExport := WRITE_FILE_BYTE( FILEID, DATA );

Where WriteExport, FILEID, and DATA are variables that are declared earlier in the ST
program. The FILEID variable has to be a UDINT and identifies the file or port to which the
data is to be written and the DATA variable is the data that is written. The DATA has to be
a byte data type, for example, 16xFF. The WriteExport variable will store the value that is
returned by the WRITE_FILE_BYTE function.
A common use for the WRITE_FILE_BYTE function is to provide a serial ASCII export
process. To achieve this, an OPEN_PORT function is used to open a serial port and then a
WRITE_FILE_BYTE function is used to write data to the port:
FileId := OPEN_PORT('COM1,9600,8,N,1,NONE');
ErrorCode := WRITE_FILE_BYTE(FileId, WriteValue);
FileId := CLOSE_FILE(FileId);
In this code, the ST Program opens the defined COM port and then performs a
WRITE_FILE_BYTE function. The WRITE_FILE_BYTE function writes the value that is stored
in the WriteValue variable to the port (the FileId in the WRITE_FILE_BYTE function
declaration corresponds to the FileId that is returned by the OPEN_PORT function). When
the string has been written to the port, the CLOSE_FILE function is used to close the port.
This allows byte data types to be written to a serial port so that they can be accessed by
other applications etc.

316

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

CLOSE_FILE
Function Name

CLOSE_FILE

Description

Closes an open file or serial port. The CLOSE_FILE should be used


after data has been written to a file or serial port.

Arguments

FILEID {UDINT}
The FILEID is a number that identifies the file or port that is to be
closed.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Zero {UDINT}
The CLOSE_FILE function returns zero.

NOTE: You should only use the CLOSE_FILE function in ST Programs.


Example:
ST Program - CLOSE_FILE:
To use a CLOSE_FILE function in an ST program, you need to use this syntax:
ClosePort := CLOSE_FILE(FILEID);

Where ClosePort and FILEID are variables that are declared earlier in the ST program. The
FILEID variable has to be a UDINT and identifies the file or port that is to be closed. The
ClosePort variable is a UDINT and stores the zero that is returned by the CLOSE_FILE
function.
For an example of the CLOSE_FILE function being used in an ST Program, refer to the
example in WRITE_FILE (see page 315).

PD-6017 07/2012

317

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

EXECUTE_SQL
Function Name

EXECUTE_SQL

Description

Executes an SQL Query. The SQL Query is executed at the end of the
Logic program execution process, during the write outputs phase.

Arguments

SQL {STRING}
The SQL is a valid SQL Query statement.
For more information on the data types for the inputs and outputs,
see Data Type Hierarchy, on page 392.

Returns

Boolean.
The SQL executes at the end of the Logic program and the success
(True) or failure (FALSE) of the SQL statement is not available to the
Logic program.

The preferred way of inserting, updating or deleting data via SQL from Logic is to use the
%D in the variable syntax (see Inserting, Updating, and Deleting Values by Using SQL in
an ST Program, on page 116).
EXECUTE_SQL is deprecated and is retained for backward compatibility only.

318

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Built-In Function Blocks


ClearSCADA includes built-in function blocks that you can use in your Logic programs.
The built-in function blocks are available in Function Block Diagrams and ST programs
and are categorized as:

Counters (see page 319)

CTD (see page 320)

CTU (see page 323)

CTUD (see page 326)

State Change Detectors (see page 330)

F_TRIG (see page 330)

R_TRIG (see page 332)

Set and Reset Bistables (see page 334)

RS (see page 334)

SR (see page 337)

Timers (see page 339)

TOF (see page 339)

TON (see page 341)

TP (see page 344)

Counters
The following counter function blocks provide incremental and decremental counters:

PD-6017 07/2012

CTD (see page 320)Decremental counter

CTU (see page 323)Incremental counter

CTUD (see page 326)Incremental and decremental counter.

319

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

CTD
Function Block
Name

CTD

Description

CTD is a down counter function block and it is typically used to


indicate when a count has decreased to a minimum value.

Arguments

CD {BOOL}
Determines when the counter decreases. The counter will go down by
1 when the CD input changes from False to True. The counter does
not change again until the CD input changes from True to False and
then back to True. The counter is only affected by the CD input
changing from False to True.
If the counter reaches the number specified by the PV input, the
counter will no longer decrease, even if the CD input continues to
change from False to True.
LD {BOOL}
Indicates whether there is a Load. If the LD value is True, the CV
output is set to the preset value (PV) irrespective of the count; if the
LD value is False, the CV output has a value that corresponds to the
number of times the CD value has changed.
PV {INT}
This is an integer input that defines the starting number for the
counter.

Returns

Q {BOOL}
The Q output defines whether the count is active or inactive. If the CV
output is greater than 0, the Q output is False and the counting is
active; if the CV output reaches 0, the Q output is True and the
counting stops.
CV {INT}
The CV output is the value of the counter. It decreases by 1 each time
the CD input changes from False to True.
The CV output begins as the same number as the PV input. It can
decrease until it reaches 0, at which point the Q output becomes True
and the counting stops.

320

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - CTD Function Block Diagram:
In this Function Block Diagram, the LD output begins as True, and so the CV output is set to
be the same as the PV input of 10. The LD output then becomes False and so the counting
begins (as the CV output can now be affected by the CD input). The CD input changes from
True to False and then back to True again. This causes the CV output to decrease by 1 as the
CD input has changed from False to True once. The Q output remains as False as the CV
output is above 0. The Q output will only change to True when the CD input has changed
from False to True a further 9 times (reducing the CV output to 0). When the Q output
changes to True, the counting stops.

Example - CTD ST Program:


The syntax for entering a CTD function block in an ST program is:
VAR
CD_IN AT %M(.Digital Point1): BOOL;
LD_IN: AT %M(.Digital Point2): BOOL;
END_VAR
VAR
PV_IN: INT;
Q_OUT: BOOL;
CV_OUT: INT;
FB : CTD;
END_VAR

FB( CD := CD_IN, LD := LD_IN, PV := PV_IN, Q := Q_OUT, CV := CV_OUT


);
The direct variables are declared in a separate VAR block to the internal variables. The input
and output variables for the CTD function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the CD input variable is named CD_IN). In this
example, the direct variables for the CD and LD inputs (CD_IN and LD_IN) reference digital
points (the Boolean values for these inputs are taken from digital points in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.

PD-6017 07/2012

321

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( CD := CD_IN, LD := LD_IN, PV := PV_IN, Q := Q_OUT, CV := CV_OUT
);
So, the ST Program uses the CD_IN input as the CD input for the FB function block (which
has already been declared as a CTD type). For the LD input, it uses the LD_IN variable, and
for the PV input it uses the PV_IN variable. For its outputs, it uses the Q_OUT variable for the
Q output and the CV_OUT variable for the CV output.

322

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

CTU
Function Block
Name

CTU

Description

CTU is an up counter function block and it is typically used to indicate


when a count has increased to a maximum value.

Arguments

CU {BOOL}
Determines when the counter increases. The counter will go up by 1
when the CU input changes from False to True. The counter does not
change again until the CU input changes from True to False and then
back to True. The counter is only affected by the CU input changing
from False to True.
If the counter reaches the number specified by the PV input, the
counter will no longer increase, even if the CU input continues to
change from False to True.
R {BOOL}
Indicates whether there is a reset. If the R value is True, the CV output
is set to 0 irrespective of the count; if the R value is False, the CV
output has a value that corresponds to the number of times the CU
value has changed.
PV {INT}
This is an integer input that defines the maximum number for the
counter.

Returns

Q {BOOL}
The Q output defines whether the count is active or inactive. If the CV
output is less than the PV number, the Q output is False and the
counting is active; if the CV output reaches the PV number, the Q
output is True and the counting stops.
CV {INT}
The CV output is the value of the counter. It increases by 1 each time
the CU input changes from False to True.
The CV output begins at 0. It can increase until it reaches the PV
value, at which point the Q output becomes True and the counting
stops.

PD-6017 07/2012

323

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - CTU Function Block Diagram:
In this Function Block Diagram, the R output begins as True, and so the CV output is set to 0.
The R output then becomes False and so the counting begins (as the CV output can now be
affected by the CU input). The CU input changes from False to True. This causes the CV
output to increase by 1 as the CU input has changed from False to True once. The Q output
remains as False as the CV output is less than the PV input. The Q output will only change to
True when the CU input has changed from False to True a further 9 times (increasing the CV
output to 10). When the Q output changes to True, the counting stops.

Example - CTU ST Program:


The syntax for entering a CTU function block in an ST program is:
VAR
CU_IN AT %M(.Digital Point1): BOOL;
R_IN: AT %M(.Digital Point2): BOOL;
END_VAR
VAR
PV_IN: INT;
Q_OUT: BOOL;
CV_OUT: INT;
FB : CTU;
END_VAR

FB( CU := CU_IN, R := R_IN, PV := 10, Q := Q_OUT, CV := CV_OUT );


The direct variables are declared in a separate VAR block to the internal variables. The input
and output variables for the CTU function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the CU input variable is named CU_IN). In this
example, the direct variables for the CU and R inputs (CU_IN and R_IN) reference digital
points (the Boolean values for these inputs are taken from digital points in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.

324

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( CU := CU_IN, R := R_IN, PV := 10, Q := Q_OUT, CV := CV_OUT );
So, the ST Program uses the CU_IN input as the CU input for the FB function block (which
has already been declared as a CTU type). For the R input, it uses the R_IN variable, and for
the PV input it uses the value 10. For its outputs, it uses the Q_OUT variable for the Q output
and the CV_OUT variable for the CV output.

PD-6017 07/2012

325

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

CTUD
Function Block
Name

CTUD

Description

CTUD is an up and down counter function block and it is typically


used to indicate when a count has decreased to 0 or increased to a
specified maximum number.

Arguments

CU {BOOL}
Determines when the counter increases. The counter will go up by 1
when the CD input changes from False to True. The counter does not
increase again until the CD input changes from True to False and then
back to True (although it may decrease, if the CD input changes from
False to True). The counter is only affected by the CD input changing
from False to True.
If the counter reaches the number specified by the PV input, the
counter will no longer increase, even if the CD input continues to
change from False to True.
CD {BOOL}
Determines when the counter decreases. The counter will go down by
1 when the CD input changes from False to True. The counter does
not decrease again until the CD input changes from True to False and
then back to True (although it may increase if the CU input changes
from False to True). The counter is only affected by the CD input
changing from False to True.
If the counter reaches 0, it will no longer decrease, even if the CD
input continues to change from False to True.
R {BOOL}
Indicates whether there is a reset. If the R value is True, the CV output
is set to 0 irrespective of the count; if the R value is False, the CV
output has a value that corresponds to the number of times the CU
and CD values have changed.
LD {BOOL}
Indicates whether there is a Load. If the LD value is True, the CV
output is set to the same value as PV irrespective of the count; if the
LD value is False, the CV output has a value that corresponds to the
number of times the CU and CD values have changed.
PV {INT}
This is an integer input that defines the maximum number for the
counter.

326

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Returns

QU {BOOL}
The QU output defines whether the up count is active or inactive. If
the CV output is less than the PV number, the Q output is False and
the counting is active; if the CV output reaches the PV number, the
QU output is True and the counting up stops.
QD {BOOL}
The QD output defines whether the down count is active or inactive. If
the CV output is greater than 0, the QD output is False and the
counting is active; if the CV output reaches 0, the QD output is True
and the counting down stops.
CV {INT}
The CV output is the value of the counter. It increases by 1 each time
the CU input changes from False to True and decreases by 1 when
the CD input changes from False to True.
The CV is set to 0 when the R input is True and is set to the same
number as the PV input when the LD input is True.

PD-6017 07/2012

327

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - CTUD Function Block Diagram:

In this Function Block Diagram, we assume that the CV counter begins at 0 following the R
input being True. The R input then changes to False and the CU input changes from False to
True (as shown). This causes the CV value to increase by 1. The QU and QD outputs remain
as False as the CV value is greater than 0 and less than the PV value.
The CD input changes from False to True. This makes the CV counter decrease by 1 and so
it returns to 0. As the CV value is 0, the QD output changes to True.

Example - CTUD ST Program:


The syntax for entering a CTUD function block in an ST program is:
VAR
CU_IN AT %M(.Digital Point1): BOOL;
CD_IN: AT %M(.Digital Point2): BOOL;
R_IN: AT %M(.Digital Point3): BOOL;
LD_IN: AT %M(.Digital Point4): BOOL;
END_VAR
VAR
PV_IN: INT;
QU_OUT: BOOL;
QD_OUT: BOOL;
CV_OUT: INT;
FB : CTUD;
END_VAR

FB( CU := CU_IN, CD := CD_IN, R := R_IN, LD := LD_IN, PV := 10, QU :=


QU_OUT, QD := QD_OUT, CV := CV_OUT );

328

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

The direct variables are declared in a separate VAR block to the internal variables. The input
and output variables for the CTUD function block are also allocated names that are different
to the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the CD input variable is named CD_IN). In this
example, the direct variables for the CU, CD, R and LD inputs (CU_IN, CD_IN, R_IN and
LD_IN) reference digital points (the Boolean values for these inputs are taken from digital
points in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( CU := CU_IN, CD := CD_IN, R := R_IN, LD := LD_IN, PV := 10, QU :=
QU_OUT, QD := QD_OUT, CV := CV_OUT );
So, the ST Program uses:

The CU_IN input as the CU input

The CD_IN input as the CD input

The R_IN input as the R input

The LD_IN input as the LD input

10 as the PV input.

The FB declaration sets the ST program to use a CTUD type of function block.
For the outputs, the ST program uses the QU_OUT variable for the QU output, the QD_OUT
variable for the QD output, and the CV_OUT variable for the CV output.

PD-6017 07/2012

329

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

State Change Detectors


There are 2 types of built-in function blocks for detecting changes of state:

F_TRIG (see page 330)

R_TRIG (see page 332).

F_TRIG
Function Block
Name

F_TRIG

Description

F_TRIG is an edge detection function block. It detects a change in the


state of a Boolean input. The output from an F_TRIG function block
produces a pulse when True.

Arguments

CLK {BOOL}
When the CLK input changes from True to False, the Q output
changes to True for one execution of the function block. The Q output
then returns to being False until the CLK input changes from True to
False again.

Returns

Q {BOOL}
The Q output changes state according to the CLK input. When the
CLK input changes from True to False, the Q output becomes True. It
remains True for one execution of the F_TRIG function block and then
returns to being False.

Examples:
Example - F_TRIG Function Block Diagram:

In this example, the CLK input comes from a digital point named 'PressureAlert'. The CLK
input changes from True to False causing the Q output to change from False to True. The Q
output remains True for one execution of the function block and then returns to being False.

330

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Example - F_TRIG ST Program:


The syntax for entering an F_TRIG function block in an ST program is:
VAR
CLK_IN AT %M(.Digital Point1): BOOL;
END_VAR
VAR
Q_OUT: BOOL;
FB : F_TRIG;
END_VAR
FB( CLK := CLK_IN, Q => Q_OUT);
The direct variable is declared in a separate VAR block to the indirect variables. The input
and output variables for the F_TRIG function block are also allocated names that are
different to the names of the inputs and outputs in the function block as this makes it easier
to understand the ST program (for example, the CLK input variable is named CLK_IN). In this
example, the direct variable for the CLK input (CLK_IN) references a digital point (the
Boolean value for the input is taken from a digital point in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( CLK := CLK_IN, Q => Q_OUT);

So, the ST Program uses the CLK_IN input as the CLK input for the FB function block
(which has already been declared as an F_TRIG type). For the Q output, it uses the
Q_OUT variable.

PD-6017 07/2012

331

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

R_TRIG
Function Block
Name

R_TRIG

Description

R_TRIG is an edge detection function block. It detects a change in


the state of a Boolean input. The output from an F_TRIG function
block produces a pulse when True.

Arguments

CLK {BOOL}
When the CLK input changes from False to True, the Q output
changes to True for one execution of the function block. The Q output
then returns to being False until the CLK input changes from False to
True again.

Returns

Q {BOOL}
The Q output changes state according to the CLK input. When the
CLK input changes from False to True, the Q output becomes True. It
remains True for one execution of the R_TRIG function block and then
returns to being False.

Examples:
Example - R_TRIG Function Block Diagram:

In this example, the CLK input comes from a digital point named 'PressureAlert'. The CLK
input changes from False to True causing the Q output to change from False to True. The Q
output remains True for one execution of the function block and then returns to being False.
Example - R_TRIG ST Program:
The syntax for entering an R_TRIG function block in an ST program is:
VAR
CLK_IN AT %M(.Digital Point1): BOOL;
END_VAR
VAR
Q_OUT: BOOL;
FB : R_TRIG;
END_VAR
FB( CLK := CLK_IN, Q => Q_OUT);

332

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

The direct variable is declared in a separate VAR block to the indirect variables. The input
and output variables for the R_TRIG function block are also allocated names that are
different to the names of the inputs and outputs in the function block as this makes it easier
to understand the ST program (for example, the CLK input variable is named CLK_IN). In this
example, the direct variable for the CLK input (CLK_IN) references a digital point (the
Boolean value for the input is taken from a digital point in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( CLK := CLK_IN, Q => Q_OUT);

So, the ST Program uses the CLK_IN input as the CLK input for the FB function block
(which has already been declared as an R_TRIG type). For the Q output, it uses the
Q_OUT variable.

PD-6017 07/2012

333

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Set and Reset Bistables


The Set-Reset and Reset-Set bistables are useful function blocks as they allow an output
state to be determined by the states of two inputs. This is especially useful for providing
push button functionality, for example, an SR function block can be used to provide the
functionality for start and stop buttonsthe output of the SR function block is dependent
on whether the input is true for the start button, the stop button, or both.
There are 2 Set and Reset bistables:

RS (see page 334)The Reset input is dominant in the RS function block.

SR (see page 337)The Set input is dominant in the SR function block.

RS
Function Block
Name

RS

Description

RS is a reset latch where the Reset is dominant over the Set. It can be
used to determine the state of a Boolean output based on the states
of 2 Boolean inputs.

Arguments

S {BOOL}
The Set input S only affects the Q1 output when the R1 input is False.
If the S input changes from False to True and the R1 input is False,
the change to the S input will cause the Q1 output to become True.
The Q1 output will then stay True until the R1 state changes; Q1 will
not respond to the S input changing state again until R1 has become
True and then changed to False again.
R1 {BOOL}
The Reset input R1 is dominant in the RS function block. When its
input is True, the Q1 output is False; when the R1 input is False, the
value of the Q1 output is dependent on the S input.

Returns

Q1 {BOOL}
The Q1 output is True when the R1 input is True. When the R1 input is
False, the Q1 input can respond to the S input:

334

If the S input changes from False to True and the R1 input is


False, the Q1 output becomes True.

If the S input changes from True to False while the R1 input is


False, the Q1 output remains True.

If the R1 input is True, the Q1 output is False irrespective of the


state of S.

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - RS Function Block Diagram:

It is easier to understand the functionality of the RS function block if you imagine the S and
R1 inputs as corresponding to power buttons, and the Q1 output as the result of those
buttons being pressed.
The S input receives its value from a point that represents a 'power on' button on plant; the
R1 input receives its value form a point representing the 'power off' button.The True state
corresponds to the buttons being pressed (active) and the False state corresponds to the
buttons not being pressed (inactive).
The power on button is pressed (S is True) and the power off button is not pressed (R1 is
False), so the power is on (Q1 is True). As the power on button cannot turn the power off,
further changes to the S input will not affect the output (as long as R1 remains False). The
power remains on until the off button is pressed (Q1 remains True until R1 becomes True).
When the power off button is pressed (R1 becomes True), the output becomes False (the
power is off). The output will remain False until the R1 input changes to False (the power off
button is not pressed) and the S input is True (the power on button is pressed).
If both buttons are pressed at the same time (S and R1 are both True), the R1 input is
dominant and so the power is off (Q1 is False).

PD-6017 07/2012

335

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Example - RS ST Program:
The syntax for entering an RS function block in an ST program is:
VAR
S_IN AT %M(.Digital Point1): BOOL;
R1_IN AT %M(.Digital Point2): BOOL;
END_VAR
VAR
Q1_OUT: BOOL;
FB : RS;
END_VAR
FB( S := S_IN, R1 := R1_IN, Q1:= Q1_OUT );

The direct variables are declared in a separate VAR block to the indirect variables. The input
and output variables for the RS function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the R1 input variable is named R1_IN). In this
example, the direct variables for the S input (S_IN) and R1 input (R1_IN) reference digital
points (the Boolean values for the inputs are taken from digital points in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( S := S_IN, R1 := R1_IN, Q1 := Q1_OUT );

So, the ST Program uses the S_IN input as the S input for the FB function block (which
has already been declared as an RS type). It uses the R1_IN variable as the value for the
R1 input and for the Q1 output it uses the Q1_OUT variable.

336

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

SR
Function Block
Name

SR

Description

SR is a reset latch where the Set is dominant over the Reset. It can be
used to determine the state of a Boolean output based on the states
of 2 Boolean inputs.

Arguments

S1 {BOOL}
The Set input S1 is dominant in the SR function block. When its input
is True, the Q1 output is True; when the S1 input is False, the value of
the Q1 output is dependent on the R input.
R {BOOL}
The Reset input R only affects the Q1 output when the S1 input is
False. If the R input changes from False to True and the S1 input is
False, the change to the R input will cause the Q1 output to become
True. The Q1 output will then stay True until the S1 state changes; Q1
will not respond to the R input changing state again until S1 has
become True and then changed to False again.

Returns

Q1 {BOOL}
The Q1 output is True when the S1 input is True. When the S1 input is
False, the Q1 input can respond to the R input:

If the R input changes from False to True and the S1 input is


False, the Q1 output becomes True.

If the R input changes from True to False while the S1 input is


False, the Q1 output remains True.

If the S1 input is True, the Q1 output is True irrespective of the


state of R.

Examples:
Example - SR Function Block Diagram:

It is easier to understand the functionality of the SR function block if you imagine the S1 and
R inputs as corresponding to power buttons, and the Q1 output as the result of those
buttons being pressed.
The S1 input receives its value from a point that represents a 'power on' button on plant; the
R input receives its value form a point representing the 'power off' button.The True state
corresponds to the buttons being pressed (active) and the False state corresponds to the
buttons not being pressed (inactive).
The power on button is pressed (S1 is True) and the power off button is not pressed (R1 is
False), so the power is on (Q1 is True). As the power on button cannot turn the power off,
further changes to the S1 input will not affect the output (as long as R remains False). The
power remains on until the power on button is no longer pressed (S1 is False) and the power
off button is pressed (R is True). This means that Q1 remains True until S1 becomes False
and R becomes True.

PD-6017 07/2012

337

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

The power on button is no longer pressed and so S1 becomes False. Both S1 and R are
False as neither button has been pressed and the Q1 output is True as the S1 input was
previously True.
As both inputs are False, pressing the power off button sets the Q1 output to False as the R
input only has an effect when the S1 input is False.
If both buttons are pressed at the same time (S1 and R are both True), the S1 input is
dominant and so the power is on (Q1 is True).

Example - SR ST Program:
The syntax for entering an SR function block in an ST program is:
VAR
S1_IN AT %M(.Digital Point1): BOOL;
R_IN AT %M(.Digital Point2): BOOL;
END_VAR
VAR
Q1_OUT: BOOL;
FB : SR;
END_VAR
FB( S1 := S1_IN, R := R_IN, Q1:= Q1_OUT );

The direct variables are declared in a separate VAR block to the indirect variables. The input
and output variables for the SR function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the R input variable is named R_IN). In this
example, the direct variables for the S1 input (S1_IN) and R input (R_IN) reference digital
points (the Boolean values for the inputs are taken from digital points in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( S1 := S1_IN, R := R_IN, Q1 := Q1_OUT );

So, the ST Program uses the S1_IN input as the S1 input for the FB function block (which
has already been declared as an SR type). It uses the R_IN variable as the value for the R
input and for the Q1 output it uses the Q1_OUT variable.

338

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Timers
The timer function blocks are useful when you need an output to be dependent on the
state of an input, but also require a delay. Delays with state changes are often needed
when the communications equipment is known to be unreliable, for example, when you
know that sensors sometimes report incorrect states due to signal interference.
There are 2 types of built-in timer function block:

TOF (see page 339)A false output is delayed by a specified amount of time.

TON (see page 341)A true output is delayed by a specified amount of time.

TP (see page 344)A pulse is output for a specified time.

TOF
Function Block
Name

TOF

Description

Sets an output to False after a specified time delay. This is useful


when the input signals are unreliable due to interference etc. By
having a delay, you can stop fluctuating input values from affecting
the outputa True input will set the Q output to True immediately, but
a False input will have to remain False for a set time before it causes
the Q output to become False.

Arguments

IN {BOOL}
When the IN input changes to False, the timer ET begins to increase.
The output remains True until the ET time reaches the time limit
defined by the PT input. When the ET time reaches the PT time, the
output changes to False (only if the IN input is still False).
PT {TIME}
The PT input defines the amount of time for the delay. The output
cannot change to False unless the IN input is False for the PT time.

Returns

Q {BOOL}
The Q Boolean output is True whenever the IN input is True. If the IN
input changes to False, the Q output remains True until the ET time
has reached the limit defined by the PT time. If the IN input is still
False then the ET time reaches the PT time, the Q output changes to
False.
ET {TIME}
The ET time counter begins when the IN input changes from True to
False. It increases towards the time limit defined by the PT input.
When it reaches the PT limit, the ET counter stops and the output
either changes or remains the same (depending on whether the IN
input is still False).

PD-6017 07/2012

339

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - TOF Function Block Diagram:

The POWER Boolean provides the input for IN. It begins as False and then changes to True
which causes the Q output to change to True. The IN input then changes to False, and the
ET counter begins to count up to the amount of time defined by the PT input (in this case, 30
seconds). After 15 seconds, the IN input changes back to True. When the ET counter
reaches 30 seconds, the Q output remains True as the IN input was not continuously False
for 30 seconds.
The IN input changes from True to False again. As before, the ET counter starts to increase
from 1s upwards towards 30 seconds. During this time, the IN input remains False. When
the ET counter reaches 30s, the Q output changes to False as the IN input has been False
for over 30 seconds.
Example - TOF ST Program:
The syntax for entering a TOF function block in an ST program is:
VAR
IN_IN AT %M(.Digital Point1): BOOL;
END_VAR
VAR
PT_IN: TIME;
Q_OUT: BOOL;
ET_OUT: TIME;
FB : TOF;
END_VAR
FB( IN := IN_IN, PT := PT_IN, Q => Q_OUT, ET => ET_OUT );
The direct variable is declared in a separate VAR block to the indirect variables. The input
and output variables for the TOF function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the PT input variable is named PT_IN). In this
example, the direct variable for the IN input (IN_IN) references a digital point (the Boolean
value for the input is taken from a digital point in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( IN := IN_IN, PT := PT_IN, Q => Q_OUT, ET => ET_OUT );
So, the ST Program uses the IN_IN input as the IN input for the FB function block (which has
already been declared as a TOF type). The PT input is provided by the PT_IN variable, the Q
output is stored by the Q_OUT variable, and the ET output is stored by the ET_OUT variable.

340

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

TON
Function Block
Name

TON

Description

Sets an output to True after a specified time delay. This is useful when
the input signals are known to be unreliable, for example, when input
signals are affected by interference. By having a delay, you can stop
fluctuating input values from affecting the outputa False input will
set the Q output to False immediately, but a True input will have to
remain True for a set time before it causes the Q output to become
True.

Arguments

IN {BOOL}
When the IN input changes to True, the timer ET begins to increase.
The output remains False until the ET time reaches the time limit
defined by the PT input. When the ET time reaches the PT time, the
output changes to True (only if the IN input is still True).
PT {TIME}
The PT input defines the amount of time for the delay. The output
cannot change to True unless the IN input is True for the PT time.

Returns

Q {BOOL}
The Q Boolean output is False whenever the IN input is False. If the IN
input changes to True, the Q output remains False until the ET time
has reached the limit defined by the PT time. If the IN input is still True
then the ET time reaches the PT time, the Q output changes to True.
ET {TIME}
The ET time counter begins when the IN input changes from False to
True. It increases towards the time limit defined by the PT input. When
it reaches the PT limit, the ET counter stops and the output either
changes or remains the same (depending on whether the IN input is
still True).

NOTE: When using TON, you should have the execution set to an interval so that the
program re-executes and re-evaluates the condition of the timer. TON timers do not function
as a SLEEP or WAIT type command.

PD-6017 07/2012

341

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Examples:
Example - TON Function Block Diagram:

The ShutDown Boolean provides the input for IN. It begins as True and then changes to
False which causes the Q output to change to False. The IN input then changes to True, and
the ET counter begins to count up to the amount of time defined by the PT input (in this
case, 30 seconds). After 15 seconds, the IN input changes back to False. When the ET
counter reaches 30 seconds, the Q output remains False as the IN input was not
continuously True for 30 seconds.
The IN input changes from False to True again. As before, the ET counter starts to increase
from 1s upwards towards 30 seconds. During this time, the IN input remains True. When the
ET counter reaches 30s, the Q output changes to True as the IN input has been True for over
30 seconds.

342

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Example - TON ST Program:


The syntax for entering a TON function block in an ST program is:
VAR
IN_IN AT %M(.Digital Point1): BOOL;
END_VAR
VAR
PT_IN: TIME;
Q_OUT: BOOL;
ET_OUT: TIME;
FB : TON;
END_VAR
FB( IN := IN_IN, PT := PT_IN, Q => Q_OUT, ET => ET_OUT );
The direct variable is declared in a separate VAR block to the indirect variables. The input
and output variables for the TON function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the PT input variable is named PT_IN). In this
example, the direct variable for the IN input (IN_IN) references a digital point (the Boolean
value for the input is taken from a digital point in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( IN := IN_IN, PT := PT_IN, Q => Q_OUT, ET => ET_OUT );
So, the ST Program uses the IN_IN input as the IN input for the FB function block (which has
already been declared as a TON type). The PT input is provided by the PT_IN variable, the Q
output is stored by the Q_OUT variable, and the ET output is stored by the ET_OUT variable.

PD-6017 07/2012

343

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

TP
Function Block
Name

TP

Description

Sets an output to True for a defined time duration. This is useful when
a change in state needs to be indicated for a set amount of time, for
example, a pulse timer could be used to activate alarm sirens on site
for 10 minutes.

Arguments

IN {BOOL}
When the IN input changes from False to True, the timer ET begins to
increase. The Q output remains True until the ET time reaches the
time limit defined by the PT input. When the ET time reaches the PT
time, the output changes to False even if the IN input remains True.
PT {TIME}
The PT input defines the amount of time for the delay. The output
changes to True for the PT time and then reverts to False.

Returns

Q {BOOL}
The Q output is True whenever the IN input changes from False to
True. The output remains True until the ET counter reaches the time
specified by the PT input (at which point it reverts to False).
The Q output can be False even if the IN input is Truethe output will
only be True for the PT time. When the PT time has expired, the Q
output reverts to False even if the IN input remains True. In this
situation, the Q output would not become True again unless the IN
input changes from True to False and then back to True again.
ET {TIME}
The ET time counter begins when the IN input changes from False to
True. It increases towards the time limit defined by the PT input. When
it reaches the PT limit, the ET counter stops and the output reverts to
False. The ET counter then resets to 0.

NOTE: When using TP, you should have the execution set to an interval so that the program
re-executes and re-evaluates the condition of the timer. TP timers do not function as a
SLEEP or WAIT type command.
Examples:
Example - TP Function Block Diagram:

The ShutDown Boolean provides the input for IN. It begins as False and then changes to
True which causes the Q output to change to True. This starts the ET counter which begins
to count up to the amount of time defined by the PT input (in this case, 30 seconds). After 30
seconds, the Q output changes back to False and the ET counter resets to 0. The Q output
will not change from False to True again until the IN input changes from True to False and
then back to True (the output only changes when the IN input changes from False to True).

344

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Example - TP ST Program:
The syntax for entering a TP function block in an ST program is:
VAR
IN_IN AT %M(.Digital Point1): BOOL;
END_VAR
VAR
PT_IN: TIME;
Q_OUT: BOOL;
ET_OUT: TIME;
FB : TP;
END_VAR
FB( IN := IN_IN, PT := PT_IN, Q := Q_OUT, ET :=ET_OUT );
The direct variable is declared in a separate VAR block to the indirect variables. The input
and output variables for the TP function block are also allocated names that are different to
the names of the inputs and outputs in the function block as this makes it easier to
understand the ST program (for example, the PT input variable is named PT_IN). In this
example, the direct variable for the IN input (IN_IN) references a digital point (the Boolean
value for the input is taken from a digital point in the database).
In the second VAR block, the internal variables are declared, including an FB variable that
defines the type of function block.
The ST Program can then reference the variables as inputs and outputs for the function
block:
FB( IN := IN_IN, PT := PT_IN, Q := Q_OUT, ET :=ET_OUT );

PD-6017 07/2012

345

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Conversions
You can use the Conversions options to convert a variable of one data type into a variable
of a different data type. For example, you can convert a boolean value into a byte value by
using the BOOL_TO_BYTE conversion.
To access the conversions on a Function Block Diagram or Ladder Diagram:
1.

Display the diagram in Design mode.

2.

Right-click on the background of the diagram to display a context sensitive menu.

3.

Select the Conversions option to display a further menu.

4.

Select the option for the type of value that you want to convert. For example, if you
want to convert a string value into a byte value, select the String option.

A further menu is displayed.


5.

Select the option that corresponds to the type of value into which the value will be
converted. For example, if you want to convert a string into a byte, select the
STRING_TO_BYTE option.

A conversion box is added to the diagram.


6.

Connect the value that is to be converted to the connection box on the left of the
conversion box. The value will be converted and will be the output of the connection
box. You can connect a write tag to the right connection box so that the converted
value is written to the database, or you can connect the right connection box to a
function block.

NOTE: If a Logic program is invalid due to an incorrect data type, a message is displayed in
the compiler display at the bottom of the Logic diagram. The message indicates the type of
data that is expected (required) and the input or output at which an incorrect data type was
found. You can use this information to determine where conversions are needed and where
different types of conversion are required.
To use conversions in ST programs, simply reference the conversion by its name within an
expression. The names the conversions are same as the option names on the context
sensitive menus, for example, BOOL_TO_BYTE, STRING_TO_DINT, INT_TO_SINT etc.
The format for using a conversion in ST is:
<Name of Target Variable> := <Conversion type> (<Name of Source
Variable>);

346

PD-6017 07/2012

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Where:
<Name of Target Variable> is the name of the variable that is to be affected by the result of
the conversion (the converted value).
<Conversion type> is the name of the conversion, such as BYTE_TO_BOOL.
<Name of Source Variable> is the name of the variable that has the source value that is the
input for the conversion.
In each case, do not enter the angle brackets < >.
NOTE: When using conversions in ST programs, you need to enter the name of the
conversion in its full form (as shown in the Conversion options on the context sensitive menu
for Function Block Diagrams and Ladder Diagrams). For example, for date and time
conversions, you have to enter DATE_AND_TIME and not use the abbreviated form (DT). The
only exceptions to this rule are DT_TO_DATE and DT_TO_TOD.

PD-6017 07/2012

347

Chapter 8 - Built-in Functions, Function Blocks, and Conversions

Using Logic to Run an Executable File


You can use the SYSTEM function to allow a Logic program to run a .exe file. For more
information, see SYSTEM, on page 311.

Using Logic to Write to a File or Serial Port


You can use the OPEN_PORT and WRITE_FILE functions to write data to a serial port.
This is useful for exporting ASCII data to a serial port.
You can also use the WRITE_FILE function to write data to a file. For more information,
please refer to:

348

OPEN_PORT (see page 312)

OPEN_FILE (see page 313)

WRITE_FILE (see page 315)

CLOSE_FILE (see page 317).

PD-6017 07/2012

Chapter 9 - User Function Blocks

9 User Function Blocks

ClearSCADA allows you to create custom function blocks. You can use custom function
blocks, referred to as user function blocks, to significantly reduce the amount of Logic
programming required on your system.
User function blocks allow you to create special items that can be referenced by other
Logic programs. These special items are called Libraries, and you can use them to store
function blocks that need to be used by several programs. As the configuration for a user
function block is stored in a Library, it means you can include the function block in a
program simply be referencing the Library. There is no need for you to program the
function block in each Logic diagram or ST program.
There are 2 types of Library:

ST Library

Function Block Library

Both ST Libraries and Function Block Libraries allow you to create custom function
blocks that can be referenced by other Logic programs. Before you decide which type of
library you are going to use, you should consider:

The number of functions to be included in your libraryST Libraries can include


multiple functions, but Function Block Libraries can only contain a single function.

Your personal preferencedo you find it easier to work with the code of ST programs
or the more graphical interface of Function Block Diagrams? If you prefer to use ST
code, you should create an ST Library; if you prefer the Function Block Diagrams, you
should consider a Function Block Library, but please be aware that Function Block
Libraries can only contain one function.

When you have decided on the type of library you are going to use, you can create a
suitable database item and then edit the library.
To create, edit, reference, and update Libraries, refer to the relevant section:

Create an ST Library (see page 350)

Edit an ST Library (see page 350)

Create a Function Block Library (see page 353)

Edit a Function Block Library (see page 354)

Reference an ST Library or Function Block Library in a Logic Diagram (see page 355)

Reference an ST Library or Function Block in an ST Program (see page 356)

Update an ST Library or Function Block Library (see page 357).

PD-6017 07/2012

349

Chapter 9 - User Function Blocks

Create an ST Library
Before you can configure an ST library to represent a custom function block, you need to
create an ST library database item. The database item will be used to store the
configuration settings for the ST library.
To create an ST library:
1.

In the Database Bar, right-click on the system, Group, or Group Template that is to
contain the ST library.

A context sensitive menu is displayed.


2.

Select the New option, then the Logic option, then the Structured Text Library option.

A new ST library item is added to the tree-structure. It is selected automatically, ready


for you to define its name.
3.

Enter a suitable name, then press the Enter key or select another part of the interface to
confirm your selection.

Now that you have created an ST library item, you can edit it (see Edit an ST Library, on
page 350).

Edit an ST Library
You need to edit each ST Library so that it contains the code that defines a user function
block.
To edit an ST library:
1.

In the Database Bar, right-click on the ST library item to display a context sensitive
menu.

2.

Select the Edit option to display the ST Library Editor window. This window works in the
same way as the ST Program windowit has a section for entering the ST code and a
compiler section.

3.

Enter the ST code for the custom function block. Begin the code by using the
FUNCTION_BLOCK definition, then define the VAR_INPUTS, VAR_OUTPUTS, and
expressions in blocks in the same way as any other ST program (see Compiling an ST
Program or ST Library, on page 122).
NOTE: An example of the code for an ST Library is included at the end of this section.

350

4.

Use the compile tools to check the syntax of the ST Library code (see Compiling an ST
Program or ST Library, on page 122).

5.

Save the ST Library.

PD-6017 07/2012

Chapter 9 - User Function Blocks

Example:
The following ST code is used in an ST Library to provide the Logic that converts a value
in Celsius to a value in Fahrenheit:
FUNCTION_BLOCK Celsius_to_Fahrenheit
VAR_INPUT
Celsius:INT;
END_VAR
VAR_OUTPUT
Fahrenheit:INT;
END_VAR
Fahrenheit := ((Celsius*9/5) + 32);
Fahrenheit := Fahrenheit;
END_FUNCTION_BLOCK

PROGRAM ConvertLoad
VAR
c : Celsius_to_Fahrenheit;
END_VAR

VAR
LOAD AT %M(.Load) :LREAL;
STATUS AT %M(.Status) :BYTE;
END_VAR

VAR
In : INT := 30;
Out : INT;
END_VAR;

c(Celsius := In, Fahrenheit => Out);

PD-6017 07/2012

351

Chapter 9 - User Function Blocks

IF LOAD = 0 THEN
STATUS:= 0;
ELSIF LOAD < 50 THEN
STATUS := 1;
ELSIF LOAD < 90 THEN
STATUS := 2;
ELSE
STATUS := 3;
END_IF;

END_PROGRAM

The code can be referenced by multiple Logic programs. This means that the Celsius to
Fahrenheit conversion only needs to be created once (in an ST Library) and it can be
included in as many Logic programs as required.
When you have edited the ST Library, you can reference it in other Logic programs. For
more information, see Reference an ST Library or Function Block Library in a Logic
Diagram, on page 355 and Reference an ST Library or Function Block in an ST Program
(see page 356).

352

PD-6017 07/2012

Chapter 9 - User Function Blocks

Create a Function Block Library


Before you can configure a Function Block Library to represent a custom function block,
you need to create a Function Block Library database item. The database item will be
used to store the configuration settings for the Function Block Library.
To create a Function Block Library:
1.

In the Database Bar, right-click on the system, Group, or Group Template that is to
contain the Function Block Library.

A context sensitive menu is displayed.


2.

Select the New option, then the Logic option, then the Function Block Library option.

A new Function Block Library item is added to the tree-structure. It is selected


automatically, ready for you to define its name.
3.

Enter a suitable name, then press the Enter key or select another part of the interface to
confirm your selection.

Now that you have created a Function Block Library item, you can edit it (see Edit a
Function Block Library, on page 354).

PD-6017 07/2012

353

Chapter 9 - User Function Blocks

Edit a Function Block Library


When you have added a Function Block Library database item, you can edit it so that it
contains the Logic that defines the functionality of your custom function block.
To edit a Function Block Library:
1.

In the Database Bar, right-click on the Function Block Library item to display a context
sensitive menu.

2.

Select the Edit option to display the Function Block Library Editor display. This window
works in the same way as the Function Block Diagram displayit has a section for
defining the variables, a design section for creating the Function Block Diagram, and a
compiler section for checking the syntax.
NOTE: As an alternative to steps 1 and 2, you can double-click on the Function Block
Library item to display it in Design mode.

3.

Create the Logic for the custom function block by adding variables, constants,
functions, and function blocks in the same way that you would create a Function Block
Diagram. For further information, see Function Block Diagrams, on page 157 and
Built-in Functions, Function Blocks, and Conversions (see page 223).
When you save the Function Block Library and reference it in a Logic diagram, the
function block library will appear as a graphical representation of the function blockit
will have input and output connections and will provide the Logic functionality that you
have defined. Obviously, if you reference the Function Block Library in an ST program,
you will not see the graphical representation of the Function Block Library.

4.

Use the compile tools to check the syntax of the Function Block Library (see Compiling
a Function Block Diagram or Function Block Library, on page 184).

5.

Save the Function Block Diagram.

When you have edited the Function Block Diagram, you can reference it in other Logic
programs. For more information, see Reference an ST Library or Function Block Library in
a Logic Diagram, on page 355 and Reference an ST Library or Function Block in an ST
Program (see page 356).

354

PD-6017 07/2012

Chapter 9 - User Function Blocks

Reference an ST Library or Function Block Library in a Logic Diagram


When you have created one or more ST Libraries or Function Block Libraries, you can
reference them in other Logic programs, including Logic diagrams such as Function Block
Diagrams.
NOTE: For information on referencing a library in an ST program, see Reference an ST
Library or Function Block in an ST Program, on page 356.
By referencing an ST Library or Function Block Library, you allow a Logic program to use
the Logic behaviour that is defined in the library without having to program it. This is
useful when the same Logic is needed in multiple programs.
To reference an ST Library or Function Block Library in a Logic Diagram:
1.

Display the Logic diagram in Design mode.

2.

Select the Edit menu.

3.

Select the Libraries option to display the Libraries window.


The Libraries window contains a list of the ST and Function Block Libraries that are
available.

4.

Check the check boxes for those libraries that you want to reference in the Logic
diagram (and clear the check boxes for those libraries that are not required)..

5.

Select the OK button to confirm your selection and close the Libraries window.

6.

On the Logic diagram, right-click on the background of the diagram to display a context
sensitive menu.

7.

Select the User Function Blocks option.

A further menu is displayed. The further menu contains a list of the custom function
blocks that you have created.
8.

Select the option for the function block that you require.

A further option is displayed. The option has the same name as the custom function
block.
9.

Select the option that has the same name as the required function block.

The custom function block is added to your Logic diagram.


You can connect variables and constants to the inputs and outputs of the custom function
block. To do this, you should use the same methods that you use to make connections to
a built-in function block (see Built-In Function Blocks, on page 319).

PD-6017 07/2012

355

Chapter 9 - User Function Blocks

Reference an ST Library or Function Block in an ST Program


To reference an ST Library or Function Block Library in an ST program, you need to
enable the Libraries and then define them as variables in the code. There is no need to
define the function block with FUNCTION_BLOCK...END_FUNCTION_BLOCK.
As with referencing libraries in a Logic diagram, you can only reference those libraries that
you enable via the Libraries window.
To reference an ST Library or Function Block Library in an ST Program:
1.

Display the ST program in Design mode.

2.

Select the Edit menu.

3.

Select the Libraries option to display the Libraries window.

4.

Check the check boxes for the libraries that you want to use in the ST program and
clear the check boxes for those libraries that are not required.

5.

Select the OK button to confirm your selection and close the Libraries window.

6.

Edit the code for the ST program.


You need to include the user function block (that is defined in one of the Libraries) in a
VAR...END_VAR definition. The VAR definition needs to use the following format:
VAR
<Variable name>: <Name of library>;
END_VAR
Where <Variable name> is the name that you will use to reference the user function
block within the ST code of the program you are editing.
<Name of library> is the name of the user function block that you defined in the ST
Library or Function Block Library (this is the same name as the ST Library or Function
Block Library).
Do not enter the angle brackets < >. We use the angle brackets to indicate that the
name is dependent on the entries you have made.
When you have defined the variables, you can use expressions to define the values and
Logic for the program (see ST Programs, on page 29).
For example, if you are referencing an ST Library named 'Celsius_To_Fahrenheit' then
the ST program code could be:
PROGRAM Celsius_To_Fahrenheit_Conversion
VAR
TempC :LREAL:=20.0;
TempF:LREAL;
END_VAR
VAR
C_TO_F: Celsius_To_Fahrenheit;
END_VAR
C_TO_F(Celsius := TempC,Fahrenheit => TempF);
END_PROGRAM

7.

356

Save the ST program.

PD-6017 07/2012

Chapter 9 - User Function Blocks

Update an ST Library or Function Block Library


If you need to make changes to an ST Library or Function Block Library, you have to edit
the Library and then update any Logic programs that reference the Library. Working this
way means that your Logic programs will use the updated version of the Library.
To update an ST Library or Function Block Library:
1.

In the Database Bar, either double-click on the ST Library or Function Block Library
item or right-click on it and select the Edit option from the context sensitive menu.

The library is displayed in Design mode.


2.

Alter the code or Function Block diagram as required. You can use the Build menu
options to check the code (see Update an ST Library or Function Block Library, on page
357).

3.

Save the Library. Now you need to update the Logic programs that reference the
Library.

4.

For each Logic program that references the altered Library:


i.

Display the Logic program in Design mode.

ii. Select the Edit menu, then select the Library Update option.
iii. Save the ST program.

PD-6017 07/2012

357

Chapter 9 - User Function Blocks

358

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

10 Logic Program Properties and Values

Each type of Logic program is represented in the database by a database item. Like other
database items, ST Programs, ST Libraries, Function Block Diagrams, Ladder Diagrams,
and Sequential Function Charts have configuration Forms.
To learn about the settings that are available on ST Program, Ladder Diagram, Function
Block Diagram, and Sequential Function Chart Forms, see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359.
To learn about the settings that are available on the ST Library Form, see Configure an ST
Library, on page 385.
As with other types of database item, the Logic programs also have OPC tags for their
configuration properties. You can view these tags by using the OPC Data Bar (see OPC
Properties for Logic Programs, on page 388).

Configure an ST Program, Ladder Diagram, SFC or FBD


Each Logic database item has its own Form that you can use to configure relevant
settings. The Forms for ST Programs, Ladder Diagrams, Sequential Function Charts and
Function Block Diagrams are very similar. You can use them to:

View the Name and configure the Help View for the Logic program. These settings are
available on the Identification tab. For more information, see Defining Identification
Details, on page 199 in the ClearSCADA Guide to Core Configuration.

Associate the Logic program with up to 4 custom pick actions by using the User
Methods tab. For more information, see Using the User Methods Tab to Define Custom
Actions, on page 203 in the ClearSCADA Guide to Core Configuration.

Enable or Disable a Logic Program (see page 362)

Define the Severity of a Logic Program's Alarms and Events (see page 363)

Define the Execution Settings for a Logic Program (see page 364)

Define when a Logic Program Updates its Outputs (see page 377)

Define whether a Logic Program Executes Methods after a Failed Method (see page
379)

Define the Conversion Types for a Logic Program (see page 380)

Define the Number of Instructions for a Logic Program (see page 382)

Define the Time Zone to be used for Calculations within the Logic Program (see page
384).

NOTE: To create the code or diagram for a Logic program, you have to use the dedicated
Logic editor.

PD-6017 07/2012

359

Chapter 10 - Logic Program Properties and Values

To display a Logic program's Form and configure its settings:


1.

In the Database Bar, right-click on the Logic program icon to display a context sensitive
menu.

2.

Select the Properties option to display the relevant Form.


Use the
Identification tab to
view the Name of
the Logic program
and define its Help
View.

Use the User


Methods tab to
associate the
Logic program
with up to 4
custom actions.

Use the Logic tab to define


the execution, conversion
settings etc.

Use these settings to


enable or disable the
Logic program, define
the severity of its
alarms and events and
set its priority number.

Use the Execution


settings to define when
and how the Logic
program is executed.

Use these settings to


define whether the
Logic program can be
triggered by a change
in value, define when
the program updates
its outputs, and define
how the program
reacts to methods that
cannot be performed
successfully.
Use these settings to define how the Logic program converts values,
and to set the Instruction limit and Execution Queue Size.

NOTE: Alternatively, you can select the Properties option for the program from any
instance of the program's context sensitive menu. For example, you may have a Mimic
that provides access to an ST Program's Form or to its context sensitive menu.
3.

360

Use the Identification tab to define the Help View for the Logic program as required.
(see Defining Identification Details, on page 199 in the ClearSCADA Guide to Core
Configuration).

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

4.

Use the User Methods tab to associate the Logic program with up to 4 custom pick
actions as required (see Using the User Methods Tab to Define Custom Actions, on
page 203 in the ClearSCADA Guide to Core Configuration).

5.

Select the Logic tab.

6.

Use the In Service check box to Enable or Disable the Logic program (see Enable or
Disable a Logic Program, on page 362).

7.

Use the Severity combo box to set the severity for alarms and events that are
associated with the Logic program (see Define the Severity of a Logic Program's
Alarms and Events, on page 363).

8.

Use the execution-related settings to define when and how the Logic program can be
executed (see Define the Execution Settings for a Logic Program, on page 364):

9.

PriorityUse to define whether the Logic program is executed in preference to


other Logic programs (see Define the Priority of a Logic Program, on page 366)

Execution MethodUse to define whether the Logic program is executed on a time


basis or when its inputs change (see Define the Execution Method for a Logic
Program, on page 367)

IntervalUse to define how often timed execution of the Logic program takes place
(see Define the Interval Settings for a Logic Program, on page 368).

Interval OffsetUse to define the start time for the first timed execution (see Define
the Interval Settings for a Logic Program, on page 368).

Interval Offset Time ZoneUse to define the time zone to be used when calculating
the time for the first timed execution (see Define the Interval Settings for a Logic
Program, on page 368).

Input Change DetectionUse to define whether the Logic program is executed


when it detects a change in the value of one of its inputs (see Define whether a
Logic Program Executes when the Value of an Input Changes, on page 370)

Execute on Quality ChangeUse to define whether the Logic program is executed


when it detects a change in the quality of one of its inputs (see Define whether a
Logic Program Executes when the Quality of an Input Changes, on page 371)

Allow Manual ExecutionUse to control the availability of the Execute action that is
used to manually execute the Logic program (see Define whether a Logic Program
can be Executed Manually, on page 373)

Execution PermissionUse to define the permission required to access the


Execute action for the Logic program (see Define which Permission is Required to
Execute a Logic Program, on page 374)

Use the Trigger setting to configure the Logic program to execute in response to a
change in the value of a selected property of a specific database item (see Associate
the Execution of a Logic Program with a Property in the Database, on page 375).

10. Use the Update Outputs setting to Define when a Logic Program Updates its Outputs
(see page 377).
11. Use the Ignore Method Errors setting to Define whether a Logic Program Executes
Methods after a Failed Method (see page 379).
12. Use the Byte - String Conversions and String to Time Conversion Mode settings to
Define the Conversion Types for a Logic Program (see page 380).
13. Use the Instruction Limit setting to Define the Number of Instructions for a Logic
Program (see page 382).

PD-6017 07/2012

361

Chapter 10 - Logic Program Properties and Values

14. Use the Execution Queue Size setting to define the maximum number of values
(reported by an outstation) that can be stored in the execution queue. The default
setting of 250 is usually appropriate (see Define the Maximum Number of Executions
that can be Queued, on page 376).
15. Use the Program Time Zone setting to define the time zone to be used if the Logic
program uses time conversion functions (see Define the Time Zone to be used for
Calculations within the Logic Program, on page 384).
16. Save the Logic program's Form to confirm and store your selections.

Enable or Disable a Logic Program


ClearSCADA can only execute active Logic programs. Logic programs are active by
default, but they can be deactivated (and re-activated) by selecting the In Service check
box on the Logic tab.
To enable or disable a Logic program:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Check the In Service check box to enable the program or clear it to disable the
program.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

362

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define the Severity of a Logic Program's Alarms and Events


You can use the Severity combo box on the Logic tab to set the severity level for the
alarms and events that are associated with the selected Logic program. This is useful
when certain programs are more significant than others.

To define the severity of a Logic program's alarms and events:


1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Choose the Severity level that is appropriate for the program you are configuring. The
default range of Severity options is None (lowest importance), Low, Medium, High,
Critical (highest importance). These options are configurable via the Server
Configuration Tool and may have been altered on your system.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

PD-6017 07/2012

363

Chapter 10 - Logic Program Properties and Values

Define the Execution Settings for a Logic Program


When you have defined the program code for your program, you need to configure it so
that the system can execute it. To do this, you need to use the various Execution settings,
the Trigger setting and the Execution Queue Size setting. Depending on your selections,
the system will execute the program:

At regular intervals

When its inputs are processed

When it detects changes to the values of its inputs

When it is triggered by a change to a value in the database (only applicable Logic


programs that have an On Interval execution method)

When there is a change in the quality of any of its inputs (only applicable to Logic
programs that have an On Input Processed execution method).

To define the execution settings for a Logic Program:

364

1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Define the following execution-related settings:

PriorityUse to define whether the Logic program is executed in preference to


other Logic programs (see Define the Priority of a Logic Program, on page 366)

Execution MethodUse to define whether the Logic program is executed on a time


basis or when its inputs change (see Define the Execution Method for a Logic
Program, on page 367)

IntervalUse to define how often timed execution of the Logic program takes place
(see Define the Interval Settings for a Logic Program, on page 368).

Interval OffsetUse to define the start time for the first timed execution (see Define
the Interval Settings for a Logic Program, on page 368).

Interval Offset Time ZoneUse to define the time zone to be used when calculating
the time for the first timed execution (see Define the Interval Settings for a Logic
Program, on page 368).

Input Change DetectionUse to define whether the Logic program is executed


when it detects a change in the value of one of its inputs (see Define whether a
Logic Program Executes when the Value of an Input Changes, on page 370)

Execute on Quality ChangeUse to define whether the Logic program is executed


when it detects a change in the quality of one of its inputs (see Define whether a
Logic Program Executes when the Quality of an Input Changes, on page 371)

Allow Manual ExecutionUse to control the availability of the Execute action that is
used to manually execute the Logic program (see Define whether a Logic Program
can be Executed Manually, on page 373)

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

4.

PD-6017 07/2012

TriggerUse to set the Logic program to execute in response to a change in the


value of a selected property of a specific database item (see Associate the
Execution of a Logic Program with a Property in the Database, on page 375)

Execution Queue SizeUse to define the maximum number of values (reported by


an outstation) that can be stored in the execution queue. The default setting of 250
is usually appropriate (see Define the Maximum Number of Executions that can be
Queued, on page 376).

Save the configuration changes you have made.

365

Chapter 10 - Logic Program Properties and Values

Define the Priority of a Logic Program


Each Logic program has a Priority setting that you can use to define whether the program
is executed in preference to other programs that are scheduled to execute at the same
time.
ClearSCADA executes one Logic program at a time. If more than one Logic program is
scheduled to occur at the same time, ClearSCADA executes the program that has the
lowest Priority number first. This means that by defining a range of different Priority
numbers for your Logic programs, you can prioritise all (or a selected few) of your
programs.
If multiple Logic programs with the same Priority setting are scheduled to occur at the
same time, ClearSCADA execute them in according to the queue time. The program that
has been queued for the longest amount of time is executed first, and the program that
has been queued for the least amount of time is executed last.
Logic programs have a Priority of 0 by default. Programs with 0 Priority are executed first,
followed by programs with 1 Priority, and then programs with 2 Priority and so on.
To change the Priority of a Logic program, display the Logic Program Form, select the
Logic tab, then enter an appropriate number in the Priority field. Remember that Logic
programs with the lowest numbers are executed in preference to those with higher
numbers.
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

366

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define the Execution Method for a Logic Program


Each Logic program has an Execution Method setting that you can use to define whether
the program is executed as a response to its inputs or on a timed basis.
The Execution Method setting provides 2 options:

On Input ProcessedThe program is executed whenever one of its inputs is


processed. This means that every time ClearSCADA receives a value for one of the
inputs, it will execute the program (even if the value has not changed since the last time
the program was executed).
A program that uses On Input Processed will only execute if there is a change to one of
its inputs and that input is deemed to be valid. The following inputs are valid:

%I but only if the program does not use the NOCACHE attribute, and the tag for
the variable references a field, method, aggregate or historic tag

%M but only if the program has no assignments (does not write to the variable),
does not use the NOCACHE attribute, and the tag for the variable references a field,
method, aggregate or historic tag.

The following inputs are invalid:

%O

Inputs using NOCACHE

Inputs that reference a register or status tag

%M inputs that have assignments.

If the program does contain a valid input, it will not execute and a message will be
displayed.
The On Input Processed setting should not be confused with the Input Change
Detection setting, which causes the program to be executed whenever ClearSCADA
detects that the value of one of the inputs has changed since the previous execution.
For more information on the Input Change Detection setting, see Define whether a
Logic Program Executes when the Value of an Input Changes, on page 370.

On IntervalThe program is executed regularly at timed intervals. You need to define


the timed intervals in the Interval and Interval Offset fields (see Define the Interval
Settings for a Logic Program, on page 368).

To change the Execution Method of a Logic program, display the Logic Program Form,
select the Logic tab, then choose the appropriate setting from the Execution Method
combo box.
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

PD-6017 07/2012

367

Chapter 10 - Logic Program Properties and Values

Define the Interval Settings for a Logic Program


Logic programs have several Interval settings that can be used when the Execution
Method is set to On Interval (see Define the Execution Method for a Logic Program, on
page 367). They allow you to define the time of a Logic programs 'first' timed execution
or value check, and how often subsequent timed executions and value checks take place.
The Interval settings are:

IntervalUse to define:

The amount of time between each execution of the program

Whether the Logic program executes automatically. If you set the Interval to 0, the
Logic program will not execute automatically - it can only be executed by the
Execute method being called. The Execute method can be called manually or can
be called by other Logic programs, Schedules etc.
When the Interval is set to any value other than 0, it will execute automatically at the
defined interval. For example, if the Interval is 5H, ClearSCADA will execute the
Logic program every 5 hours, without the need for a Schedule.

How frequently the program checks the value of the Trigger item (this only applies
to programs that have an Execution Method of On Interval and are configured to
use a Triggersee Associate the Execution of a Logic Program with a Property in
the Database, on page 375)

How frequently the program checks changes to its inputs (this is only applicable if
the Input Change Detection setting is enabled, see Define whether a Logic Program
Executes when the Value of an Input Changes, on page 370).

If a Logic program has a Trigger and Input Change Detection enabled, it will check the
value of the Trigger and the value of its inputs according to the defined Interval. The
program will execute if either the Trigger item value has changed or a change to an
input has been detected.
You can enter the time in the OPC Time Interval format or use the Interval window to
define the appropriate time (see Interval Window, on page 175 in the ClearSCADA
Guide to Core Configuration).
By default, the program will execute, check the value of its inputs, or check the value of
its Trigger when the Logic driver starts and then will continue to be execute or check
the values every 10 seconds (as the default Interval Offset is NOW and the default
Interval setting is 10S).
By changing the Interval, you can alter the amount of time between each timed
execution or check.
NOTE: Manual executions have no effect on any timed executions. Apart from the very
first execution, the time of the next timed execution is: the time of the previous timed
execution + the Interval. So, if the previous execution was at 13:10:05 and the Interval is
15S, the next timed execution would be 13:10:20, even if there was a manual execution
between 13:10:05 and 13:10:20.

368

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Interval OffsetUse to define the start time for the first execution or value check for the
Logic program. By default, the Interval Offset setting is blank which means that the
default setting for the field is NOW. As a result, it means that the first execution or value
check occurs as soon as the Logic driver starts with subsequent executions or value
checks taking place according to the Interval setting.
However, you can change the Interval Offset so that there is a delay between the Logic
Driver starting and the first timed execution or value check taking place. The calculation
works like this:
Time of Logic Driver Starting+Interval Offset='First' timed
execution or value check.
For example, if you set the Interval Offset to M, the first execution or value check will
not take place until the start of the first minute after the Logic Driver has started. So if
the Logic Driver started at 12:15:19, the 'first' execution or value check would not take
place until 12:16:00 (the start of the next minute). The 'first' execution or value check is
the initial execution or value check after the Logic Driver starts or after a change to the
Interval Offset has been saved.
If the Logic Driver is already running when you make the Interval Offset change, the
time of the configuration change replaces the time of the Logic Driver starting in the
calculation:
Time of Interval Offset Config Change+Interval
Offset='First'timed execution or value check
As with the Interval, you can enter the Interval Offset in the OPC time interval format or
you can use the Interval window that is displayed when you select the browse button
next to the Interval field.

Interval Offset Time ZoneUse to define the clock that is used when calculating the
time for the Interval Offset. You can choose from:

Coordinated Universal Time (UTC)

Local Time without Daylight Saving Time

Local Time with Daylight Saving Time (for regional variations to GMT standard time,
such as British SummerTime).

ClearSCADA uses the time zone to calculate the current time which is then used during
the application of the Interval Offset and Interval settings.

To change the Interval, Interval Offset, or Interval Offset Time Zone of a Logic program,
display the Logic Program Form, select the Logic tab, then enter the required times in the
Interval or Interval Offset fields. You have to use the OPC Time Interval format. If you are
changing the Interval Offset Time Zone, simply select the required time zone from the
combo box as appropriate.
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.
Using OPC Time Formats: See page 173.

PD-6017 07/2012

369

Chapter 10 - Logic Program Properties and Values

Define whether a Logic Program Executes when the Value of an Input


Changes
If a Logic program is configured to have an Execution Method setting of On Interval, you
can configure the system to automatically execute the program whenever one of the
programs inputs changes value. This is useful, as it means you can set a Logic program
to execute on a timed basis, but only if its inputs have changed value.
To choose whether a Logic program executes only when its inputs have changed, you
need to use the Input Change Detection check box on the Logic tab of Logic Program
Form:

If you check the Input Change Detection check box, the system will only execute the
program if one of the program's inputs changes. This means that if the program is
scheduled to be executed, but none of its inputs have changed value, the program will
not be executed.
NOTE: If your Logic program is designed to use database values in a calculation, and
then write the result to a point, you should consider enabling the Execute on Quality
Change feature (see Define whether a Logic Program Executes when the Quality of an
Input Changes, on page 371).

If you clear the Input Change Detection check box, the system will execute the program
according to its Interval settings (see Define the Interval Settings for a Logic Program,
on page 368). The program will still be executed even if the program's input values have
not changed since it was last executed. The program will have updated events etc.
relating to the execution.

Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

370

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define whether a Logic Program Executes when the Quality of an Input


Changes
You can configure a Logic program so that it is executed whenever one of its inputs
changes value and/or the quality of any of its inputs changes. This is useful if you need to
use your Logic program to provide certain behavior in the event of a quality change.
Example:
A Logic program is configured to execute On Input Processed and has Execute on Quality
Change enabled. It is coded so that it reads the values of 4 points on an outstation.
When the point values change, the Logic program calculates the total value of the points and
writes the result to another point (a derived point). The Logic program also includes code
that sets the program to exclude any points that have Bad quality from its calculation. If any
of the points are excluded due to Bad quality, the Logic program is set to write Bad to the
Current Quality property of the derived point.
When the value of any of the 4 input points changes, the Logic program executes, calculates
the total value and writes the result to the derived point. The Logic program also executes if
the quality of any of the input points changes.
There is a power failure and the outstation goes offline. ClearSCADA detects the fault and
changes the quality of the 4 points to Bad as they may be inaccurate or out of date. But the
current values of the points remain the same as before the power failure.

ClearSCADA detects that the outstation has failed,


which results in the quality of the points changing to
Bad. However, the current values of the points
remain the same - they are unaffected by the
outstation failure.

As Execute on Quality Change is enabled and 1 or more of the 4 input points have changed
quality, the Logic program executes. The 4 input points now have Bad quality and so they
are excluded from the Logic programs calculation. This means that the result of the
calculation is 0 and this is the value that is written to the derived point. As one or more of the
inputs also have Bad quality, the Logic program sets the Current Quality value of the derived
point to Bad. This means that the Current Value and Current Quality of the derived point
indicates that there may be a problem with the Logic program or its inputs.
If the Execute on Quality Change feature was disabled, the Logic program would only
execute when any of the input values changed. So when the outstation failed, the Logic
program would not execute as the values for the points would not have changed.
Consequently, the value of the derived point would remain the same - there would be no
indication that the values used to calculate the derived point value are now unreliable.

PD-6017 07/2012

371

Chapter 10 - Logic Program Properties and Values

To choose whether a Logic program executes when the quality states of its inputs have
changed, you need to use the Execute on Quality Change check box on the Logic tab of
Logic Program Form:

If you check the Execute on Quality Change check box, the system will execute the
program if it detects:

A change in the value of the input (Logic programs that are set to On Input
Processed execute automatically when their input values change)

A change in the quality of the input.

If you clear the Execute on Quality Change check box, the system will execute the
program only when its input values change.

Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

372

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define whether a Logic Program can be Executed Manually


To execute a Logic program manually, users select the Execute action from the
context-sensitive menu for the Logic program database item. The availability of the
Execute action is dependent on the permissions of the users User account and the
configuration of the Logic programif the Logic programs Allow Manual Execution
setting is selected, the Execute action is available; if the Allow Manual Execution setting is
de-selected, the Execute action is unavailable, even if the user has sufficient permissions
to access the actions for the program.
Being able to control the availability of the Execute action is useful as it means you can
create Logic programs that can only be executed by ClearSCADA, either as a response to
input changes or on a timed basis.
To define whether a Logic program can be executed manually, display the Logic Program
Form, select the Logic tab, then either:

Check the Allow Manual Execution check box to make the Execute action available on
the context-sensitive menu for the Logic program.

Or

Clear the Allow Manual Execution check box to make the Execute action unavailable on
the context-sensitive menu for the Logic program.

Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

PD-6017 07/2012

373

Chapter 10 - Logic Program Properties and Values

Define which Permission is Required to Execute a Logic Program


You can use the Execution Permission setting to define which security permission (if any)
is required to access a Logic programs Execute action. Each Logic program has its own
Execution Permission setting, so you can control which users can execute Logic
programs on a per-program basis.
NOTE: The availability of the Execute action can also be restricted by using the Allow Manual
Execution setting (see Define whether a Logic Program can be Executed Manually, on page
373). If the Allow Manual Execution setting is disabled for a Logic program, users will not be
able to access the programs Execute action even if they have the required Execution
Permission.
Example:
A Logic program named PumpControl is configured to have an Execution Permission
setting of Control. It is also configured to have the Allow Manual Execution setting enabled.
A user logs on via a User account named A Hall. The A Hall user has the Control
permission for the PumpControl program. This means that A Hall can access the Execute
action for the PumpControl program, as Control is the defined Execution Permission.
Another Logic program named SensorVariation is also configured to have an Execution
Permission of Control. However, the A Hall user does not have the Control permission for
the SensorVariation program. When the A Hall user accesses the context sensitive menu
for the SensorVariation program, the Execute action is not included as an option.
The configuration of the PumpControl program is changed so that it no longer has Allow
Manual Execution enabled. With the change in place, the A Hall user is unable to select the
Execute action for the PumpControl program, even though A Hall has the Control
permission. This is because the Allow Manual Execution setting is disabled; the Execute
permission is unavailable to users, irrespective of their permissions for the program.

To define the Execution Permission for a Logic program, display the Logic Program Form,
select the Logic tab, then use Execution Permission combo box to choose the required
permission. Only users that have the selected permission will be able to access the
programs Execute action (which is only available if the Allow Manual Execution setting is
also enabled, see Define whether a Logic Program can be Executed Manually, on page
373).
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

374

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Associate the Execution of a Logic Program with a Property in the


Database
If your Logic program is configured to execute On Interval (see Define the Execution
Method for a Logic Program, on page 367), you can use the Trigger setting to associate
the Logic program with any property of any database item. When there is a change to the
value of the selected property, the Logic program will execute.
If the Logic program is set to have an Execute Method of On Interval, the time specified
for the Interval defines how often the program checks the value of the Trigger item. For
example, if the Interval is 30S, the program will check the value of the Trigger item every
30 seconds, and the program will only execute if the value of the Trigger item has
changed.
The Trigger feature is useful when you need a Logic program to execute as a response to
the value or state of a database item that is not used as an input in the program. For
example, you may have a Logic program that uses various points as inputs, but is
triggered by the state of the outstation with which those points are associated. The
outstation state is not defined as an input in the program (as it is not relevant to the
program), but when the state of the outstation changes, the Logic program executes.
You can set a Logic program to execute in response to a change to any property field in
the database. To do this, display the Logic Program Form, select the Logic tab, then use
the browse button feature of the Trigger field to select the required property. When the
value of the selected property changes, the Logic program will be executed.
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

PD-6017 07/2012

375

Chapter 10 - Logic Program Properties and Values

Define the Maximum Number of Executions that can be Queued


If your Logic program is configured to execute On Input Processed (see Define the
Execution Method for a Logic Program, on page 367), you can use the Execution Queue
Size setting to define the maximum number of executions that can be placed in a queue.
This feature is designed for use with programs that need to perform calculations on
values that are reported by outstations.
When an outstation reports values, it reports them in a block (multiple values are reported
at once). As a Logic program can only be executed in response to one value at a time,
ClearSCADA stores the block of values in a queue, referred to as the execution queue.
Any Logic programs that use the values reported by the outstation then use the values in
the queuethey execute for each value in turn. This means that Logic programs execute
in response to the reported values rather than the current values (some of the current
values may have been updated by the time the program is executed).
The Execution Queue Size defines the maximum number of values that can be stored in
the execution queue. Typically, the default Execution Queue Size of 250 is appropriate.
However, you may need to change this setting if your program is not performing its
calculations on the reported values (this often means that there are too many values being
reported, and the execution queue is full and so cannot store any new values).
If the execution queue becomes full, any further values reported by the outstation will be
disregarded, so if the Execution Queue Size is too small, data could be lost.
To change the Execution Queue Size, display the Logic Program Form, select the Logic
tab, then enter the required number in the Execution Queue Size field. We recommend
that you do not increase the Execution Queue Size beyond 1000 as doing so may cause
the server to run out of memory.
Further Information
Display the Logic Program Form: see Configure an ST Program, Ladder Diagram, SFC or
FBD, on page 359.

376

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define when a Logic Program Updates its Outputs


You can use the Logic program Forms to define when a Logic program updates its output
values:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Use the Update Outputs combo box to set a program to update its outputs:

Changed Outputs OnlyIf the program calculates values that are different to the
existing output values, the existing output values are overwritten. The new values
from the programs results replace the existing output values (but only for those
outputs that have different values to those in the programs results). This setting is
useful when you only want the program to update the outputs to reflect changes in
the Logic programs calculated results.
The main advantages of using the Changed Outputs Only setting are that the
program will only generate historic records for values that have changed and there
is no needless processing (as ClearSCADA only writes new values to the outputs
that need to be updated and only generates historic records for values that have
changed).

All Outputs (Always)The program will write a new value, even if the result of the
program returns the same output value as the existing output value. This setting is
useful when you only want the program to update on every execution.
The main advantage of using the All Outputs (Always) setting is that you can check
that the program is executing correctly at the required intervals or when the inputs
are updated. This means you can have confidence that the program is functioning
correctly, even though its outputs are not changing.

All Outputs (If Any Changed)If the program returns one or more output values that
are different to the existing values, new values are written for each of the outputs.
This setting is mainly designed for use with Logic programs that write to the
PresetTimestamp or PresetQuality fields of internal points.
To help you understand how the All Outputs (If Any Changed) setting works, we will
begin by explaining how the PresetTimestamp and PresetQuality fields can be
used.
The Preset Timestamp and PresetQuality data fields are used to store the time
stamp and quality values for the internal points historic record. By default, the
PresetTimestamp value is the current time and the PresetQuality value is Good, but
by writing to these fields, you can apply a different time stamp and quality value.
This is useful when you use an internal point to store a value that is derived from
other point values, for example, for storing the average value of a selection of
points. By writing to the PresetTimestamp and PresetQuality fields, you can set the
historic record of the internal point to match the time stamps and quality values of
the points used in the calculation. If the PresetQuality and PresetTimestamp were
not written, the internal points historic record would use the time stamp for the time
of the calculation and the quality would be Good (which may not be the case).

PD-6017 07/2012

377

Chapter 10 - Logic Program Properties and Values

The PresetQuality and PresetTimestamp are written when the internal point is next
updated, and once written, are reset. This means that once they have been applied,
they have no effect on further updates (unless the program is coded so that the
PresetQuality and PresetTimestamp fields are written to again).
If you have a Logic program that writes to the PresetQuality and/or
PresetTimestamp fields, your choice of Update Outputs affects when the Preset
values are applied:

With the Changed Outputs Only setting, the Preset fields are only applied if there is
a change to the calculated value (that is to be stored in the internal point changes).
This is because the Logic program is set to only write to the CurrentValue of the
internal point if the calculated value has changed since the last execution. If the
Logic program does not write to the CurrentValue, there is no new historic value to
be logged and so the Preset values are ignored.

With the All Outputs (If Any Changed) setting, the Preset fields are applied if the
Logic programs inputs have a change of quality, a different time stamp, or the result
of the Logic programs calculation changes. If any of these changes occur, the
Logic program writes to the CurrentValue, PresetTimestamp and PresetQuality
fields of the internal point. This means that a historic record is created even if the
calculated value of the Logic program has not changed.

With the All Outputs (Always) setting, the Preset fields are applied every time the
Logic program executes. This is because the Logic program writes the
PresetTimestamp, PresetQuality and CurrentValue of the internal point on each
execution, irrespective of whether any of these values has changed. As a result,
there is a historic value logged for every execution of the Logic program.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

378

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Define whether a Logic Program Executes Methods after a Failed


Method
You can use the Ignore Method Errors check box to define how a Logic program reacts to
methods that are unable to be performed successfully. This feature is especially useful
with programs that are used to perform several methods in sequence.

Use the Ignore Method Errors check box to define whether the
program ignores methods that cannot be performed successfully.

When a program executes, it reads its inputs, then evaluates its internal calculations, then
writes its outputs. Finally, it performs its methods (if any). It performs each method in turn.
By default, if one of its methods cannot be performed, the program aborts any attempt to
perform subsequent methods. This means that one erroneous method in a program will
result in other methods being aborted.
You can change this setting so that the program will ignore erroneous methods, and
continue to perform any other methods.
To control whether a Logic program continues to execute its methods following an
unsuccessful method:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Either:

Check the Ignore Method Errors check box to allow the program to ignore
erroneous methods and continue to execute further methods.

Or:

Clear the Ignore Method Errors check box to set the program so that it makes no
attempt to execute methods following an unsuccessful attempt to perform a
method.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

PD-6017 07/2012

379

Chapter 10 - Logic Program Properties and Values

Define the Conversion Types for a Logic Program


You can use the Byte-String Conversions and String to Time Conversion Mode combo
boxes to define how a Logic program converts values. The conversions that you select
will affect the results of the program, so you need to choose the correct types of
conversion for your needs.
To define the conversion types:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Use the Byte - String Conversions combo box to choose the conversion type for
converting byte values into string values.

The available options include:

4.

CharacterThe system will use ASCII codes to convert the byte number into a
string value. Each character has a a corresponding ASCII codethe program will
read the byte value as an ASCII code.

Decimal IntegerThe system will use binary codes to convert the byte number into
a string value. Each character has a corresponding binary codethe program will
read the byte value as a binary code.

Hexadecimal IntegerThe system will use hexadecimal codes to convert the byte
number into a string value. Each character has a corresponding hexadecimal
valuethe program will read the byte value as a hexadecimal value.

Use the String to Time Conversion Mode combo box to define the format that will be
used when the time inputs are converted to strings. The format can be:

WindowsUses a format that is similar to the date and time formats for the UK
locale of Microsoft Windows. The format of the string is dependent on the type of
input time value:
Input Type
Date

Output String Format (Windows)


dd-MM-yyyy
For example, 09-12-2011

Date and Time

dd-MM-yyyy hh:mm:ss.SSS
For example, 09-12-2011 22:31:14.313

Time of Day

hh:mm:ss.SSS
For example, 22:31:14.313

Time

hh:mm:ss.SSS
For example, 22:31:14.313
The milliseconds are omitted if they are zero.
If the time is negative, the string is prefixed with a minus sign,
for example, minus 12 hours is: -12:00:00.

380

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

IEC 61131-3The IEC 61131-3 format is used to convert the input into a string
output. The format of the string is dependent on the type of input time value:
Input Type
Date

Output String Format (IEC 61131-3)


D#yyyy-MM-dd
For example, D#2011-12-03

Date and Time

DT#yyyy-MM-dd-hh:mm:ss.SSS
For example, DT#2011-12-03-13:43:24.341

Time of Day

TOD#hh:mm:ss.SSS
For example, TOD#22:31:14.313

Time

T#DdHhMmSsFms
Where D, H, M, S and F represent numerical values for day,
hour, minute, second and milliseconds, respectively. For
example:
T#16d21h19m25s13ms
Any element that is zero is omitted (unless all of the elements
are 0, in which case the string is T#0). For example, one and a
half hours is T#1h30m.
If the time is negative, a minus sign is added after the T#. For
example, minus 30 minutes is: T#-30m.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

PD-6017 07/2012

381

Chapter 10 - Logic Program Properties and Values

Define the Number of Instructions for a Logic Program


You can use the Instruction Limit setting to define the maximum number of instructions
permitted for a Logic program. The program will be aborted if this number of instructions
is reached before the program has been executed. This means that if a program contains
code errors that can cause an infinite loop, the Instruction Limit will stop the program
from using all of the CPU resources.
Each program has a number of instructions. The instructions are referred to as op codes.
You can see the op codes for a single execution of an ST program by using the Compile
with Diagnostics feature (see Compiling an ST Program or ST Library, on page 122).
When a program is executed, the system performs each instruction in turn. This continues
until each of the instructions in the program have been executed or the Instruction Limit
has been reached.
Normally, a program runs and has its instructions executed without affecting system
performance. This is because the default setting for the Instruction Limit is 10000, and it
would take a very large program to require this many instructions.
However, if there is an infinite loop in the program, the program will not be able to
complete. The system continues to perform each instruction in turn, but as the code or
diagram structure is badly constructed, the list of instructions cannot be completed. This
means that eventually the Instruction Limit is reached and the program is aborted.
The Instruction Limit feature prevents badly written programs from using all of the CPU
resources.

Example of a Program with an Infinite Loop Logic Error:


The following code is incorrect and contains a Logic error that causes an infinite loop:
PROGRAM NAME
VAR
i:INT := 20;
Count : INT;
END_VAR
WHILE i < 50 DO
Count := COUNT +1;
END_WHILE;
END_PROGRAM

In the example, the WHILE statement is used to increase the Count value by +1 when the i
value is less than 50. As the i value is defined as 20, it is less than 50 and so the count will
increase by 1this is an infinite loop as the program cannot end. The system would
continue to attempt to execute this program until the Instruction Limit was reached, at which
point it would abort the program.

382

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

To identify that the code contains a Logic error, you could examine the Logic Execution
Status List (a Query list). The list contains a Number of Instructions entry which shows the
number of instructions on the last execution of the program. If this number is approaching
the Instruction Limit or exceeds it, there may be a Logic error and you will need to
examine the code for an infinite loop. Of course, it may be that your program is very large
and has intentional loops and a very high number of instructions. If this is the case, you
may need to alter the Instruction Limit setting.
To change the Instruction Limit setting:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Enter the required maximum number of instructions per program in the Instruction Limit
field.

To configure the other Logic tab settings, see Configure an ST Program, Ladder Diagram,
SFC or FBD, on page 359.

PD-6017 07/2012

383

Chapter 10 - Logic Program Properties and Values

Define the Time Zone to be used for Calculations within the Logic
Program
If your Logic program makes use of time conversion functions such as
MAKE_DATE_AND_TIME_FROM_OPC, it needs to be able to interpret the relative parts of
the time values. For example, if an OPC Relative time is defined as 'DAY+5H', the
program needs to be able to determine whether DAY begins at midnight UTC, midnight
local time with Daylight Saving Time, or midnight local time without Daylight Saving Time.
By default, a Logic program will use Coordinated Universal Time (UTC).
By using the Program Time Zone setting, you can choose which time zone is to be used
when interpreting relative time values.
To change the Program Time Zone:
1.

Display the configuration Form for the relevant program (see Configure an ST Program,
Ladder Diagram, SFC or FBD, on page 359).

2.

Select the Logic tab.

3.

Use the Program Time Zone combo box to choose the appropriate time zone setting for
your Logic program:

Coordinated Universal Time (UTC)

Local Time without Daylight Saving Time

Local Time with Daylight Saving Time (for regional variations to GMT standard time,
such as British SummerTime).

The Program Time Zone setting that you choose is used for time conversions within the
Logic program (the Interval Offset Time Zone setting defines the time zone that is used
to determine when the program is executedsee Define the Interval Settings for a
Logic Program, on page 368).
4.

Save any changes that you have made to the configuration.

Further Information
Date and Time: See page 251.
Time Zones: see Time Zone Support in ClearSCADA, on page 189 in the ClearSCADA
Guide to Core Configuration.

384

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Configure an ST Library
You can use the ST Library Form to configure the settings for an ST Library. The Form
allows you to:

View the Name and configure the Help View for the ST Library. These settings are
available on the Identification tab. For more information, see Defining Identification
Details, on page 199 in the ClearSCADA Guide to Core Configuration.

Associate the ST Library with up to 4 custom pick actions by using the User Methods
tab. For more information, see Using the User Methods Tab to Define Custom Actions,
on page 203 in the ClearSCADA Guide to Core Configuration.

Choose the Color for Function Blocks Stored in ST Libraries

Create a ToolTip for an ST Library.

NOTE: You cannot use the ST Library Form to code the function block(s) for an ST Library.
You need to use the ST Library Editor to create the code (see Using Libraries in ST
Programs, on page 121).
To display the ST Library Form and configure its settings:
1.

In the Database Bar, right-click on the ST Library icon to display a context sensitive
menu.

2.

Select the Properties option to display the ST Library Form.


Use the Identification tab to set
the Help View for the ST Library.

Use the User Methods tab to associate the


ST Library with up to 4 custom actions.

Use the
Library tab to
set the color
for Function
Blocks in the
library and
define a
ToolTip.

3.

Use the Identification tab to define the Help View for the ST Library as required (see
Defining Identification Details, on page 199 in the ClearSCADA Guide to Core
Configuration).

4.

Use the User Methods tab to associate the ST Library with up to 4 custom pick actions
as required (see Using the User Methods Tab to Define Custom Actions, on page 203
the ClearSCADA Guide to Core Configuration).

PD-6017 07/2012

385

Chapter 10 - Logic Program Properties and Values

5.

Use the Colour button to set the color for Function Blocks that are stored in the ST
Library (see Choose the Color for Function Blocks Stored in ST Libraries, on page 386).

6.

Use the Comment field to enter a string that will be shown as a generic ToolTip for
function blocks that are stored in the ST Library (see Create a ToolTip for an ST Library,
on page 387).

7.

Save the ST Library Form.

Choose the Color for Function Blocks Stored in ST Libraries


You can use the Color button on the Library tab of the ST Library Form to define the color
for function blocks that are stored in the library. When a function block that is stored in the
library is added to a Function Block Diagram, the function block will be colored
accordingly. For example, if you choose red and then use one of the ST Library's function
blocks on a Function Block Diagram, the function block will be displayed in red.

This 'POWER' function block is stored in an


ST Library and is added to a Function Block
Diagram as a User Function Block. As the
ST Library has its Color setting to Red, the
function block is displayed in red.

To choose the color for a function block that is stored in the ST Library:
1.

Display the ST Library Form and select the Library tab (see Configure an ST Library, on
page 385).

2.

Select the Color button to display the Color Palette.

3.

Use the Color Palette to choose an existing system color or custom color or select the
... button to access the Color window. You can use the Color window to create a new
custom color. For more information on the Color Palette and Color window, see Using
the Color Window to Define a Color, on page 539 in the ClearSCADA Guide to Core
Configuration.

To configure the other Library tab settings, see Configure an ST Library, on page 385.

386

PD-6017 07/2012

Chapter 10 - Logic Program Properties and Values

Create a ToolTip for an ST Library


You can use the Comment field on the Library tab of the ST Library Form to create a
generic ToolTip for the function blocks that are stored in the ST Library. When one of the
function blocks is used as a user function block on a Function Block Diagram, the
diagrammatic version of the function block will be associated with the comment. When a
user positions the cursor over the function block, a ToolTip will be displayed containing
the comment. This feature is especially useful when you want to provide an indication as
to which ST Library contains the code for a function blockby providing details of the ST
Library in your comment, you can make it easy for other operators and engineers to locate
the ST Library that contains the function block.

Comment is shown
as a ToolTip

To create a generic comment for an ST Library ToolTip:


1.

Display the ST Library Form and select the Library tab (see Configure an ST Library, on
page 385).

2.

Enter the string for the ToolTip in the Comment field.

To configure the other Library tab settings, see Configure an ST Library, on page 385.

PD-6017 07/2012

387

Chapter 10 - Logic Program Properties and Values

OPC Properties for Logic Programs


Logic programs are represented in the ClearSCADA database by database items. Like
other database items, Logic programs have properties that can be accessed via OPC.
To view the properties for a Logic program:

388

1.

Select the OPC button on the Operate toolbar to display the OPC Bar in place of the
Database Bar.

2.

Expand the System icon, then expand the Root Group.

3.

Expand the hierarchy until you locate the required Logic program.

4.

Expand the program to reveal its tags. Each tag represents a property (and the value
that is stored for that property) of the Logic program. Further tags are located within the
Config tag.

5.

Position the cursor over any of the tags to display a brief description of the tag in a
ToolTip.

PD-6017 07/2012

Chapter 11 - Logic Data Types

11 Logic Data Types

Logic programs have values that use the data type names that are specified in the IEC
1131-3 standard. These data type names have different names in the Windows
Automation standard and the ClearSCADA code. This means that the name for the data
type of a value will vary depending on whether you access it in Logic, OPC (which uses
the Windows Automation standard), or the ClearSCADA Database Schema (which uses
the ClearSCADA code data type names).
In this section, we explain how to Display the OPC Data Type for a Property (see page
389). We also provide a table that shows the different data type names for each standard
(see Data Types for Logic, OPC, and ClearSCADA, on page 390) and information on how
the categories for data types (see Data Type Hierarchy, on page 392).

Display the OPC Data Type for a Property


You can view the OPC data type for any property in the database by performing the
following steps:
1.

Select the OPC button to display the OPC Data Bar.

2.

Expand the Root branch in the tree-structure.

3.

Continue to expand the branches until you have located the required property for the
relevant database item.

4.

Right-click on the database item property to display a context sensitive menu.

5.

Select the Display Value option to access the Value window.

6.

Examine the Data Type entry. This shows the OPC data type name for the value.

A table that shows the OPC data type names and their corresponding Logic and
ClearSCADA data type names is included in Data Types for Logic, OPC, and ClearSCADA
(see page 390).

PD-6017 07/2012

389

Chapter 11 - Logic Data Types

Data Types for Logic, OPC, and ClearSCADA


Each Logic program has values that are of a specific data type, for example, the Name
value of a point is a STRING data type. However, the name for the data type varies
depending on whether you access the value via Logic, OPC, or ClearSCADA (access the
value in the ClearSCADA database schema). For example, in Logic, the Name value of a
point is a STRING data type, whereas the Name value in OPC is a VT_BSTR data type.
The following table shows the names of the data types in Logic, OPC (automation), and
ClearSCADA:

Logic

OPC
(Automatio
n)

390

ClearSCAD
A
(shown on
Database
Schema)

Range

BOOL

VT_BOOL

Boolean

True or False

SINT

VT_I1

Byte

-128 to 127

INT

VT_I2

Word

-32768 to 32767

DINT

VT_I4

Long

-2147483648 to 2147483647

USINT

VT_UI1

UINT

VT_UI2

Unsigned
Word

0 to 65535

UDINT

VT_UI4

Unsigned
Long

0 to 4294967295

REAL

VT_R4

Float

32 bit precision floating point

LREAL

VT_R8

Double

64 bit precision floating point

TIME

VT_DATE

TIME_OF_DAY

VT_DATE

DATE

VT_DATE

DATE_AND_TIME

VT_DATE

Time

STRING

VT_BSTR

Variant

BYTE

VT_UI1

0 to 255

WORD

VT_I2

0 to 65535

DWORD

VT_I4

0 to 255

Time

Color

0 to 4294967295

PD-6017 07/2012

Chapter 11 - Logic Data Types

Internally, Logic uses:

A FILETIME to represent DATE, and DATE_AND_TIME. Conversion to VT_DATE usually


involves a small loss of precision, for example a VT_DATE is only accurate to a few uS,
whereas a FILETIME is accurate to 100nS. In the conversion to VT_DATE, the FILETIME
is rounded to the nearest 10uS. DATE and DATE_AND_TIME values can be mapped to
VT_DATE and VT_BSTR variant types.

A signed 64 bit integer to represent TIME types, where each increment represents 1mS.
TIME types can be mapped to a number of VARIANT types including VT_BSTR, VT_UI1,
VT_I2, VT_I4, VT_R4, VT_R8 and VT_VARIANT. For numeric values, the value is the
number mS, for VT_BSTR, the time value is converted to a string. The format of the
string is either day [-]hh:mm:ss.mmm, or an 61131 time constant T#XhYmZs depending
on the configuration of the program.

A FILETIME to represent TIME_OF_DAY. The actual value is offset to the unix epoch of
1-JAN-1970. Thus 1-JAN-1970 00:00:00.000 represents 00:00:00.000, and
1-JAN-1970 23:59:59.999 represents 23:59:59.999. Values outside of the range
1-JAN-1970 00:00:00.000 to 1-JAN-1970 23:59:59.999 are not strictly valid.
TIME_OF_DAY values cannot be mapped to VARIANT types.

The data types that are available to a function, function block etc. are organized into a
hierarchy. For more information, see Data Type Hierarchy, on page 392.
For more information on the ClearSCADA Database Schema, see Working with the
Database Schema, on page 19 in the ClearSCADA Guide to the Database.

PD-6017 07/2012

391

Chapter 11 - Logic Data Types

Data Type Hierarchy


Many functions and function blocks can use various types of values. To make things
simpler, the data types are grouped into categories. For example, the SUB function can
use LREAL, REAL, DINT, INT, SINT, UDINT, UINT, USINT, and TIME inputs. These data
types are part of the ANY_MAGNITUDE category. This means that when we state that the
SUB function has inputs that can be of the type ANY_MAGNITUDE, its inputs can be of
any data type that is in the ANY_MAGNITUDE category (as shown below).
The categories for the various data types are organized in a hierarchy as follows:

So, if a function is described as requiring inputs of the type ANY_BIT, it means that the
function's inputs can be DWORD, WORD, BYTE, or BOOL. ANY_BIT is the name of a
category; it is not a data type in its own right.
For information on the data types supported by each function and function block, see
Built-in Functions, Function Blocks, and Conversions, on page 223.

392

PD-6017 07/2012

Chapter 12 - Using Actions Associated with Logic Programs

12 Using Actions Associated with Logic Programs

Logic program database items provide access to a variety of actions, some of which are
designed specifically for use with Logic. In this section, we describe the purpose of these
Logic-specific pick actions, which include:

Disable Execution (see page 393)

Enable Execution (see page 394)

Execute (see page 394)

Restart Execution (see page 395)

Set Variable (see page 395).

Disable Execution
Associated with: ST Programs, Function Block Diagrams, Ladder Diagrams, Sequential
Function Charts
Security permission required to access this pick action: Configure
The Disable Execution action allows you to set a Logic program so that it cannot be
executed. Once you have selected the Disable Execution action for a Logic program, the
programs Execute method cannot be triggered (and the Execute action cannot be
selected).
If you use the Disable Execution action on a Logic program, that program will be unable to
execute again until its Enable Execution action is selected. If you select the Enable
Execution action, the Execute action and method for the Logic program become available
again, and so the Logic program can be triggered to execute when required.
You can see whether a Logic program has had its execution status set to disabled by
using the Status Display (the Execution status shows Enabled or Disabled). For more
information, see Logic Specific Status Attributes, on page 397.
Also see Enable Execution, on page 394.

PD-6017 07/2012

393

Chapter 12 - Using Actions Associated with Logic Programs

Enable Execution
Associated with: ST Programs, Function Block Diagrams, Ladder Diagrams, Sequential
Function Charts
Security permission required to access this pick action: Configure
By using the Enable Execution action, you can allow a Logic program to be executed via
the Execute action or Execute method. The Enable Execution action is only available on
Logic programs that currently cannot be executed (programs that previously had their
Disable Execution action selected).
You can see whether a Logic program has had its execution status set to enabled or
disabled by using the Status Display (the Execution status shows Enabled or Disabled).
For more information, see Logic Specific Status Attributes, on page 397.
Also see Disable Execution, on page 393.

Execute
Associated with: ST Programs, Function Block Diagrams, Ladder Diagrams
Security permission required to access this pick action: Configure
Use the Execute action to trigger a Logic program manually. When you select the Execute
action, the Logic program runs and the functionality provided by the program is applied.
For example, if you have a Logic program that calculates the average value of two input
points, when you select its Execute action, the program will read its inputs and calculate
the average value at that time.
You can only select the Execute action if the Logic programs execution status is set to
Enabled (see Enable Execution, on page 394) and the Logic program is configured to
allow manual execution (see Define whether a Logic Program can be Executed Manually,
on page 373).

394

PD-6017 07/2012

Chapter 12 - Using Actions Associated with Logic Programs

Restart Execution
Associated with: ST Programs, Function Block Diagrams, Ladder Diagrams, Sequential
Function Charts.
Security permission required to access this pick action: Configure
Use the Restart Execution action to reset a Logic programs internal variables to their
initial values and recalculate the next execution time (if the program executes On Interval).
When you select the Restart Execution action, all internal variables are reset to their initial
values and the Logic program is queued for execution immediately. Any intervals for
future executions are calculated from the time you selected Restart Execution (now). The
only exception to this is if the Logic program has a defined offset, in which case, when
you select the Restart Execution action, the offset is applied before the program is
queued for execution.
NOTE: The Restart Execution action is not applicable to ST Libraries.

Set Variable
Associated with: ST Programs, Function Block Diagrams, Ladder Diagrams, Sequential
Function Charts. This action is also available on ST Libraries but has no effect
Security permission required to access this pick action: Control
Use the Set Variable action to define the value for a variable in a Logic program. This is
useful when you need to test that a Logic program uses a variable as expected, prior to
setting the Logic program as live on your system. For example, lets say you create a
Logic program that is to trigger an action when a Boolean input variable is True. During
testing, you can use the Set Variable action to set the variable to True so that you can
check that the Logic program responds to the True value with the expected response.
When you select the Set Variable action for a Logic program, a Set Variable dialog box is
displayed. In the dialog box, enter the Name of the variable you want to set, then use the
Value field to define the test value. The defined value will be applied to the specified
variable and will remain in place until it is overwritten by a reported value or you set the
variable manually.

PD-6017 07/2012

395

Chapter 12 - Using Actions Associated with Logic Programs

396

PD-6017 07/2012

Chapter 13 - Logic Specific Status Attributes

13 Logic Specific Status Attributes

You can view the status of any Logic program by accessing its Status Display:
1.

In the Database Bar, right-click on the Logic program in which you are interested to
display its context sensitive menu.

2.

Select the View Status option to display the Logic programs Status Display.

The Status Display provides status information about the Logic program, including
attributes that are common to many types of database item such as Id and Full Name,
as well as the following Logic-specific status attributes:

PD-6017 07/2012

ExecutionHas three possible entries:

EnabledThe Logic program has been manually enabled via the Enable
Execution method. This means that the Logic program can be executed.

DisabledThe Logic program has been manually disabled via the Disable
Execution method. This means that the Logic program cannot be executed
unless a user manually enables the Logic program. However, if the Logic
program is copied or exported, the copy or export version will revert to the
default setting of Enabled and so could be executed.

Out of ServiceThe Logic program cannot be executed as it is set to out of


service in its configuration. The Logic program will not execute, even if the
Enable Execution method is usedit can only execute when it has the In
Service setting enabled in its configuration.

OverrunsThe number of times that the program has overrun. An overrun is when
the program is set to execute at a set interval, but it takes longer than the interval to
run. Overruns usually indicate that a Logic program is not running as often as
required. If a program is overrunning, you should investigate it thoroughly to
determine exactly why it is taking longer than expected to run, then make the
appropriate configuration changes. If a Logic program continues to overrun, it can
affect the running of other Logic programs.

Last ExecutionThe start time of the Logic programs latest execution.

Execution TimeThe length of time taken for the programs latest execution.

DebuggingIndicates whether a ViewX client has the Logic program open in


Debug mode (Yes or No). If the Debugging status is Yes, the Logic program will not
run and cannot execute as another user is debugging the program. Manual and
scheduled executions of the program cannot take place until the program is taken
out of debugging mode (and the Debugging status becomes No).

397

Chapter 13 - Logic Specific Status Attributes

398

PD-6017 07/2012

Schneider Electric Industries S.A.S.


35 rue Joseph Monier
CS 30323
92506 Rueil-Malmaison Cedex, France
PD-6017 18

www.scheider-electric.com

Design: Schneider Electric - ClearSCADA Development, UK


Production: Schneider Electric - ClearSCADA Development, UK

Potrebbero piacerti anche