0% found this document useful (0 votes)
22 views52 pages

Structured Text

Uploaded by

Andrei Kokurin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views52 pages

Structured Text

Uploaded by

Andrei Kokurin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

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 Data type conversion............................................................................................................ 14
4.4 Comparison operators and decisions................................................................................... 16
4.5 State machine - CASE statement.........................................................................................19
4.6 Loops.....................................................................................................................................21
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............................................................................................. 31
6.1 Pointers and references........................................................................................................31
6.2 Preprocessor for IEC programs............................................................................................ 31
7 Diagnostic functions........................................................................................................................... 32

8 Exercises............................................................................................................................................ 33
8.1 Exercise - Box lift..................................................................................................................33
8.2 Exercise - Dispersion mixer..................................................................................................34
9 Summary............................................................................................................................................ 36

10 Appendix...........................................................................................................................................37
10.1 Arrays.................................................................................................................................. 37
10.2 Exercise solutions............................................................................................................... 40

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 line of comment.*)


(*
These
Multi-line comment are several
lines of comment.
*)
// This is a general
Comment with "//" // text block.
// It contains comment.
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
Parentheses () 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 equals 38 *)

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


Solving an expression with parentheses:
Result := (6 + 7) * (5 - 3); (* Result equals 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.4 "Comparison operators and decisions"
• 4.5 "State machine - CASE statement"
• 4.6 "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. Operator
priorities should be taken into consideration. Parentheses 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 operators

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 operators

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 operator - 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 operators

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 operators, but with parentheses

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 parentheses.

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 Result
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.3 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 cautious 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.4 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 2. 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 18°C, the display should read


"Cold".

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


should read "Opt" (optimal).
3) If the temperature is over 25°C, 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 25°C. 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.5 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.

Figure 9: Overview of the CASE statement

TM246 - Structured Text 19


Command groups

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.

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

20 TM246 - Structured Text


Command groups

4.6 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.

There are two main types of loops: those where loop control begins at the top and those where it begins
at the bottom.
Loops where control begins at the top (FOR, WHILE) check the terminating 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.6.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

2 Specifying the keyword "BY" is optional.

TM246 - Structured Text 21


Command groups

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.3 "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

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.

22 TM246 - Structured Text


Command groups

Figure 12: Crane with five loads

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

Arrays are required for solving this exercise. Additional information on arrays can be found in
the attachment or in Automation Help.
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 37.

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 : USINT := 4;
END_VAR
Table 22: Suggestion for variable declaration

TM246 - Structured Text 23


Command groups

4.6.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

4.6.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

24 TM246 - Structured Text


Command groups

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.6.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
EXIT EXIT;
END_IF
UNTIL i > 5
END_REPEAT

TM246 - Structured Text 25


Command groups

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

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,
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 functionblock*)
TON_Bell();
(*-- read results*)
doBell := TON_Bell.Q;
Table 26: Debouncing a button with the TON() function block

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 functionblock*)
TON_Bell();
(*-- read results*)
doBell := TON_Bell.Q;
Table 27: 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 Automation Help.

28 TM246 - Structured Text


Functions, function blocks and actions

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


Setting the variable "diSwitch" should start the timer.

2) Call the CTU upward counter function block.


Setting the variable "diCountlmpuls," should increase the upward counter by 1 due to the rising
edge. Setting the variable "diReset" should reset the CV output to 0.

VAR
TON_Test : TON;
CTU_Test : CTU;
Declaration: diSwitch : BOOL;
diCountImpuls : BOOL;
diReset : BOOL;
END_VAR
Table 28: Suggestion for variable declaration

A more detailed description of the library function can be found in Automation Help. 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

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.

TM246 - Structured Text 29


Functions, function blocks and actions

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 29: Calling actions in the main program

Actions

30 TM246 - Structured Text


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 references to iSource*)
Table 30: 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 complete list of all available commands can be found in Automation Studio Help.

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

TM246 - Structured Text 31


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

32 TM246 - Structured Text


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

TM246 - Structured Text 33


Exercises

8.2 Exercise - Dispersion mixer

Here we are going to configure a mixing system that mixes water and paint into a dispersion.

Figure 19: Schematics of a paint mixing system

The mixing program will run according to the following procedure:


• The mixing program waits until the start button is pressed (gDiStart).
• Water (gDoWaterValve) is added to the container until the "gDiWaterOK" sensor is triggered.
• The mixing unit (gDoMixer) starts and paint (gDoColorValve) is added until the "gDiSens-
Full" sensor is triggered.
• The mixing time should take 30 seconds.
• The drain valve (gDoDrainValve) and drain pumpgDoDrainPump) are turned on to empty the
container.
• The draining process is complete when the "gDiSensLow" signal is triggered.
• The starting situation is restored.

Exercise: Implementing the dispersion mixer


The task at hand is to analyze the dispersion mixer process and then to program it step by step in Struc-
tured Text. To do so, carry out the following steps:

1) Sketch out the process.

34 TM246 - Structured Text


Exercises

° Define the steps.


° Define the transitions.
(transition conditions from one step to the next)
° Define the actions.
(program sections that are called directly in a step)

2) [optional] Determine which steps can be transferred to an IEC action.

3) Implementing the requirements in a Structured Text program

A timer block from the STANDARD library should be used to implement the mixing time. Ensure
that the timer is reset after the time expires.

TM246 - Structured Text 35


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. This pro-
gramming language is especially powerful when using arithmetic functions and formulating mathemati-
cal calculations.

36 TM246 - Structured Text


Appendix

10 Appendix

10.1 Arrays

Unlike variables of a primitive data type, values of the same data


type are outlined in arrays. Each individual element can be accessed
using the array's name and an index value.
The value of the array index 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 20: 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 value 123 to index 0*)
aPressure[0] := 123;
Table 31: 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 32: 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]"3. In both of these cases, an array with a starting index of 0 and
a maximum index of 9 will be created.

Task: Creating the "aPressure" array

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

2) Open the variable declaration window.

3) Declare the "aPressure" array.


3 This input method is only supported by the table editor in Automation Studio.

TM246 - Structured Text 37


Appendix

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 33: 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 \ Derived data types \ Arrays

38 TM246 - Structured Text


Appendix

Task: 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.

Multidimensional 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 (*Zählweise mit 0 beginnend*)
code Array2Dim[2,2] := 11;

Figure 21: Accessing the value


in Column 3, Row 3

Table 34: 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.

TM246 - Structured Text 39


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 35: 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 36: 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 37: IF statement

40 TM246 - Structured Text


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 38: Nested IF statement

Exercise: Fill level exercise


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

TM246 - Structured Text 41


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;
doLow := TRUE;
1..24: (*-- level is low*)
doLow := TRUE;
25..90:(*-- level is ok*)
doOk := TRUE;
ELSE (*-- level is high*)
doHigh := TRUE;
END_CASE
Table 39: 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 40: REPEAT statement, terminating search results, limiting cycles

42 TM246 - Structured Text


Appendix

Exercise: Crane total load


VAR CONSTANT
MAX_INDEX: USINT := 4;
END_VAR
VAR
Declaration: aWeights : ARRAY[0..MAX_INDEX] OF INT;
iCnt : USINT;
sumWeight : DINT;
avgWeight : INT;
END_VAR
sumWeight := 0;
FOR iCnt := 0 TO MAX_INDEX DO
Program code: sumWeight := sumWeight + aWeights[iCnt];
END_FOR
avgWeight := DINT_TO_INT (sumWeight / (MAX_INDEX + 1));
Table 41: 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 42: Calling TON and CTU

TM246 - Structured Text 43


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 43: Possible solution to the box lift exercise

44 TM246 - Structured Text


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;
ConvTopOn := TRUE;
selectLift := GETBOX;
END_IF

Table 43: Possible solution to the box lift exercise

TM246 - Structured Text 45


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 43: Possible solution to the box lift exercise

Exercise: Implementing the dispersion mixer


Variable declarations
(********************************************************************
* COPYRIGHT -- Bernecker + Rainer
********************************************************************
* Program: mixer
* File: mixer.var
* Author: Academy
* Created: February 04, 2015
********************************************************************
* Local variables of program mixer
********************************************************************)

46 TM246 - Structured Text


Appendix

(*state machine variables*)


VAR
sMixerState : enMixerStates := enWAIT_FOR_START;
END_VAR
(*Digital input signals*)
VAR
gDiStart : BOOL := FALSE;
gDiWaterOK : BOOL := FALSE;
gDiSensFull : BOOL := FALSE;
gDiSensLow : BOOL := FALSE;
END_VAR
(*Digital output signals*)
VAR
gDoWaterValve : BOOL := FALSE;
gDoColorValve : BOOL := FALSE;
gDoMixer : BOOL := FALSE;
gDoDrainPump : BOOL := FALSE;
gDoDrainValve : BOOL := FALSE;
END_VAR
(*Function block instance variables*)
VAR
TON_Mixer : TON;
END_VAR
Cyclic program section
(********************************************************************
* COPYRIGHT -- Bernecker + Rainer
********************************************************************
* Program: mixer
* File: mixerCyclic.st
* Author: Academy
* Created: February 04, 2015
********************************************************************
* Implementation of program mixer
********************************************************************)

