Structured Text Programming: A Step by Step Guide (With Examples)

Do you find large ladder diagrams hard to read, including your own?

Although ladder logic is easy for beginners to learn, reading and understanding it can be difficult. For that reason, some programmers prefer Structured Text for PLC programming. This tutorial explains how it works.

Finding your way through a large ladder logic PLC program can be difficult. Technicians and electricians may find the language straightforward to learn but less straightforward to use. A ladder diagram that you understand may still confuse another programmer.

Try reading one of these ladder logic examples, and notice how long it takes you to understand the program.

For this kind of work, I prefer another PLC programming language: Structured Text.

Content of Structured Text Tutorial

What is Structured Text Programming?

Structured Text is PLC programming language defined by PLCOpen in IEC 61131-3. The programming language is text-based, compared to the graphics-based ladder diagram or Function Block Diagram.

A graphical language may seem the better choice for PLC programming at first. In my opinion, that applies only to smaller programs. A text-based program takes up much less space, making its flow and logic easier to read. For example, you can scale a PLC analog input or output with a single line of code or set an alarm for your SCADA system solution.

You can also combine programming languages, including function blocks containing functions written in Structured Text. Because the language is standardised, you can use it across different PLC brands. Siemens S7 PLCs are probably the most common in Europe at least. They support Structured Text. You can get started with the Siemens S7-1200 Starter Kit, which also introduces the Siemens PLC environment.

Read my reviews of the best PLC programming courses. These courses can help you learn to program different PLC types.

High-level Programming Languages

If you are already familiar with high-level programming languages such as PHP, Python and C, you will recognise parts of Structured Text. Its syntax resembles a high-level programming language, using loops and variables along with conditions and operators.

If you have never used a high-level language, Structured Text can introduce you to its syntax and concepts. Sometimes, starting with a simpler language helps you understand PLC logic first. For example, the Siemens LOGO Starter Kit is a programmable relay with a very simple visual programming language.

Before continuing, read this short PLC program written in Structured Text. Try to work out what it does and see whether any of its syntax looks familiar.

PROGRAM stexample
  VAR
    x : BOOL;
  END_VAR
  x := TRUE;
  REPEAT
    x := FALSE;
  UNTIL x := FALSE;
  END_REPEAT;
END_PROGRAM;

The Flow of Structured Text

Begin by learning the structure, or syntax, of Structured Text. Understanding that structure helps you follow the flow of your program.

In the example above, the program starts with PROGRAM and ends with END_PROGRAM. Your PLC program sits between these two delimiting keywords for program declarations. Keywords are explained later in the tutorial.

END_PROGRAM does not stop your program completely. When the PLC reaches END_PROGRAM, the PLC scan cycle starts again and repeats your program.

Structured Text Program Flow

Structured Text Program Flow.

As with ladder logic and other PLC languages, the program runs repeatedly. If you have programmed microcontrollers such as the Arduino UNO, the PROGRAM/END_PROGRAM construct will resemble an infinite loop in C.

NOTE:
When programming in Structured Text, you often do not write the PROGRAM/END_PROGRAM construct yourself. The PLC programming software supplies it, leaving you to write the code inside it.

Structured Text follows the same flow control as ladder logic: execute one line at a time.

Starting with the Syntax of Structured Text

The syntax of a programming language defines how that language is written, including the symbols that give it form and meaning.

Structured Text uses symbols such as colons and semicolons, as the example shows. These symbols identify operators and functions as well as statements and variables. Each character contributes to the meaning of the code.

The tutorial explains the syntax in detail as you progress. Start with these general Structured Text rules. You do not need to memorize all the syntax rules yet; you will learn them as you begin programming:

  • All statements are divided by semicolons
    Structured Text consists of statements and semicolons to separate them.
  • The language is not case-sensitive
    Even though it is good practice to use upper- and lowercase for readability, it’s not necessary.
  • Spaces have no function
    But they should be used for readability.

Before a Structured Text program can run, your computer translates it into a language the PLC understands.

When uploading a Structured Text program to the PLC, the programming software will compile your program. It translates your code into a form of machine code that can be executed by the PLC.

To understand your program, the compiler follows the rules of the programming language syntax.

For example, when the compiler reaches a semicolon, it recognises the end of the current statement. The compiler reads up to each semicolon and then executes that statement.

