Anda di halaman 1dari 48

TM246

Structured Text
Prerequisites and requirements
Training modules TM210 Working with Automation Studio
TM213 Automation Runtime
TM223 Automation Studio Diagnostics
Software Automation Studio 3.0.90 or higher
Hardware None

2 TM246 - Structured Text


Table of contents

TABLE OF CONTENTS

1 INTRODUCTION.................................................................................................................................. 4
1.1 Learning objectives................................................................................................................. 4
2 GENERAL INFORMATION.................................................................................................................. 5
2.1 Features of Structured Text.................................................................................................... 5
2.2 Editor functions....................................................................................................................... 6
3 BASIC ELEMENTS.............................................................................................................................. 8
3.1 Expressions............................................................................................................................. 8
3.2 Assignments............................................................................................................................ 8
3.3 Source code documentation: Comments................................................................................9
3.4 Order of operations...............................................................................................................10
3.5 Reserved keywords...............................................................................................................11
4 COMMAND GROUPS........................................................................................................................12
4.1 Boolean operations............................................................................................................... 12
4.2 Arithmetic operations............................................................................................................ 13
4.3 Comparison operators and decisions................................................................................... 16
4.4 State machine - CASE statement.........................................................................................19
4.5 Loops.....................................................................................................................................20
5 FUNCTIONS, FUNCTION BLOCKS AND ACTIONS........................................................................ 27
5.1 Calling functions and function blocks................................................................................... 27
5.2 Calling actions.......................................................................................................................29
6 ADDITIONAL FUNCTIONS, AUXILIARY FUNCTIONS..................................................................... 30
6.1 Pointers and references........................................................................................................30
6.2 Preprocessor for IEC programs............................................................................................ 30
7 DIAGNOSTIC FUNCTIONS............................................................................................................... 31

8 EXERCISES....................................................................................................................................... 32
8.1 Exercise - Box lift..................................................................................................................32
9 SUMMARY......................................................................................................................................... 33

10 APPENDIX........................................................................................................................................34
10.1 Arrays.................................................................................................................................. 34
10.2 Exercise solutions............................................................................................................... 37

TM246 - Structured Text 3


Introduction

1 INTRODUCTION

Structured Text is a high-level programming language. Its basic concept includes elements taken from
the languages BASIC, Pascal and ANSI C. With its easy-to-understand standard constructs, Structured
Text (ST) is a fast and efficient way of programming in the field of automation.

The following chapters will introduce you to the commands, keywords and syntax used in Structured
Text. Simple examples will give you a chance to use put these concepts into practice to make it easier
for you to understand them.

1.1 Learning objectives

This training module uses selected exercises to help you learn the basics of high-level language pro-
gramming with Structured Text (ST).
You will learn about the high-level language editor and Automation Studio's SmartEdit features.
You will learn the basic elements used in high-level language programming, as well as how to
use ST commands.
You will learn how to use command groups and arithmetic functions.
You will learn how to use comparison and Boolean operators.
You will learn how to call the elements used to control program flow.
You will learn how to work with reserved keywords.
You will learn the difference between actions, functions and function blocks, as well as how to
use them.
You will learn how to use the diagnostic functions available for high-level language program-
ming.

4 TM246 - Structured Text


General information

2 GENERAL INFORMATION

2.1 Features of Structured Text

General information
ST is a text-based, high-level language for programming automation systems. Its simple standard con-
structs make programming fast and efficient. ST uses many traditional features of high-level languages,
including variables, operators, functions and elements for controlling program flow.
The ST programming language is standardized in accordance with the IEC1

Features
Structured Text is characterized by the following features:
High-level, text-based language
Structured programming
Easy-to-use standard constructs
Fast and efficient programming
Self-explanatory and flexible
Similar to Pascal
Conforms to the IEC 61131-3 standard

Possibilities
Automation Studio supports the following functions:
Digital and analog inputs and outputs
Logical operations
Logical comparison expressions
Arithmetic operations
Decisions
Step switching mechanisms
Loops
Function blocks
Dynamic variables
Calling actions
Integrated diagnostics

1 The IEC 61131-3 standard is a worldwide applicable standard for programming languages used on program-
mable logic controllers. In addition to Structured Text, other programming languages such as Sequential
Function Chart, Ladder Diagram, Instruction List, and Function Block Diagram are defined.

TM246 - Structured Text 5


General information

2.2 Editor functions

The editor is a text editor with many additional functions. Commands and keywords are shown in color.
Areas can be expanded and collapsed. Autocomplete is available for variables and constructs (SmartE-
dit).

Figure 1: User program in the ST editor

The editor has the following functions and features:


Distinction between uppercase and lowercase letters (case sensitive)
Autocomplete (SmartEdit, <CTRL> + <SPACE>, <TAB>)
Inserting and managing code snippets (<CTRL> + q, k)
Identification of corresponding pairs of parentheses
Expanding and collapsing constructs (outlining)
Inserting block comments
URL recognition
Line modified marker

Programming \ Editors \ Text editors


Programming \ Editors \ General operations \ SmartEdit
Programming \ Editors \ General operations \ SmartEdit \ Code snippets
Programming \ Programs \ Structured Text (ST)

6 TM246 - Structured Text


General information

The editor for variable declaration supports the initialization of variables, constants, user data types and
structures. In addition, the used variables can be commented on and documented in doing so. The
declaration editors also support SmartEdit features.

Programming \ Editors \ Table editors \ Declaration editors

TM246 - Structured Text 7


Basic elements

3 BASIC ELEMENTS

The following section describes the basic elements of ST in more detail. Expressions, assignments, the
use of comments in the program code and reserved keywords, among others, are explained.

3.1 Expressions

An expression is a construct that returns a value after it has been calculated. Expressions consist of
operators and operands. An operand can be a variable, constant or function call. Operators are used to
connect the operands (3.4 "Order of operations"). Every expression must be ended in a semicolon (";"),
regardless of it concerning a function call or an assignment.

b + c;
(a - b + c) * COS(b);
SIN(a) + COS(b);
Table 1: Examples of expressions

3.2 Assignments