PROGRAM _CYCLIC

(*reset all outputs - will be set in the individual states*)


gDoWaterValve := FALSE;
gDoColorValve := FALSE;
gDoMixer := FALSE;
gDoDrainValve := FALSE;
gDoDrainPump := FALSE;
TON_Mixer.IN := FALSE;

(* implementation of dispersion mixer state machine *)


CASE sMixerState OF
(*wait until operator starts process by start button*)
enWAIT_FOR_START:
IF gDiStart = TRUE THEN
sMixerState := enFILL_WATER;

TM246 - Structured Text 47


Appendix

END_IF

(*fill water into the reservoir until limit is reached*)


enFILL_WATER:
IF gDiWaterOK = TRUE THEN
sMixerState := enFILL_COLOR;
END_IF

gDoWaterValve := TRUE;

(*add color and mix dispersion until reservoir is full*)


enFILL_COLOR:
IF gDiSensFull = TRUE THEN
sMixerState := enMIX_TIME;
END_IF

gDoColorValve := TRUE;
gDoMixer := TRUE;

(*mix color and water until time is elapsed*)


enMIX_TIME:

TON_Mixer.IN := TRUE;
TON_Mixer.PT := T#30s;

IF TON_Mixer.Q = TRUE THEN


sMixerState := enBOTTLE_DISPERSION;
END_IF

gDoMixer := TRUE;

(*continue mixing and bottle dispersion until reservoir is empty*)


enBOTTLE_DISPERSION:
IF gDiSensLow = TRUE THEN
sMixerState := enWAIT_FOR_START;
END_IF

gDoDrainValve := TRUE;
gDoDrainPump := TRUE;
gDoMixer := TRUE;

END_CASE

(*call timer function block*)


TON_Mixer();

END_PROGRAM

48 TM246 - Structured Text


Offered by the Automation Academy

Offered by the Automation Academy

The Automation Academy provides targeted training courses for our customers as well as our own em-
ployees.
At the Automation Academy, you'll develop the skills you need in no time!
Our seminars make it possible for you to improve your knowledge in the field of automation engineering.
Once completed, you will be in a position to implement efficient automation solutions using B&R technol-
ogy. This will make it possible for you to secure a decisive competitive edge by allowing you and your
company to react faster to constantly changing market demands.

Seminars

Quality and relevance are essential components of our seminars. The


pace of a specific seminar is based strictly on the experience that course
participants bring with them and tailored to the requirements they face. A
combination of group work and self-study provides the high level of flexi-
bility needed to maximize the learning experience.
Each seminar is taught by one of our highly skilled and experienced
trainers.

Training modules
Topic categories:
Our training modules provide the basis for learning both at seminars ➯ Control technology
as well as for self-study. These compact modules rely on a consistent ➯ Motion control
didactic concept. Their bottom-up structure allows complex, interre- ➯ Safety technology
lated topics to be learned efficiently and effectively. They serve as
➯ HMI
the best possible companion to our extensive help system. The train-
ing modules are available as downloads and can be ordered as print- ➯ Process control
ed versions. ➯ Diagnostics and service
➯ POWERLINK and openSAFETY

ETA system

The ETA system provides realistic constructions for training, education


and laboratory use. Two different basic mechanical constructions can be
selected. The ETA light system offers a high degree of mobility, saves
space and is well-suited for lab work. The ETA standard system has a
sturdy mechanical structure and includes pre-wired sensors and actua-
tors.

Find out more!

Would you like additional training? Are you interested in finding out what the B&R
Automation Academy has to offer? You've come to the right place.
Detailed information can be found under the following link:
www.br-automation.com/academy

TM246 - Structured Text 49


Offered by the Automation Academy

50 TM246 - Structured Text


Offered by the Automation Academy

TM246 - Structured Text 51


V1.0.8.9 ©2017/12/15 by B&R, All rights reserved.
All registered trademarks are the property of their respective owners.
We reserve the right to make technical changes.

You might also like