Comment Syntax

Textual programming languages let you add text that is not executed. Use this text for comments within your code.

As a beginner, always add comments to your code. Comments help you understand it when you return to it later.

Structured Text supports comments on a single line or across multiple lines.

Single line comment:

// comment

Comment after end of ST line:

<expression>; /* comment */

or

<statement>; (* comment *)

Multiple line comment:

/* start comment
...
end comment */

or

(* start comment
...
end comment *)

Should You Comment Every Detail?

As your programming improves, reduce the number of comments explaining functionality. This advice comes from The Tao of Programming, a programming book inspired by the old Chinese Tao Te Ching. More precisely, the principle behind the book explains the advice.

Take this little story in chapter 2.4:

A novice asked the Master: “Here is a programmer that never designs, documents or tests his programs. Yet all who know him consider him one of the best programmers in the world. Why is this?”

The Master replied: “That programmer has mastered the Tao. He has gone beyond the need for design; he does not become angry when the system crashes, but accepts the universe without concern. He has gone beyond the need for documentation; he no longer cares if anyone else sees his code. He has gone beyond the need for testing; each of his programs are perfect within themselves, serene and elegant, their purpose self-evident. Truly, he has entered the mystery of Tao.”

Although this story takes the idea to an extreme, write code that is easy to understand even without comments. Start by using spaces to make the code easier to read.

While you are still learning, do not worry about having too many comments. Add as many as you need.

Making Statements with Structured Text

Structured Text consists of statements. What does a statement do?

In everyday language, people and organisations make statements. You might make one yourself, as might a president or a company. A PLC programming statement follows a similar idea.

A statement is you telling the PLC what to do.

Let’s take the first statement as an example:

X : BOOL;

The compiler reads this as one statement because the semicolon marks where the statement ends. Separating statements with semicolons is the main syntax rule of this language.

With this statement, you tell the PLC to create a variable called X and that variable should be a BOOL type.

Using Variables in Structured Text

Before examining the statement further, return to the keywords mentioned earlier. The definition of variable X sits between two keywords: VAR and END_VAR.

PROGRAM/END_PROGRAM and VAR/END_VAR are both constructs. Each delimits a part of your program for a specific purpose: PROGRAM contains the PLC program, while VAR contains its variable definitions.

These four keywords are reserved words, so you cannot use them for other purposes in Structured Text. For example, you cannot name your program PROGRAM or program (STL is not case sensitive). That word is reserved for the construct that delimits the PLC program.

Now return to variables.

You may already know how variables work from another programming language.

If variables are new to you, watch this introduction:

A variable is a place where you can store data.

You can choose from several data types to match the kind of data you want to store. These different kinds of data are called data types. For example, a variable that stores either TRUE or FALSE, can be declared as a BOOL type.

The BOOL type is a boolean data type which means that it can contain a boolean value (TRUE or FALSE).

A variable has a data type and holds a value of that type. You also control another part of its definition: the variable name.

Each variable has a name so you can use it throughout the PLC program. Begin a variable definition in the VAR construct by writing that name:

X : BOOL;

This statement will create a variable called X, with a BOOL data type.

Some PLC software, including Siemens STEP 7 and Rockwell, does not use VAR/END_VAR for variable declarations. These variables are often called tags or symbols. Even in Structured Text, you declare them in a visual interface (shown below) or in a function block.

Variables, Tags or Symbols?

In PLC programming, variables are often called tags in the software. Studio 5000 Logix Designer for Allen Bradley PLCs uses tags. Older SIMATIC STEP 7 versions for Siemens PLCs use symbols, while newer STEP 7 versions, from TIA Portal version 11, use tags.

SIMATIC STEP 7 Tags

SIMATIC STEP 7 TIA Portal Variables called PLC tags.

Whatever the software calls variables, their function stays the same. IEC 61131-3 programming software such as STEP 7, Codesys or Studio 5000 always includes the standard data types.

Data Types in Structured Text

Depending on what PLC brand you are using, you will have some different data types available. In a Siemens PLC you have data types in STEP 7 available that are similar to the standard ones in IEC 61131-3. But you will also have other data types only used in SIEMENS PLC’s like the S5TIME.