Assignments consists of a variable on the left side which is assigned the result of a calculation or ex-
pression on the right side using the assignment operator ":=". All assignments must be completed with
a semicolon ";".

Result := ProcessValue * 2; (*Result (ProcessValue * 2) *)


Table 2: Assignment takes place from left to right

When this line of code is executed, the value of the "Result" variable is twice the value of the
"ProcessValue" variable.

Accessing variable bits


It is also possible to only deal with particular bits when making assignments. To do so, simply place a
period (".") after the name of the variable. Access then takes place using the bit number, beginning with
0. Constants can also be used in the place of the bit number.

Result := ProcessValue.1;
Table 3: Accessing the second bit of "ProcessValue"

8 TM246 - Structured Text


Basic elements

3.3 Source code documentation: Comments

Comments are an important part of source code. They describe the code and make it more understand-
able and readable. Comments make it possible for you or others to understand a program long after it
has been completed. They are not compiled and have no influence on program execution. Comments
must be placed between a pair of parenthesis and asterisks, e.g. (*comment*).
An additional comment form is introduced with "//". Several lines can be selected in the editor and com-
mented out with one of the icons in the toolbar. This variant is an expansion to the existing IEC standard.

Figure 2: Commenting out a block of text

One-line comment (*This is a single comment line.*)


(*
These
Multi-line comment are several
lines of commenting.
*)
// This is a general
Comment with "//" // text block.
// It is commented out.
Table 4: Comment variations

Programming \ Editors \ Text editors \ (Un)commenting selections


Programming \ Structured software development \ Program layout

TM246 - Structured Text 9


Basic elements

3.4 Order of operations

The use of different operators brings up the question of priority. The priority of the operators is important
when solving an expression.
Expressions are solved by taking the operators with the highest priority into account first. Operators with
the same priority are executed from left to right as they appear in the expression.

Operator Syntax
Braces () Highest priority
Function call Call(Argument)
Exponent **
Negation NOT
Multiplication, division, modulo operator *, /, MOD
Addition, subtraction +, -
Comparisons <, >, <=, >=
Equality comparisons =, <>
Boolean AND AND
Boolean XOR XOR
Boolean OR OR Lowest priority

The resolution of the expression is performed by the compiler. The following examples show that different
results can be achieved through the use of parentheses.

Solving an expression without parentheses:


Result := 6 + 7 * 5 - 3; (* Result is 38 *)

Multiplication is performed first, followed by addition. Subtraction is performed last.


Solving an expression with parentheses:
Result := (6 + 7) * (5 - 3); (* Result is 26 *)

The expression is executed from left to right. The operations in parentheses are executed be-
fore the multiplication since the parentheses have higher priority. You can see that using paren-
theses can lead to different results.

10 TM246 - Structured Text


Basic elements

3.5 Reserved keywords

In programming, all variables must adhere to certain naming conventions. In addition, there
are reserved keywords that are already recognized as such by the editor and are shown in a
different color. These cannot be used a variables.
The libraries OPERATOR and AsIecCon are a standard part of new projects. The functions
they contain are IEC functions that are interpreted as keywords.
In addition, the standard also defines literals for numbers and character strings. This makes it
possible to represent numbers in different formats.

Programming \ Structured software development \ Naming conventions


Programming \ Standards \ Literals in IEC languages
Programming \ Programs \ Structured Text (ST) \ Keywords
Programming \ Libraries \ IEC 61131-3 functions

TM246 - Structured Text 11


Command groups

4 COMMAND GROUPS

The following command groups are the basic constructs of high-level language programming. These
constructs can be flexibly combined and nested within one another.
They can be categorized according to the following command group categories:
4.1 "Boolean operations"
4.2 "Arithmetic operations"
4.3 "Comparison operators and decisions"
4.4 "State machine - CASE statement"
4.5 "Loops"

4.1 Boolean operations

Boolean operators can be used to link variable values at the binary level. NOT, AND, OR and XOR are
differentiated between. The operands do not necessarily have to be of data type BOOL. However, the
order of operations should be considered. Brackets can be used.

Symbol Logical operation Examples


NOT Binary negation a := NOT b;
AND Logical AND a := b AND c;
OR Logical OR a := b OR c;
XOR Exclusive OR a := b XOR c;
Table 5: Overview of Boolean connectives

The truth table for these operations looks like this:

Input AND OR XOR


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Table 6: Truth table for Boolean connectives

Boolean operations can be combined in any way. Additional sets of parentheses increase program read-
ability and ensure that the expression is solved correctly. The only possible results of the expression are
TRUE (logical 1) or FALSE (logical 0).

12 TM246 - Structured Text


Command groups

Boolean connective - Comparison between Ladder Diagram and Structured Text

Figure 3: Linking normally open and normally closed contacts

doValveSilo1 := diSilo1Up AND NOT doValveSilo2 AND NOT doValveSilo3;


Table 7: Implementation with Boolean connectives

Parentheses are not needed since NOT has a higher priority than AND. Nevertheless, it is
always a good idea to use parentheses to make the program clearer.
doValveSilo1 := (diSilo1Up) AND (NOT doValveSilo2) AND (NOT
doValveSilo3);
Table 8: Implementation with Boolean connectives, but with brackets

Exercise: Light control


The output "DoLight" should be ON when the "BtnLigntOn" button is pressed and should remain ON until
the "BtnLightOff" button is pressed. Solve this exercise using Boolean operations.

Figure 4: On-off switch, relay with latch

4.2 Arithmetic operations

A key advantage of high-level programming languages is their easy handling of arithmetic operations.

Overview of arithmetic operations


Structured Text provides basic arithmetic operations for the application. Again, the order of operations
should be kept in mind when it's being used. For example, multiplication is carried out before addition.
The desired behavior can be achieved by using brackets.

Symbol Arithmetic operation Example


:= Assignment a := b;
+ Addition a := b + c;
- Subtraction a := b - c;
Table 9: Overview of arithmetic operations

TM246 - Structured Text 13


Command groups

Symbol Arithmetic operation Example


* Multiplication a:= b *c;
/ Division a := b / c;
MOD Modulo, remainder of integer division a := b MOD c;
Table 9: Overview of arithmetic operations

