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
  • Brian Hobby
    July 22, 2015 at 10:00 pm

    Good overview, will probably point some of the Engineering Institute of Technology students this way as it’s great intro topic.

  • September 3, 2015 at 8:35 am

    Finally I have found one of the best and nicely written tutorial on structured text. Great Work !!!

  • Ritesh
    October 19, 2015 at 5:20 am

    Great tutorial for beginners…. Thanks

  • Geoff Frost
    November 30, 2015 at 12:59 pm

    Example program?????

  • Erfan
    January 16, 2016 at 11:23 am

    Hi
    First thank you for your great tutorial
    I want to ask you if its possible email me this tutorial( stl language) in pdf
    Thank you so much

    • peter
      January 17, 2016 at 3:07 pm

      Hi Erfan,

      Thanks you very much for your comment! I’m glad that you like my tutorial. I have added a link to the pdf version in the top of the article.

      Best Regards
      Peter

  • January 17, 2016 at 1:02 pm

    This is a really good introduction to Structured Text Language. Just a note to remember that every PLC vendor is allowed to have a slightly different “flavor” of syntax – the IEC-61131-3 spec only nails down data types, and then says what the capabilities of the language must be, not the syntax.

    However, I take exception to this: “The truth is, that even though ladder diagram (LD) is an easy programming language for beginners, it can be very hard to read and understand.”

    The truth is that every programming language is difficult for beginners to understand because code is a lot harder to read than it is to write. This is no different than English – my 5 year old can write sentences, but still needs a lot of help reading most words, and even then will find it hard to get the meaning of a paragraph after getting bogged down in comprehending the individual words.

    I have written programs in BASIC, C/C++, Assembly, VB6, VB.Net, C#, Ladder and Structured Text. Of these I’m proficient in VB6, C#, and Ladder because I use them almost daily. I assure you that I can comprehend someone else’s Ladder Logic faster than I can read a Structured Text program, and that’s simply due to experience and practice.

    Even so, there are two reasons why Ladder Logic dominates in control system programming (at least in North America). First, as you’ve alluded to, electricians and technicians already “get it” so they immediately get a bump up the experience ladder, and that’s a great thing! I don’t know about you, but at 2 am, I’d rather the night shift electrician be able to deal with the problem right then and there without waking up someone in engineering. 🙂 Secondly, traditional imperative programming, like Structured Text (i.e. do this, then do that, then that) is a less useful mental model to have about a machine. Many things in a machine are happening in parallel. Since Ladder Logic is mimicking electrical relays, which also intuitively operate in parallel, this is a more apt mental model of what’s going on.

    If I’m programming an Arduino in C++, my knowledge of Ladder Logic helps me to write better C++ automation code. I’ve said before that Structured Text is an imperative language and Ladder Logic is a functional programming language, and there’s a reason functional programming is all the rage these days. Functional programming is easier to reason about. At its core, a PLC operates by computing the outputs and next scan’s internal state based on the inputs and last scan’s internal state. If you follow a few basic rules like making sure that each output and internal coil is only assigned once per scan, then you’re doing functional programming.

    Basically, when someone says, “It can be almost impossible to find head and tail in a larger PLC program written in ladder logic,” my years of experience has taught me that person just doesn’t have experience with ladder logic programming, and were frustrated the first time they saw it. I can’t make heads nor tails of Japanese texts either, but if I claimed this meant English is superior to Japanese, clearly that would be a fallacy, and my error would be all the more apparent to a Japanese person.

    That said, you have a very impressive site here full of useful information. Thanks so much for taking the time to add to the resources available online for beginners. I’m glad the new generation won’t have to spend so much time coming up to speed as we did!

    • Bernard Bannon
      March 31, 2020 at 9:39 pm

      Very Well Said

      I would like to also point out that it is a fallacy to say Ladder vs Structured Text. It depends on the task. If I need to handle some arrays with some kind of iterative loop then I’ll use Structured Text. If I need to look at 10 switches and do some kind of simple output logic then relay logic. One thing about relay logic is that you can look at it and see all on/off states which makes trouble-shooting very fast.

  • Stephen Gray
    April 29, 2016 at 5:16 pm

    Thank you for the tutorial / overview! I’ve been using structured text for a while now, and actually prefer it to ladder logic (which I have used much longer). I agree that, at first glance, ladder might appear to be a more understandable language. Where it is lacking is in program control and, (no pun intended), structure, which is critical to having code that is easily maintained. While clear and structured ladder can be written, it is more often than not poorly implemented, or often ends up so after feature creep. Simply put, I believe it takes more discipline to write good ladder than it does to write good structured text.
    I also find ST to be much more readable. When I read ladder, what I am thinking is often close to the language that is native in structured text… “if THIS, then THAT”. Having it in word form removes a step and allows me to focus more clearly on solving the problem, rather than on the language and tools. Also, being text based, much more code is visible at a given time on the screen, so no constant scrolling.

  • Jake
    May 7, 2016 at 8:08 pm

    Minor error, I believe. Your BITWISE operator statement initial example seems to say that ANDing 15 and 8 equals 15. I’m pretty sure that’s supposed to equal 8. Your explanation even seems to indicate it should be 8, but the first part says the result is 15.

    Otherwise, this is a great tutorial. I’ve used ST off and on for years at work, but always wished I had a better introduction. This is perfect.

  • Tayyab
    June 20, 2016 at 6:24 am

    Pretty nice for beginners. I found this tutorial to be very helpful.

    I found a litte mistake under the Bitwise Operator Heading.

    The table should be like this:

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

  • Revin
    June 25, 2016 at 3:02 am

    Hi.. The Tutorial is good.. Thank You..
    Also can i u send me a program in structured text in the right syntax.. I just need to compare with other programming techniques and it will help my students a lot…

    Load Binary values A and B..
    Logical Operation to be performed – A “AND” B
    Result should be stored in C.

    My mail Id is [email protected]
    Thanks in Advance..
    Revin.

  • Bard
    October 13, 2016 at 7:29 am

    Hi, you mention that it’s possible to have function blocks containing functions written in Structured Text. Do you have an example of this?

  • Paul
    January 29, 2017 at 2:37 pm

    is there a program out there that can directly convert LD to ST?

  • August 23, 2017 at 6:09 am

    Thank you for sharing. I found college information which provides [b]Computer Programming & Information Technology[/b] [url=asa.edu]http://www.asa.edu/computer-programming-info-tech.asp[/url]
    Computer Programming & Information Technology
    This program is designed for people who plan to pursue

  • Am.It
    August 26, 2017 at 7:23 am

    I’ve downloaded Twincat3 and installed it with Visual studio 2013. But when I tried to get the 7 days trial license it detected all zeros in the system id, like ‘000000000000000’. and even the buttons in the access toolbar are not working, it’s disabled. I’m just an initiate, Please help me out guys?

  • mustermann
    September 13, 2017 at 7:19 am

    15 AND 8 is NOT 15

  • DaleR
    May 18, 2018 at 9:14 pm

    A lot to take in. It all…almost makes sense. So many unanswered questions compared to the great arduino teaching video. Girl video was disturbing. Bit operators and truth table makes no sense. I’ll watch it a few more times to see if it will sink in.

  • Kübra Özdöşemeci
    June 3, 2018 at 5:34 pm

    Thanx for all but pls can you share more examples in St?

  • Tom Mejer Antonsen
    June 13, 2018 at 8:11 pm

    Perhaps this book can help “PLC Controls with Structured Text (ST), ISBN: 978-87-4300-241-3 , ISBN: 978-87-4300-242-0

  • pallavi
    June 30, 2018 at 7:18 am

    hi will u please suggest how to design rung and all this symbol in canvas

  • @kN
    October 4, 2018 at 11:17 am

    Hello Everyone,

    Thanks for your sharing. Let me ask you a quastion. I want to use a time delay in a “for” loop instead of using a timer block. How can i do it or which keyword is suitable to delay without requiring any statement?

  • Mohammed Nizamuddin
    February 26, 2019 at 6:33 am

    Very nice tutorial I Learn so many things, heartly Thanks for sharing your Knowledge.

  • March 4, 2019 at 4:19 pm

    Very good and detailed article. My Admirations!

  • Matt
    October 25, 2019 at 7:24 pm

    Have you ever worked in a plant? I can tell you that when the process is down, you will never hear anyone praising the CS degree programmer who used all structured text, and nested add on instructions for everything. Noone is happy that this person got creative and wrote efficient code… No they want their own people (not systems integration staff) to be able to figure it out, and fast. Ladder logic can be very organized and not hard to follow if written with care. ST is okay for very repetitive tasks. You’re against commenting your code because some guru said experts don’t have the patience to do it? The only reason to not commenting your code is job security or laziness.

  • Alex
    February 4, 2020 at 2:49 am

    Great article. Just in logical operands example (8 AND 15) = 8, not 15

  • Olaniyi Damilare
    February 20, 2020 at 6:00 pm

    Thanks for the amazing tutorial. I will request more plc structure text tutorials well explained like this one…

  • Melisa
    June 6, 2020 at 9:48 am

    I am a new beginner in this topic and this tutorial was at the exact level I wanted to get started! Thanks a lot for this clear, understandable, comparable and just the right amount of detailed information! I took many tiny notes for my later studies. I will recommend this website to my friends.

Leave a Response