The PLCOpen Organization defines the standard data types as part of the PLC programming languages. All PLC programming software with Structured Text includes them. The IEC standard divides data types into two categories: Elementary data types and derived data types.

Elementary data types

  • Integers
  • Floating points
  • Time
  • Strings
  • Bit strings

Under each elementary data types there are several IEC data types available. These are the data types defined in IEC 61131-3:

Integers:

IEC Data Type
Format Range
SINT Short Integer -128 … 127
INT Integer -32768 … 32767
DINT Double Integer -2^31 … 2^31-1
LINT Long Integer -2^63 … 2^63-1
USINT Unsigned Short Integer 0 … 255
UINT Unsigned Integer 0 … 2^16-1
LDINT Long Double Integer 0 … 2^32-1
ULINT Unsigned Long Integer 0 … 2^64-1

Floating points:

IEC Data Type
Format Range
REAL Real Numbers
±10^±38
LREAL Long Real Numbers ±10^±308

Time:

IEC Data Type
Format Use
TIME Duration of time after an event T#10d4h38m57s12ms
TIME#10d4h38m
DATE Calendar date D#1989-05-22
DATE#1989-05-22
TIME_OF_DAY Time of day TOD#14:32:07
TIME_OF_DAY#14:32:07.77
DATE_AND_TIME Date and time of day DT#1989-06-15-13:56:14.77
DATE_AND_TIME#1989-06-15-13:56:14.77

Strings:

IEC Data Type
Format Range
STRING Character String ‘My string’

Bit strings:

IEC Data Type
Format Range
BOOL Boolean 1 bit
BYTE Byte 8 bits
WORD Word 16 bits
DWORD Double Word 32 bits
LWORD Long Word 64 bits

Derived data types

  • Structured data types
  • Enumerated data types
  • Sub-ranges data types
  • Array data types

Derived data types are custom data types that you define yourself. Build them with the keywords TYPE and END_TYPE, placing the kind of derived data type you want to declare between those keywords.

These data types may seem overwhelming at first, especially if you have never used a textual programming language. You do not need to learn them all at once.

You need only a few data types to begin programming in Structured Text. As your skills develop and your programs become more complicated, you will learn more types by using them. Make sure that you don’t move ahead too fast. Take time to learn the basics properly.

Each data type holds a different format of data and therefore a different range of values.

How do you assign values to variables and use those variables?

With statements and operators.

Operators and Expressions in STL

The next thing you should know about is operators. Operators are used to manipulate data and are a part of almost any programming language. This leads us to the second thing you should know about – expressions.

Programming languages use expressions together with operators to work with data.

An expression is a construct that, when evaluated, yields a value.

When compiling an expression, the compiler evaluates it and replaces the statement with the result. This example uses the variables A and B.

A contains the value 10 and B contains 8.

A+B

The result of this expression is 18. So instead of A+B, the compiler will put in the value 18.

An expression is composed of operators and operands.

What do operators and operands do?

The expression above contains an operator and two operands. A and B are the operands, while + is the operator.

Programming language expressions with operands and operators

Programming language expressions with operands and operators.

Operators manipulate data. Here, + takes the value of variable A and adds it to the value in B.

Because + performs addition, it is called the addition operator.

Operators

There are several operators available in Structured Text. Again, IEC 61131-3 describes all the standard operators in the Structured Text language:

Operation
Symbol Precedence
Parenthesization (expression) Highest
Function Evaluation MAX(A,B)
Negation
Complement
–
NOT
Exponentiation **
Multiply
Divide
Modulo
*
/
MOD
Add
Subtract
+
–
Comparison <, >, <=, >=
Equality
Inequality
=
<>
Boolean AND
Boolean AND
&
AND
Boolean Exclusive OR XOR
Boolean OR OR Lowest

The table above lists operators by precedence. This is also called order of operations, which you may recognise from mathematics.

The order of operations determines which calculations run first. Consider this expression:

A + B * MAX(C, D)

In what order will the compiler evaluate this expression?

As you can see in the table of operators the operator with the highest precedence is a parenthesis. This means that the first thing, that will be evaluated, is everything in parenthesizes – in this example: (C, D).

MAX(C, D) is a function, so move down one row in the table to function evaluation.

So, in the above expression, the first thing that will be evaluated is the function: MAX(C, D). The function will yield (replace the function) with the answer. Which in this case is the highest of the two variables C and D.