The data type of variables and values is always crucial to calculations. The result is calculated on the
right side of the expression and only then assigned to the corresponding variable. The result depends
on the data types and syntax (notation) being used. The following table illustrates this.

Data types
Expression / Syntax Results
Result Operand1 Operand2
Result := 8 / 3; INT INT INT 2
Result := 8 / 3; REAL INT INT 2.0
Result := 8.0 / 3; REAL REAL INT 2.66667
Result := 8.0 / 3; INT REAL INT *Error
Table 10: Performed by the compiler implicitly convert

The resulting value "*Error" stands for the following compiler error message "Error 1140: Incom-
patible data types: Cannot convert REAL to INT.". This is because it is not possible to
assign the expression to this particular data type.

4.2.1 Data type conversion

When programming, one is inevitably confronted with different data types. In principle, one can mix data
types within a program. Assignment of different data types is also possible. Nevertheless, you should
be caution with this.

Implicit data type conversion


Every time assignment is performed in the program code, the compiler checks the data types. In a
statement, assignments are always made from right to left. The variable must therefore have enough
space to hold the value. Converting from a smaller data type to a larger is carried out implicitly by the
compiler without any action required by the user.
Attempting to assign a value with a larger data type to a variable of a smaller data type will result in a
compiler error. In this case, explicit data type conversion is necessary.

Even if implicit data type conversion is carried out, it's still possible that an incorrect result
will occur depending on the compiler and what's being converted. One danger here involves
assigning an unsigned value to a signed data type.
This can lead to an overflow error when adding or multiplying. This depends on the platform
being used, however. The compiler does not issue a warning in this case.

14 TM246 - Structured Text


Command groups

Expression Data types Note


Result := Value; UINT, USINT No further action necessary
(*UINT USINT*) for implicit conversion

Result := Value; INT, UINT Caution when using negative


(*INT UINT*) numbers!

Result := value1 + value2; UINT, USINT, USINT Danger of range overflow


(*UINT USINT USINT*) when adding
Table 11: Examples of implicit data type conversion

Explicit data type conversion


Although implicit data type conversion is often the more convenient method, it should not always be the
first choice. Clean programming necessitates that types are handled correctly using explicit data type
conversion. The examples below highlight some of the cases where explicit conversion is necessary.

All variable declarations are listed in IEC format. Variable declarations can be entered in this
format in the text view of the .var file for the respective program.

Here there is the danger of an overflow error when the addition takes place:

VAR
TotalWeight: INT;
Declaration: Weight1: INT;
Weight2: INT;
END_VAR

Program code: TotalWeight := Weight1 + Weight2;


Table 12: An overflow error can occur directly to the right of the assignment operator.

In this case, the data type for the result must have enough space to hold the sum of the addi-
tion operation. As a result, a larger data type is necessary. When adding, at least one of the
operands must be converted to the larger data type. The conversion of the second operand is
then handled implicitly by the compiler.

VAR
TotalWeight: DINT;
Declaration: Weight1: INT;
Weight2: INT;
END_VAR
Program code: TotalWeight := INT_TO_DINT (Weight1) + Weight2;
Table 13: Overflow errors can be prevented by using explicit conversion.

On 32-bit platforms, the operands being calculated are converted to 32-bit values. In this case,
adding does not cause an overflow error.

TM246 - Structured Text 15


Command groups

Programming \ Variable and data types \ Data types \ Basic data types
Programming \ Libraries \ IEC 61131-3 functions \ CONVERT
Programming \ Editors \ Text editors
Programming \ Editors \ Table editors \ Declaration editors \ Variable declaration

Exercise: Aquarium
The temperature of an aquarium is measured at
two different places. Create a program that calcu-
lates the average temperature and passes it along
to an analog output. Don't forget that analog inputs
and outputs must be of data type INT.

Figure 5: Aquarium

VAR
aiTemp1: INT;
Declaration: aiTemp2: INT;
aoAvgTemp: INT;
END_VAR
Table 14: Suggestion for variable declaration

4.3 Comparison operators and decisions

In Structured Text, simple constructs are provided to compare variables. They return either the value
TRUE or FALSE. Comparison operators and logical operations are mainly used as conditions in state-
ments such as IF, ELSIF, WHILE and UNTIL.

Symbol Comparison type Example


= Equal to IF a = b THEN
<> Not equal to IF a <> b THEN
> Greater than IF a > b THEN
>= Greater than or equal to IF a >= b THEN
< Less than IF a < b THEN
<= Less than or equal to IF a <= b THEN
Table 15: Overview of logical comparison operators

16 TM246 - Structured Text


Command groups

Decisions
The IF statement is used to handle decisions in the program. You already know the comparison opera-
tors. These can be used here.

Keywords Syntax Description


IF .. THEN IF a > b THEN 1. Comparison
Result := 1; Statement if 1st comparison is TRUE
ELSIF .. THEN ELSIF a > c THEN 2nd Comparison
Result := 2; Statement if 2nd comparison is TRUE
ELSE ELSE Alternative branch, no comparisons
TRUE
Result := 3; Statement for the alternative branch
END_IF END_IF End of decision
Table 16: Syntax of an IF statement

Figure 6: IF - ELSE statement

Figure 7: IF - ELSIF - ELSE statement


Table 17: IF statements at a glance

Comparison expressions can be combined with Boolean operators so that multiple conditions can be
tested simultaneously.

Explanation: If "a" is greater than "b" and if "a" is less than "c", then "Result" is
equal to 100.
IF (a > b) AND (a < c) THEN
Program code: Result := 100;
END_IF;
Table 18: Using multiple comparison expressions

An IF statement can also include additional nested IF statements. It is important that there are not too
many nesting levels as this has a tendency to make the program too confusing.

TM246 - Structured Text 17


Command groups

The SmartEdit feature of the editor can be used to enter information more easily. If you want
to insert an IF statement, simply type in "IF" and then press the <TAB> key. This automatically
adds the basic structure of the IF statement in the editor.

Programming \ Programs \ Structured Text (ST) \ IF statement


Programming \ Editors \ General operations \ SmartEdit

Exercise: Weather station - Part I


A temperature sensor measures the outside temperature. This tem-
perature is read using an analog input and should be output as tex-
tual information inside the house.

1) If the temperature is below 18C, the display should read


"Cold".

2) If the temperature is between 18C and 25C, the display


should read "Opt" (optimal).
3) If the temperature is over 25C, the display should read "Hot".
Create a solution using IF, ELSIF and ELSE statements.

Figure 8: Thermometers

A variable of data type STRING is needed to output the text. The assignment can look like this:
sShowText := 'COLD';

Exercise: Weather station - Part II


Evaluate the humidity in addition to the temperature.
The text "Opt" should only appear when the humidity is between 40 and 75% and the temperature is
between 18 and 25C. Otherwise, "Temp. OK" should be displayed.
Solve this task using a nested IF statement.

If several IF statements are checking the same variable, then it's useful to think about whether
using a CASE statement might be a better, clearer solution.
The CASE statement has an additional advantages over the IF statement in that comparisons
only have to be made once, making the program code more effective.

18 TM246 - Structured Text


Command groups

4.4 State machine - CASE statement

The CASE statement compares a step variable with multiple values. If one of the comparisons matches,
the statements that are associated with that step are executed. If none of the comparisons match, then
the program code under the ELSE statement is executed, as is the case with the IF statement.
Depending on the application, the CASE statement can be used to set up state machines or automata.

Keywords Syntax Description


CASE .. OF CASE sStep OF Beginning of CASE
1,5: For 1 and 5
Show := MATERIAL;
2: For 2
Show := TEMP;
3, 4, 6..10: For 3, 4, 6, 7, 8, 9 and 10
Show := OPERATION;
ELSE ELSE Alternative branches
(*...*)
END_CASE END_CASE End of CASE

Only one step of the CASE statement is processed per program cycle.
The step variable must be a integer data type (e.g. USINT, UINT, UINT).

Figure 9: Overview of the CASE statement

Instead of fixed numerical values, constants or elements of enumerated data types should be
used in the program code. Replacing a value with text makes the program code must easier to
read. In addition, if these values need to be changed in the program, then the only change that
needs to take place is in the declaration itself, not in the program code.

TM246 - Structured Text 19


Command groups

Programming \ Programs \ Structured Text (ST) \ CASE statement


Programming \ Variables and data types \ Variables \ Constants
Programming \ Variables and data types \ Data types \ Derived data types \ Enumerations

Exercise: Level control


The level in a container should be monitored for three areas: low, high
and OK.
Use one output for each of the low, OK, and high levels.

The level of liquid in the tank is read as an analog value (0 - 32767) and
is converted internally to a percentage value (0-100%).

A warning tone should be given if the contents fall below 1%. Create a
solution using the CASE statement.

Figure 10: Evaluating the fill level of a


container

VAR
aiLevel : INT;
PercentLevel : UINT;
doLow : BOOL;
Declaration:
doOk : BOOL;
doHigh : BOOL;
doAlarm : BOOL;
END_VAR
Table 19: Suggestion for variable declaration

4.5 Loops

In many applications, it is necessary for sections of code to be executed repeatedly during the same
cycle. This type of processing is referred to as a loop. The code in the loop is executed until a defined
termination condition is met.
Loops are used to make programs clearer and shorter. The ability to expand the program's functionality
is also an issue here.
Depending on how a program is structured, it is possible that an error will prevent the program from
leaving the loop until the CPU's time monitoring mechanism intercedes. To avoid such infinite loops,
always provide a way to terminate the loop after a specified number of repetitions.

20 TM246 - Structured Text


Command groups

There are two main types of loops: those where loop control begins at the the top and those where it
begins at the bottom.
Loops where control begins at the top (FOR, WHILE) check the termination condition before entering
the loop. Loops where control begins at the bottom (REPEAT) check the condition at the end of the loop.
These will always be cycled through at least once.

4.5.1 FOR statement

The FOR statement is used to execute a program section for a limited number of repetitions. WHILE and
REPEAT loops are used for applications where the number of cycles is not known in advance.

Keywords Syntax
FOR .. TO .. BY2 .. DO FOR i:= StartVal TO StopVal BY Step DO
Res := Res + 1;
END_FOR END_FOR
Table 20: Elements of the FOR statement

The loop counter "index" is pre-initialized with the start value "Start-
Val". The loop is repeated until the value of the terminating variable FOR
"StopVal" is reached. Here, the loop counter is always increased by
1, known as the "BY step". If a negative value is used for the "step"
increment, then the loop will count backwards.
Index := StartVal
The loop counter, the start value and the end value must all have the
same data type. This can be achieved by explicit data conversion
(4.2.1 "Data type conversion").

Index > EndVal


If the starting and ending values are the same at the begin-
ning, this type of loop will cycle through at least once! (for
example, if the start value and end value are equal to 0) No

Statement (s )

Yes

Increase Index

END_FOR

Figure 11: Overview of the FOR


statement

2 Specifying the keyword "BY" is optional.

TM246 - Structured Text 21


Command groups

Programming \ Programs \ Structured Text (ST) \ FOR statement

Exercise: Crane total load


A crane can lift five loads at once. The load receptors are each connected to an analog input and return
values in the range of 0 to 32767. In order to calculate the total load as well as the average value, the
individual loads must first be added up and divided by the number of load sensors. Create a solution for
this exercise using a FOR loop.

Figure 12: Crane with five loads

VAR
aWeights : ARRAY [0..4] OF INT;
iCnt : USNT;
Declaration:
sumWeight : DINT;
avgWeight : INT;
END_VAR
Table 21: Suggestion for variable declaration

Arrays are required for solving this exercise. Further information on arrays can be found in the
appendix or in Automation Studio.
Where possible, use array declarations for the loads and constants to limit the loop's end values.
This considerably improves the readability of declarations and programs. Making changes later
also becomes much easier.

Programming \ Programs \ Variables and data types \ Data types \ Composite data types \
Arrays
See 10.1 "Arrays" on page 34

22 TM246 - Structured Text


Command groups