Suppose C is the result. The expression then becomes:

A + B * C

Continue down the table until you reach the next operator used by the expression.

Multiplication and addition remain. Multiplication has the higher precedence, so it is evaluated first.

First calculate B * C, then add that result to A.

Each expression follows the order of precedence shown in the table above when it is evaluated.

4 Types of Operators, 4 Types of Expressions

The operators used for expressions in Structured Text can be divided into four groups. Each group of operators will have a specific function and will yield a specific data type.

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators

Arithmetic Operators

All the arithmetic operators are often just called mathematical operators because they represent the math. The result will always be the mathematical result of the expression.

  • + (add)
  • – (subtract/negate)
  • * (multiply)
  • ** (exponent)
  • / (divide)
  • MOD (modulo divide)

Example:

15 MOD 4

Result:

3

Relational Operators

To compare or find a relation between two values you can use one of the relational operators. They are used for comparison and the result will be a boolean value (BOOL type), either TRUE or FALSE.

  • = (equal)
  • < (less than)
  • <= (less than or equal)
  • > (greater than)
  • >= (greater than or equal)
  • <> (not equal)

Example:

TEMPERATURE := 93.9;
TEMPERATURE >= 100.0

Result:

FALSE

Logical Operators

If you want to compare boolean values (BOOL) and make some logic out of it, you have to use logical operators. These operators also yield a boolean value of TRUE or FALSE as a result of the expression.

  • & or AND
  • OR
  • XOR
  • NOT

Example:

LIMIT_SWITCH1 := TRUE;
LIMIT_SWITCH2 := FALSE;
LIMIT_SWITCH1 OR LIMIT_SWITCH2

Result:

TRUE

Bitwise Operators

The last group of operators is called bitwise operators because the operations are performed bitwise. It simply means that a logic operation is performed for each bit of two numbers. A result is a new number – the total result of the bitwise operations.

  • & or AND
  • OR
  • XOR
  • NOT

Example:

15 AND 8

Result:

15

A bitwise operation calculates the result one bit at a time. Convert the numbers to binary to follow the calculation:

15 = 1111
8 = 1000

Now each bit in the number 1111 (15) can be used in a logical operation with the other number 1000 (8):

1111 AND 1000
Bit number 1111 (15) 1000 (8) Result
0 1 1 1
1 1 0 0
2 1 0 0
3 1 0 0

Operators and Statements

So, in the previous section, you learned that expressions evaluate. Meaning that all expressions will yield the result and the compiler will replace the expression with the result.

What if you want the PLC (compiler) to take action and DO something?

Statements are the answer.

A statement instructs the PLC to take action, as described earlier. It tells the PLC what you want it to do.

An expression produces a calculation result. That result does little unless a statement uses it to take action, much as buying groceries does not make a meal until you cook them.

Now look at the statements you can use to take action in Structured Text.

Assignment Statement and Operator

There are several statements available in Structured Text. Each specifies an action or a condition.

The most fundamental action in Structured Text uses the assignment statement. The IEC standard developed by PLCOpen describes statements too, listing assignment first.

An assignment statement looks like this:

A := B;

Which action does this statement tell the compiler to take?

To take the value of the variable B and put it in the variable A.

The PLC is assigning a value to a variable. Here’s an even simpler example:

A := 10;

This statement will take the value 10 and put it into the variable A. Or said in another way – the variable A will be assigned the value 10.

Now that A holds 10, use it in an expression within another statement:

B := A + 2;

When this line of code is compiled, the expression A + 2 will be evaluated to 12. The compiler will replace the expression with the result 12. The statement will now look like this to the compiler:

B := 12;

The compiler now assigns 12 to variable B.

Assignment statement and expressions

How an assignment statement with expression will be evaluated by the compiler.

The symbol := is the assignment operator. Operators also appear in expressions, and confusing the two types often leads to using the wrong one.

One common mistake is using equality (=) in place of assignment (:=). The symbols look similar but do very different things. Compare these examples:

A = B
A := B;

The first line is an expression. Since this is an expression, the operator will be used to evaluate the line. The equality operator evaluates in the following way:

When the left and right sides are equal, the expression evaluates to TRUE or 1. Otherwise, it evaluates to FALSE or 0.