Exercise: Crane total load improving program code


Resulting from the previous task, the sum of the individual loads could be generated with the help of a
loop. Up to now, fixed numeric values are located in the variable declaration and in the program code.
The purpose of this task is to replace as many fixed numeric values as possible from declaration and
program code with constants.

VAR CONSTANT
Declaration: MAX_INDEX : INT := 4;
END_VAR
Table 22: Suggestion for variable declaration

4.5.2 WHILE statement

Unlike the FOR statement, WHILE loops do not rely on a loop counter. This type of loop is executed as
long as a condition or expression is TRUE. It is important to ensure that the loop has an end so that a
cycle time violation does not occur at runtime.

Keywords Syntax
WHILE .. DO WHILE i < 4 DO
Res := value + 1;
i := i + 1;
END_WHILE END_WHILE
Table 23: Executing a WHILE statement

The statements are executed repeatedly as long as the condition is


TRUE. If the condition returns FALSE the first time it is evaluated,
then the statements are never executed.

Figure 13: Overview of the WHILE


statement

Programming \ Programs \ Structured Text (ST) \ WHILE statement

TM246 - Structured Text 23


Command groups

4.5.3 REPEAT statement

A REPEAT loop is different from the WHILE loop as the termination condition is checked only after the
loop has executed. This means that the loop runs at least once, regardless of the termination condition.

Keywords Syntax
REPEAT REPEAT
(*program code*)
i := i + 1;
UNTIL UNTIL i > 4
END_REPEAT END_REPEAT
Table 24: Executing a REPEAT statement

The statements are executed repeatedly until the UNTIL condition


is TRUE. If the UNTIL condition is true from the very beginning, the
statements are only executed once.

If the UNTIL condition never takes on the value TRUE, the


statements are repeated infinitely, resulting in a runtime er-
ror.

Figure 14: Overview of the REPEAT


statement

Programming \ Programs \ Structured Text (ST) \ REPEAT statement

4.5.4 EXIT statement

The EXIT statement can be used in all of the different types of loops before the termination condition is
met. If EXIT is executed, the loop is terminated.

Keywords Syntax
REPEAT
IF setExit = TRUE THEN

24 TM246 - Structured Text


Command groups

Keywords Syntax
EXIT EXIT;
END_IF
UNTIL i > 5
END_REPEAT

Once the EXIT statement in the loop has been executed, the loop
is terminated, regardless of whether the termination condition or the
loop's ending value of the loop has been reached. In nested loops,
only the loop containing the EXIT statement is terminated.

Figure 15: The EXIT statement only


terminates the inner loop.

Programming \ Programs \ Structured Text (ST) \ EXIT statement

Exercise: Searching with termination


A list of 100 numbers should be searched to find one specific number. The list contains random numbers.
If the number 10 is found, the search process should be terminated. However, it's possible that the number
is not in the list.
Use the REPEAT and EXIT statements in your solution. Keep the two terminating conditions in mind.

VAR
Declaration: aValues : ARRAY[0..99] OF INT;
END_VAR

TM246 - Structured Text 25


Command groups

The individual elements of arrays can either be pre-initialized with values in the program code
or in the variable declaration window.

Programming \ Editors \ Table editors \ Declaration editors \ Variable declaration

26 TM246 - Structured Text


Functions, function blocks and actions

5 FUNCTIONS, FUNCTION BLOCKS AND ACTIONS

Various functions and function blocks extend the functionality of a programming language. Actions are
used to structure the program more effectively. Functions and function blocks can be inserted from the
toolbar.

Figure 16: Inserting functions and function blocks from the toolbar

5.1 Calling functions and function blocks

Functions
Functions are subroutines that return a particular value when called. One way a function can be called is
in an expression. The transfer parameters, also referred to as arguments, are the values that are passed
to a function. They are separated by commas.

VAR
sinResult : REAL;
Declaration:
xValue : REAL;
END_VAR
xValue := 3.14159265;
Program code:
sinResult := SIN(xValue);
Table 25: Calling a function with one transfer parameter

Programming \ Programs \ Structured Text (ST) \ Calling functions

Function blocks
A function block is characterized by the fact that it can take on several transfer parameters and return
multiple results.

Unlike a function, it is necessary to declare an instance variable that


has the same data type as the function block. The advantage here is
that a function block can handle more complex tasks by calculating
a result over a period of several cycles. By using different instances,
several multiple function blocks of the same type can be called with
different transfer parameters.

Figure 17: Transfer parameters (green)


and results (red) for the TON() function
block

When calling a function block, it is possible to pass all arguments or just some of them. Parameters and
results can be accessed in the program code using the elements of the instance variable.

TM246 - Structured Text 27


Functions, function blocks and actions

VAR
diButton : BOOL;
Declaration: doBell : BOOL;
TON_Bell : TON;
END_VAR
TON_bell(IN := diButton, PT := T#1s);
Call variant 1:
doBell := TON_bell.Q;
(*-- Parameters*)
TON_bell.IN := diButton;
TON_bell.PT := T#1s
Call variant 2: (*-- Call function block*)
TON_bell();
(*-- Read results*)
doBell := TON_bell.Q;
Table 26: Debouncing a button with the TON() function block

In the call for variant 1, all parameters are passed directly when the function block is called. In the call
for variant 2, the parameters are assigned to the elements of the instance variable. In both cases, the
desired result must be read from the instance variable after the call has taken place.

Programming \ Programs \ Structured Text (ST) \ Calling function blocks

Exercise: Function blocks


Call some of the function blocks in the STANDARD library. Prior to doing so, have a look at the function
and parameter descriptions found in the Automation Studio help system.

1) Call the TON turn-on delay function block.

2) Call the CTU upward counter function block.

A detailed description of library functions can be found in the Automation Studio help system.
Pressing <F1> opens the help documentation for the selected function block.
Many libraries also include different application examples that can be imported directly into the
Automation Studio project.

Programming \ Libraries \ IEC 61131-3 functions \ STANDARD


Programming \ Examples

28 TM246 - Structured Text


Functions, function blocks and actions

5.2 Calling actions

An action is program code that can be added to programs and libraries. Actions are an additional pos-
sibility for structuring programs and can also be formulated in a programming language other than the
program which calls it. Actions are identified by their names.
Calling an action is very similar to calling a function. The difference is that there are no transfer parame-
ters and a value is not returned.

If you use a CASE statement to control a complex sequence, for example, the contents of the
individual CASE steps can be transferred on to actions. This keeps the main program compact.
If the same functionality is needed elsewhere, then it's as easy as calling the action again.

CASE Sequence OF
WAIT:
IF cmdStartProc = 1 THEN
Sequence := STARTPROCESS;
END_IF

STARTPROCESS:
acStartProc; (*machine startup*)
Program:
IF Process_finished = 1 THEN
Sequence := ENDPROCESS;
END_IF

ENDPROCESS:
acEndProc; (*machine shutdown*)
(*...*)
END_CASE

ACTION acStartProc:
(*Add your sequence code here*)
Action:
Process_finished := 1;
END_ACTION
Table 27: Calling actions in the main program

Actions

TM246 - Structured Text 29


Additional functions, auxiliary functions

6 ADDITIONAL FUNCTIONS, AUXILIARY FUNCTIONS

6.1 Pointers and references

To extend the functionality of the existing IEC standard, B&R also offers pointers in ST. This allows a
dynamic variable to be assigned a particular memory address during runtime. This procedure is referred
to as referencing or the initialization of a dynamic variable.
Once the dynamic variable is initialized, it can be used to access to the contents of the memory address
it is "pointing" to. For this operation, the keyword ACCESS is used.

VAR
iSource : INT;
Declaration:
pDynamic : REFERENCE TO INT;
END_VAR
pDynamic ACCESS ADR(iSource);
Program code:
(*pDynamic reference to iSource*)
Table 28: Referencing a pointer

Extended IEC standard functionality can be enabled in the project's settings in Automation
Studio.

6.2 Preprocessor for IEC programs

In text-based programming languages, it is possible to use preprocessor directives. With regard to syn-
tax, the statements implemented broadly correspond to those of the ANSI C preprocessor.
These preprocessor commands are an IEC expansion. They must be enabled in the project settings.
Preprocessor directives are used for the conditional compilation of programs or entire configurations.
When turned on, compiler options enable functionality that affects how the compilation process takes
place.
A description and full list of available commands can be found in the Automation Studio help system.

Project management \ The workspace \ General project settings \ Settings for IEC compliance
Programming \ Programs \ Preprocessor for IEC programs

30 TM246 - Structured Text


Diagnostic functions

7 DIAGNOSTIC FUNCTIONS

Comprehensive diagnostic tools make the entire programming process more efficient. Automation Studio
includes several tools for troubleshooting high-level programming languages:
Monitor mode
Watch window
Line coverage
Tooltips
Debuggers
Cross reference

Diagnostics and service \ Diagnostics tool \ Debugger


Diagnostics and service \ Diagnostics tool \ Variable watch
Diagnostics and service \ Diagnostics tool \ Monitors \ Programming languages in monitor mode
\ Line coverage
Diagnostics and Service \ Diagnostic tools \ Monitors \ Programming languages in monitor mode
\ Powerflow
Project management \ The workspace \ Output window \ Cross reference

TM246 - Structured Text 31


Exercises

8 EXERCISES

8.1 Exercise - Box lift

Exercise: Box lift


Two conveyor belts (doConvTop, doConvBottom) are being used to transport boxes to a lift.
If the photocell (diConvTop or diConvBottom) is activated, the corresponding conveyor belt is stopped
and the lift is requested.
If the lift is not being requested, it returns to the appropriate position (doLiftTop, doLiftBottom).
When the lift is in the requested position (diLiftTop, diLiftBottom), the lift conveyor belt (doConvLift)
is turned on until the box is completely on the lift (diBoxLift).
The lift then moves to the unloading position (doLiftUnload). When it reaches the position (diLiftUnload),
the box is moved onto the unloading belt.
As soon as the box has left the lift, the lift is free for the next request.

Figure 18: Box lift

32 TM246 - Structured Text


Summary

9 SUMMARY

Structured Text is a high-level programming language that offers a wide range of functionality. It contains
everything necessary to create an application for handling a particular task. You now have an overview
of the constructs and capabilities possible in ST.

The Automation Studio help documentation contains a description of all of these constructs. Remem-
ber, this programming language is especially powerful when using arithmetic functions and formulating
mathematical calculations.

TM246 - Structured Text 33


Appendix

10 APPENDIX

10.1 Arrays

Unlike variables of a primitive data type, arrays are comprised of several variables of the same data
type. Each individual element can be accessed using the array's name and an index value.
The index used to access values in the array may not fall outside of the array's actual size. The size of
an array is defined when the variable is declared.
In the program, the index can be a fixed value, a variable, a constant or an enumerated element.

Figure 19: An array of data type INT with a range of 0 to 9 corresponds to 10 different array elements.

Declaring and using arrays


When an array is declared, it must be given a data type and a dimension. The usual convention is for
an array's smallest index value to be 0. It is important to note in this case that the maximum index for
an array of 10 elements is 9.

Declaration VAR
aPressure : ARRAY[0..9] OF INT := [10(0)];
END_VAR
Program code (*Assigning the value 123 to index 0*)
aPressure[0] := 123;
Table 29: Declaring an array of 10 elements, starting index = 0

If attempting to access an array element with index 10, the compiler outputs the following error
message:

Program code aPressure[10] := 75;


Error message Error 1230: The constant value '10' is not in range
'0..9'.
Table 30: Accessing an array index outside of the valid range

If an array of 10 elements should be declared, it can be done in the declaration editor with either
"USINT[0..9]" or "USINT[10]". In both of these cases, an array with a starting index of 0 and a
maximum index of 9 will be created.

Exercise: Creating the "aPressure" array

1) Add new "int_array" program in the Logical View

2) Open the variable declaration window.

34 TM246 - Structured Text


Appendix

3) Declare the "aPressure" array.

The array should contain 10 elements. The smallest array index is 0. The data type must be INT.

4) Use the array in program code.