Equality is a relational operator. Other operators belong to this group too. Every relational operator evaluates to TRUE or FALSE.

The second line is a statement. Its operator takes action through assignment, giving A the value held in B.

You can identify a statement by its semicolon. This marks the end of the statement for the compiler.

You can have all sorts of expressions in your assignment statements, from simple values like numbers to variables and functions. Because all expressions will be evaluated first, and then, the result of that evaluation will be used in the assignment statement.

Conditional Statements

Well, the assignment statement was pretty simple: Take the value of the right side and store it in what’s on the left side.

Consider how this fits into a PLC program. The program is a piece of logic (I call it PLC logic) that must make decisions. We use a PLC or another controller to decide what to do and act on the current state.

In simple terms, the PLC checks all input states and follows your program to decide which outputs to set.

Your PLC program uses conditional statements to make those decisions.

Conditional statements are used for exactly that: To make decisions.

There are two ways of doing conditional statements in Structured Text: IF statements and CASE statements.

IF Statements

I think Bill Gates is better at explaining the IF statement than I am. At least he can explain it in just over 1 minute in this great video from code.org. You can skip the video if you are familiar with IF statements, although I would recommend that you watch it.

IF statements are decisions with conditions.

Although IF statements are simple to understand, you need the correct syntax to give these conditional instructions to the PLC.

An IF statement must follow specific syntax for the compiler to understand it. Just as semicolons end statements, specific keywords define an IF statement.

Here’s how the syntax for IF statements look like in STL:

IF [boolean expression] THEN
  <statement>;
ELSIF [boolean expression] THEN
  <statement>;
ELSE
  <statement>;
END_IF ;

Notice that the syntax for IF statements look very similar to plain English. The first line contains two keywords: IF and THEN. Between those two keywords is the condition, which is an expression. But not just any expression. A boolean expression.

Boolean and Numeric Expressions

You can divide expressions into two groups depending on what they yield.

Boolean expressions evaluates to a BOOL type value, TRUE or FALSE.

Here’s an example of a boolean expression:

1 = 1

This expression will evaluate to or yield TRUE. A boolean expression could also look like this:

1 > 2

But this time the boolean expression will evaluate to FALSE, since 1 is not larger than 2.

Numeric expressions evaluates to an integer or a floating point number.

A numeric expression could look as simple as this one:

13.2 + 19.8

This expression will evaluate to the floating-point number 33.0, and therefore is a numeric expression.

Boolean expressions are used in IF statements as conditions.

IF the boolean expression evaluates to TRUE, THEN the following statements will be executed.

The PLC will only execute the statements after the keyword THEN, if the expression evaluates to TRUE. This is illustrated by the following example:

A := 0;
IF A = 0 THEN
  B := 0;
END_IF ;

Line number 3 will only be executed if A is equal to 0. In this case it will. A 0 is assigned to the variable A in a statement right before the IF statement.

This example makes a decision.

The decision above depends on the value of a variable. Even this simple example translates directly into real PLC programming.

Let’s say you want to make a program that sets a PLC output depending on the state of input. With a simple IF statement you can do that in Structured Text:

IF INPUT1=TRUE THEN
  OUTPUT1 := TRUE;
END_IF;

Although this example is just a piece of a bigger program (INPUT1 is the input variable and OUTPUT1 the output variable) it illustrates how the decision for a PLC output can be made. The OUTPUT1 variable will only be set to TRUE IF the INPUT1 variable is TRUE.

Since, both the INPUT1 and OUTPUT1 variables are of the type BOOL, the first line in the statement could also look like this:

IF INPUT1 THEN

Just writing the expression as “INPUT1” will still evaluate as TRUE, when the variable is TRUE.

What ELSE IF not?

For now, you’ve seen a simple IF statement, where statements are only executed if an expression is TRUE. If that expression evaluates to FALSE the statements will simply not be executed.

How do you handle multiple conditions in your PLC program?

You could write separate IF statements for each condition. Structured Text also lets you handle them within an IF statement.

As in most other programming languages, use the ELSIF and ELSE keywords for multiple conditions in the same IF statement.

Both ELSIF and ELSE are optional in IF statements, but this is how the syntax looks like:

IF [boolean expression] THEN
  <statement>;