Use the index to access the array in the program code. Use fixed numbers, constants and a variable
for this.

5) Force an invalid array access in the program code.

Access index value 10 of the array and then analyze the output in the message window.

When assigning aPressure[10] := 123;, the compiler reports the following error message.
Error 1230: The constant value '10' is not in range '0..9'.
The compiler is not able to check array access if the assignment is made using a variable.
index := 10;
aPressure[index] := 123;

Declaring an array using constants


Since using fixed numeric values in declarations and the program code itself usually leads to program-
ming that is unmanageable and difficult to maintain, it is a much better idea to use numeric constants.
The upper and lower indexes of an array can be defined using these constants. These constants can
then be used in the program code to limit the changing array index.

Declaration VAR CONSTANT


MAX_INDEX : USINT := 9;
END_VAR
VAR
aPressure : ARRAY[0..MAX_INDEX] OF INT ;
index : USINT := 0;
END_VAR
Program code IF index > MAX_INDEX THEN
index := MAX_INDEX;
END_IF
aPressure[index] := 75;
Table 31: Declaring an array using a constant

The program code has now been updated so that the index used to access the array is limited
to the maximum index of the array. An advantage of this is that arrays can be resized (larger
or smaller) without having to make a change in the program code.

Programming \ Variables and data types \ Data types \ Composite data types \ Arrays

TM246 - Structured Text 35


Appendix

Exercise: Calculating the sum and average value


The average value should be calculated from the contents of the "aPressure" array. The program has
to be structured in such a way that the least amount of changes to the program are necessary when
modifying the size of the array.

1) Calculate the sum using a loop.

Fixed numeric values may not be used in the program code.

2) Calculating the average value

The data type of the average value must be the same as the data type of the array (INT).

A constant that is already being used to determine the array size for the declaration of an array
variable can also be used as end value for the loop. When generating the average, the same
constant can also be used for division. A data type that is larger than the output data type (e.g.
DINT) must be used when adding up the individual array elements. The resulting value can then
be converted back to the INT data type using an explicit data type conversion.

Multi-dimensional arrays
Arrays can also be composed of several dimensions. The declaration and usage in this case can look
something like this:

Declaration VAR
Array2Dim : ARRAY [0..6,0..6] OF INT;
END_VAR
Program (*counting from 0*)
code Arry2Dim[2,2] := 11;

Figure 20: Accessing the value


in Column 3, Row 3

Table 32: Declaring and accessing a 7x7 two-dimensional array

An invalid attempt to access an array in the program code using a fixed number, a constant or
an enumerated element will be detected and prevented by the compiler.
An invalid attempt to access an array in the program code using a variable cannot be detected
by the compiler and may lead to a memory error at runtime. Runtime errors can be avoided by
limiting the array index to the valid range.

36 TM246 - Structured Text


Appendix

The IEC Check library can be imported into an Automation Studio project to help locate runtime errors.

Programming \ Libraries \ IEC Check library

10.2 Exercise solutions

Exercise: Light control


VAR
btnLightOn: BOOL;
Declaration: btnLightOff: BOOL;
doLight: BOOL;
END_VAR

Program code: doLight := (btnLightOn OR doLight) AND NOT bntLightOff;


Table 33: On-off switch, relay with latch

Exercise: Aquarium
VAR
aiTemp1 : INT;
Declaration: aiTemp2 : INT;
aoAvgTemp : INT;
END_VAR
aoAvgTemp := DINT_TO_INT((INT_TO_DINT(aiTemp1)
Program code:
+ aiTemp2) / 2);
Table 34: Explicit data type conversion before addition and after division

Exercise: Weather station - Part 1


VAR
aiOutside : INT;
Declaration:
sShowText : STRING[80];
END_VAR
IF aiOutside < 18 THEN
sShowText := 'Cold';
ELSIF (aiOutside >= 18) AND (aiOutside <= 25) THEN
Program code: sShowText := 'Opt';
ELSE
sShowText := 'Hot';
END_IF;
Table 35: IF - statement

TM246 - Structured Text 37


Appendix

Exercise: Weather station - Part 2


VAR
aiOutside : INT;
Declaration: aiHumidity: INT;
sShowText : STRING[80];
END_VAR
IF aiOutside < 18 THEN
sShowText := 'Cold';
ELSIF (aiOutside >= 18) AND (aiOutside <= 25) THEN
IF (aiHumid >= 40) AND (aiHumid <= 75) THEN
sShowText := 'Opt';
Program code: ELSE
sShowText := 'Temp. Ok';
END_IF
ELSE
sShowText := 'Hot';
END_IF;
Table 36: Nested IF statement

Exercise: Fill level exercise


VAR
aiLevel : INT;
PercentLevel : UINT;
doLow : BOOL;
Declaration:
doOk : BOOL;
doHigh : BOOL;
doAlarm : BOOL;
END_VAR
Table 37: CASE statement for querying values and value ranges

38 TM246 - Structured Text


Appendix

(*Scaling the analog input to percent*)


PercentLevel := INT_TO_UINT(aiLevel / 327);
(*Reset all outputs*)
doAlarm := FALSE;
doLow := FALSE;
doOk := FALSE;
doHigh := FALSE;

CASE PercentLevel OF
Program code:
0: (*-- Level alarm*)
doAlarm := TRUE;
1..24: (*-- level is low*)
doLow := TRUE;
25..90:(*-- level is ok*)
doOk := TRUE;
ELSE (*-- level is high*)
doHigh := TRUE;
END_CASE
Table 37: CASE statement for querying values and value ranges

Exercise: Searching with termination


VAR CONSTANT
MAXNUMBERS : UINT := 99;
END_VAR
Declaration: VAR
aNumbers : ARRAY[0..MAXNUMBERS] OF INT;
nCnt : INT;
END_VAR
nCnt := 0;
REPEAT
IF aNumbers[nCnt] = 10 THEN
(*Found the number 10*)
Program code: EXIT;
END_IF
nCnt := nCnt + 1;
UNTIL nCnt > MAXNUMBERS
END_REPEAT
Table 38: REPEAT statement, terminating search results, limiting cycles

TM246 - Structured Text 39


Appendix

Exercise: Crane total load


VAR CONSTANT
MAX_INDEX: UINT := 4;
END_VAR
VAR
Declaration: aWeights : ARRAY[0..MAX_INDEX] OF INT;
wCnt : INT;
sumWeight : DINT;
avgWeight : INT;
END_VAR
sumWeight := 0;
FOR wCnt := 0 TO MAX_INDEX DO
Program code: sumWeight := sumWeight + aWeights[wCnt];
END_FOR
avgWeight := DINT_TO_INT (sumWeight / (MAX_INDEX + 1));
Table 39: FOR statement, adding up weights

Exercise: Function blocks


VAR
TON_Test : TON;
CTU_Test : CTU;
Declaration: diSwitch : BOOL;
diCountImpuls : BOOL;
diReset : BOOL;
END_VAR
TON_Test(IN := diSwitch, PT := T#5s);
Program code:
CTU_Test(CU := diCountImpuls, RESET := diReset);
Table 40: Calling TON and CTU

40 TM246 - Structured Text


Appendix

Exercise: Box lift


VAR CONSTANT
WAIT : UINT:= 0;
TOP_POSITION : UINT:= 1;
BOTTOM_POSITION : UINT:= 2;
GETBOX : UINT:= 3;
UNLOAD_POSITION : UINT:= 4;
UNLOAD_BOX : UINT:= 5;
END_VAR

VAR
(*-- Digital outputs*)
doConvTop: BOOL;
doConvBottom: BOOL;
doConvLift: BOOL;
Declaration: doLiftTop: BOOL;
doLiftBottom: BOOL;
doLiftUnload: BOOL;
(*-- Digital inputs*)
diConvTop: BOOL;
diConvBottom: BOOL;
diLiftTop: BOOL;
diLiftBottom: BOOL;
diLiftUnload: BOOL;
diBoxLift: BOOL;
(*-- Status variables*)
selectLift: UINT;
ConvTopOn: BOOL;
ConvBottomOn: BOOL;
END_VAR
Table 41: Possible solution to the box lift exercise

TM246 - Structured Text 41


Appendix

doConvTop := NOT diConvTop OR ConvTopOn;


doConvBottom := NOT diConvBottom OR ConvBottomOn;
CASE selectLift OF
(*-- Wait for request*)
WAIT:
IF (diConvTop = TRUE) THEN
selectLift := TOP_POSITION;
ELSIF (diConvBottom = TRUE) THEN
selectLift := BOTTOM_POSITION;
END_IF
Program code:
(*-- Move lift to top position*)
TOP_POSITION:
doLiftTop := TRUE;
IF (diLiftTop = TRUE) THEN
doLiftTop := FALSE;
ConvBottomOn := TRUE;
selectLift := GETBOX;
END_IF

Table 41: Possible solution to the box lift exercise

42 TM246 - Structured Text


Appendix

(*-- Move lift to bottom position*)


BOTTOM_POSITION:
doLiftBottom := TRUE;
IF (diLiftBottom = TRUE) THEN
doLiftBottom := FALSE;
ConvBottomOn := TRUE;
selectLift := GETBOX;
END_IF

(*-- Move box to lift*)


GETBOX:
doConvLift := TRUE;
IF (diBoxLift = TRUE) THEN
doConvLift := FALSE;
ConvTopOn := FALSE;
ConvBottomOn := FALSE;
selectLift := UNLOAD_POSITION;
END_IF

(*-- Move lift to unload position*)


UNLOAD_POSITION:
doLiftUnload := TRUE;
IF (diLiftUnload = TRUE) THEN
doLiftUnload := FALSE;
selectLift := UNLOAD_BOX;
END_IF

(*-- Unload the box*)


UNLOAD_BOX:
doConvLift := TRUE;
IF (diBoxLift = FALSE) THEN
doConvLift := FALSE;
selectLift := WAIT;
END_IF
END_CASE
Table 41: Possible solution to the box lift exercise

TM246 - Structured Text 43


Training modules

TRAINING MODULES

TM210 Working with Automation Studio


TM213 Automation Runtime
TM223 Automation Studio Diagnostics
TM230 Structured Software Development
TM240 Ladder Diagram (LD)
TM241 Function Block Diagram (FBD)
TM242 Sequential Function Chart (SFC)
TM246 Structured Text (ST)
TM250 Memory Management and Data Storage
TM400 Introduction to Motion Control
TM410 Working with Integrated Motion Control
TM440 Motion Control: Basic Functions
TM441 Motion Control: Multi-axis Functions
TM450 ACOPOS Control Concept and Adjustment
TM460 Initial Commissioning of Motors
TM500 Introduction to Integrated Safety
TM510 Working with SafeDESIGNER
TM540 Integrated Safe Motion Control
TM600 Introduction to Visualization
TM610 Working with Integrated Visualization
TM630 Visualization Programming Guide
TM640 Alarms, Trends and Diagnostics
TM670 Advanced Visual Components
TM800 APROL System Concept
TM811 APROL Runtime System
TM812 APROL Operator Management
TM813 APROL XML Queries and Audit Trail
TM830 APROL Project Engineering
TM890 The Basics of LINUX
TM920 Diagnostics and service
TM923 Diagnostics and Service with Automation Studio
TM950 POWERLINK Configuration and Diagnostics

TM1010 B&R CNC System (ARNC0)


TM1110 Integrated Motion Control (Axis Groups)
TM1111 Integrated Motion Control (Path Controlled Movements)
TM261 Closed Loop Control with LOOPCONR
TM280 Condition Monitoring for Vibration Measurement
TM480 The Basics of Hydraulics
TM481 Valve-based Hydraulic Drives
TM482 Hydraulic Servo Pump Drives

44 TM246 - Structured Text


Training modules

TM246 - Structured Text 45


Training modules

46 TM246 - Structured Text


Training modules

TM246 - Structured Text 47


V1.0.7.1 2014/10/16 by B&R. All rights reserved.
All registered trademarks are the property of their respective owners.
We reserve the right to make technical changes.

Anda mungkin juga menyukai