ELSIF [boolean expression] THEN
  <statement>;
ELSE
  <statement>;
END_IF ;

If the boolean expression on line 1 is FALSE, the statements below will simply not be executed. Instead, the compiler will check the boolean expression after the ELSIF keyword.

ELSIF follows the same rule as IF: when its boolean expression is true, the statements that follow are executed.

The final keyword is ELSE, the default option in an IF statement. When every IF and ELSIF expression evaluates to FALSE, the statements following ELSE are executed.

IF statements in Structured Text

How the PLC will execute IF statements in Structured Text.

Combining Operators for Advanced Conditions

Besides making multiple conditions you can also expand your conditions to include multiple variables.  You can combine multiple expressions, typically done with a logical operator, to get a larger expression.

Suppose 1 input being TRUE is insufficient and you need 2 TRUE inputs before setting an output. Write the expression like this:

IF (INPUT1) AND (INPUT2) THEN
  OUTPUT1 := TRUE;
END_IF;

Now the expression will evaluate to TRUE, only if INPUT1 and INPUT2 is TRUE.

CASE Statements

The second way of making decisions in Structured Text is with CASE statements.

CASE statements make decisions like IF statements, but use numeric expressions in place of boolean expressions. Their syntax also differs slightly, making CASE more suitable for some tasks.

This is how the syntax for CASE statements looks like in Structured Text:

CASE [numeric expression] OF
  result1: <statement>;
  resultN: <statemtent>;
ELSE
  <statement>;
END_CASE;

In CASE statements there is only 1 expression. The result of that expression is then used to decide which statements are executed.

CASE statements also use ELSE for a default option. Its statements run only when none of the cases matches the numeric expression result.

Here’s a very simple example:

PROGRAM_STEP := 3;
CASE PROGRAM_STEP OF
  1: PROGRAM_STEP := PROGRAM_STEP+1;
  2: PROGRAM_STEP := PROGRAM_STEP+2;
  3: PROGRAM_STEP := PROGRAM_STEP+3;
ELSE
  PROGRAM_STEP := PROGRAM_STEP+10;
END_CASE;

Although this is a very simple example (the variable has a fixed value) the example shows you how to make a decision depending on the result of a numeric expression. In this example, the numeric expression is simply just the value of the variable, 3. If could be any expression that evaluates to an integer or a floating-point value.

Iteration with Repeating Loops

Probably one of the most powerful features in Structured Text is the ability to make loops that repeat lines of code.

Once again, Code.org has made one of the best introductions to repeating loops. This time, Facebook founder, Mark Zuckerberg uses a little more than a minute to explain repeating loops.

PLC programming uses loops for many purposes. A loop can run a function or set of statements a fixed number of times, or keep running until a condition stops it.

In Structured Text you will find 3 different types of repeating loops:

  1. FOR
  2. WHILE
  3. REPEAT

Every type of loop has a condition that controls whether it repeats or stops. In FOR and WHILE loops, the condition determines whether to repeat or not. A REPEAT loop instead uses an UNTIL condition to decide whether to stop or not.

FOR Loops

A FOR loop repeats a specified number of times. Along with FOR, it uses the keywords TO, BY, DO and END_FOR.

This is the syntax of FOR loops in Structured Text:

FOR count := initial_value TO final_value BY increment DO
  <statement>;
END_FOR;

The first line is easier to follow when you break it into parts:

FOR
Keyword that starts the FOR loop statement.

count := initial_value
This assignment sets the starting value for the count. The variable is named count, and initial_value is the value it starts from.

TO
The keyword before the value to count up to.

final_value
This is the value you want to count to. Place 100 here and your loop will count up to 100.

BY
This keyword lets you specify a custom increment.

increment
The value of which you want to increase the count for every time the loop runs. If you set the increment to 10 and the count to 100, the loop will run 10 times.

DO
<statement>;
END_FOR;
The statements between DO and END_FOR run each time the loop repeats. Put the statements you want to repeat in this part of the loop.

A FOR loop repeats a preset number of times. In a PLC program, that could suit an item that must be painted/dried four times. A FOR loop that counts to four fits that task.

At last, you can use an IF statement with the keyword EXIT to stop the loop before the count. You can add a boolean condition that if TRUE stops the loop.

IF [boolean expression] THEN
  EXIT;
END_IF;

WHILE Loops

The while loop is a little different from the FOR loop, because it is used to repeat the loop as long as some conditions are TRUE. A WHILE loop will repeat as long as a boolean expression evaluates to TRUE.

Here’s the syntax of WHILE loops:

WHILE [boolean expression] DO
  <statement>;
END_WHILE;

Between the WHILE and DO keywords are the boolean expression. If that boolean expression evaluates to TRUE, all the statements until the END_WHILE keyword will be executed.

At END_WHILE, the boolean expression is evaluated again. The loop repeats while the expression remains TRUE. To stop it, change a value used by the expression so that the result becomes FALSE.

Here’s an example of a WHILE loop in Structured Text:

counter := 0;
WHILE counter < 10 DO
  counter := counter + 1;
  machine_status := counter * 10;
END_WHILE;

If you look at the third line you will see how the loop will eventually stop repeating.  The boolean expression uses the counter variable and checks if its value is less than or equal to 10. But since the value of the counter is set to 0 right before the WHILE loop, the boolean expression will be TRUE unless the counter is changed.

Line 3 changes that value. As the first statement inside the WHILE loop, it runs with the other statements on every repetition. The third line increases the counter variable by 1, giving an increment of 1.

In the example above, the loop will repeat 10 times. When the value of count reaches 10, the boolean expression will be evaluated to FALSE (because 10 is not less than 10) and the loop will stop.

To stop a WHILE loop before its boolean expression becomes FALSE, use EXIT. Put an IF statement containing EXIT anywhere between DO and END_WHILE.

IF [boolean expression] THEN
  EXIT;
END_IF;

REPEAT Loops

The last type of repeating loop in Structured Text is the REPEAT loop. It works the opposite way of the WHILE loop. This loop will stop repeating when a boolean expression is TRUE.

In ST, the syntax for REPEAT loops looks like this:

REPEAT
  <statement>;
UNTIL [boolean expression]
END_REPEAT;

Because the boolean expression comes after the statements, a REPEAT loop always executes them at least one time. Use it when an action must happen one time before a condition decides whether to run it again.

As with WHILE loops, change a value in the boolean expression during execution so the loop can stop. You can increment a variable to count repetitions, or use a conditional statement such as IF inside the loop.

Structured Text Programming Software

Reading this tutorial is a start to learning Structured Text. Put it into practice now by using the language yourself.

Write PLC programs to practise Structured Text and build your command of the language.

Beckhoff TwinCat 3

One of the best pieces of PLC programming software, when you want to learn Structured Text, is Beckhoff TwinCat 3. The programming software from Beckhoff is fully compatible with all the IEC 61131-3 PLC programming languages including Ladder Diagram (LD) and Structured Text (ST).

TwinCat 3 includes a simulator, which is its main advantage for learners. Instead of buying a PLC, use the soft PLC.

A free YouTube video series is available from SquishyBrained. Follow his channel for tutorials, including a video series about his DIY 3D Printer. His tutorials introduce Structured Text PLC programming in TwinCat 3.

Codesys

You may have heard of Codesys before. It is an open-source software environment for IEC 61131-3 PLC programming. Open source just means that it is free for download, which makes it perfect for students.

Beginner resources for Codesys are limited, but Brian Hobby has made tutorial videos that explain how to get started.

The first video walks through creating a Codesys project and includes some Ladder Logic.

Use the second video to begin Structured Text programming in Codesys.

Learning Through Practice

Learning a programming language takes effort. These basic habits can help when you are beginning:

  • Learning takes time
    You just started out. Give yourself some time to learn the language (syntax, functions, …)
  • Practice as much as possible
    Try to make as many PLC programs and solutions in Structured Text as possible.
  • Learn from your failures
    Every time you make a mistake, don’t get sad. Learn from it, and become a better programmer.
  • Keep learning
    Keep reading and watching tutorials, and continue using other learning materials.
  • Talk to other PLC programmers
    Last but not least is discussing in forums and asking questions. Get involved and learn from other PLC programmers.

For me, talking with other programmers matters most. Learning from their experience can be the most effective way to understand both the language and its practical use.

Join the discussion below: Ask your first question about Structured Text and connect with other PLC programmers.

What did you learn from this tutorial?

30 Comments
Leave a response