Structured Text

Structured Text (ST) is a high-level textual programming language defined by the IEC 61131-3 standard. It is supported by most PLC vendors, including Siemens (SCL), Beckhoff, CODESYS, Rockwell Automation, Omron and Schneider Electric. The integrated SoftPLC compiles Structured Text to highly optimized JavaScript, which is executed inside your web browser. The compiler supports IEC 61131-3 (Edition 4), with the exception of multi-threading.

Contents

Getting Started

A Structured Text project is made up of program organization units (POUs), which are programs, functions and function blocks. Each POU declares its variables, followed by the statements that operate on them. Every statement ends with a semicolon. The following program switches on a lamp three seconds after a start button is pressed:

PROGRAM Main
VAR
    StartButton AT %IX0.0 : BOOL;
    Lamp AT %QX0.0 : BOOL;
    Delay : TON;
END_VAR

Delay(IN := StartButton, PT := T#3s);
Lamp := Delay.Q;
END_PROGRAM

The StartButton and Lamp variables have explicit addresses, so they can be imported as tags and can be bound to signals in the model, such as the state of a push button and the state of an indicator light. The Delay variable is an instance of the standard TON on-delay timer.

Keywords and identifiers are not case-sensitive, so END_IF, End_If and end_if are equivalent. By convention, keywords are written in upper case.

The following pages describe the language in more detail:

Comments

Comments are ignored by the compiler. There are three styles of comment:

// A single-line comment.
(* A multi-line comment. *)
/* Another multi-line comment. */

Identifiers

Identifiers name variables, types and POUs. An identifier starts with a letter or an underscore, followed by letters, digits and underscores. An identifier cannot contain two consecutive underscores or end with an underscore, and it cannot be a keyword. Examples of valid identifiers include Motor1, conveyor_speed and _Count.

Literals

Any literal can be prefixed with a type name and a # sign, which gives the literal that type. Without a prefix, the type of a number or string is determined by where it is used, such as the type of the variable it is assigned to. A prefix is required when the type cannot be determined, for example when both operands of AND are literals. A typed literal that is outside of the range of its type is reported as an error.

Numbers

Integers can be written in decimal, hexadecimal, octal or binary. Underscores may be used to separate digits. Real numbers require a decimal point, and may have an exponent.

Count := 1_000_000;      // Decimal.
Mask := 16#FF;           // Hexadecimal.
Mode := 8#17;            // Octal.
Bits := 2#1010_0101;     // Binary.
Speed := 2.5;            // Real.
Large := 1.0E6;          // Real with an exponent.

A number is given a specific type by writing the type name and a # sign before it. The prefix comes before any base, so a hexadecimal byte is written BYTE#16#F0. Typing a number is necessary when nothing else determines its type, and it lets the compiler check that the value fits in that type.

Mask := BYTE#16#F0 AND BYTE#16#3C;     // Untyped literals would be ambiguous here.
Ratio := REAL#2;                       // A whole number written as a REAL.
Small := SINT#200;                     // Error: outside of the range of SINT (-128 to 127).

Booleans

Boolean literals are TRUE and FALSE. A boolean can also be written as 0 or 1.

Running := TRUE;
Fault := FALSE;
Active := 1;
Enabled := BOOL#1;

Durations

Durations have the TIME type and are written with the T# or TIME# prefix. The units are days (d), hours (h), minutes (m), seconds (s), milliseconds (ms), microseconds (us) and nanoseconds (ns). Long durations use the LT# or LTIME# prefix.

Delay := T#500ms;
Timeout := T#1m30s;
Period := T#1.5s;
Precise := LT#250us;

Dates and Times

Day := D#2024-01-31;                   // DATE, can also be written as DATE#.
Opening := TOD#12:30:00;               // TIME_OF_DAY, can also be written as TIME_OF_DAY#.
Stamp := DT#2024-01-31-12:30:00;       // DATE_AND_TIME, can also be written as DATE_AND_TIME#.

The long date and time types have nanosecond resolution:

LongDay := LD#2024-01-31;                      // LDATE, can also be written as LDATE#.
LongOpening := LTOD#12:30:00.000001;           // LTIME_OF_DAY, can also be written as LTIME_OF_DAY#.
LongStamp := LDT#2024-01-31-12:30:00;          // LDATE_AND_TIME, can also be written as LDATE_AND_TIME#.

Strings

Single-byte strings (STRING) use single quotes, and double-byte strings (WSTRING) use double quotes. The dollar sign introduces special characters:

Sequence Meaning
$' Single quote
$" Double quote
$$ Dollar sign
$L or $N Line feed
$R Carriage return
$T Tab
$P Form feed
$41 The character with the hexadecimal code 41 (the letter A)
Message := 'It$'s running';
Wide := "Line one$NLine two";

When a string is assigned to a variable, it takes the type of the variable, so a single character in quotes can be assigned to a CHAR. A string literal can also be prefixed with its type, which is useful when the literal is passed to a function that accepts several string types. A typed WSTRING can use single quotes, and Unicode strings (USTRING) have the short prefix U#.

Label := WSTRING#'Place';
Text := U#'Unicode';                   // Can also be written as USTRING#'Unicode'.
Initial := CHAR#'A';

Enumerations

An enumeration value can be qualified with the name of its enumeration type.

Lamp := Green;
Lamp := Color#Green;                   // Qualified with its type.

Operators

Operators are listed from the highest precedence to the lowest. Operators with the same precedence are evaluated from left to right.

Operator Description
( ) Parentheses
^ Dereference
-, +, NOT Negation, unary plus and complement
** Exponentiation
*, /, MOD Multiplication, division and modulo
+, - Addition and subtraction
<, >, <=, >= Comparison
=, <> Equality and inequality
AND, & Boolean or bitwise AND
XOR Boolean or bitwise exclusive OR
OR Boolean or bitwise OR

Integer division truncates towards zero, so -7 / 2 is -3. The result of MOD has the same sign as the dividend, so -7 MOD 3 is -1. Division by zero is a runtime error. Arithmetic on integers is checked, so a result that is outside of the range of its type is also a runtime error.

The logical operators AND, OR, XOR and NOT operate on BOOL values, and bitwise on the bit string types BYTE, WORD, DWORD and LWORD.

Running := Start AND NOT Stop;
InRange := Position >= 0.0 AND Position <= 100.0;
Low := Status AND BYTE#16#0F;

Assignment

The := operator assigns the value of an expression to a variable:

Total := Total + 1;
Speeds[2] := 1.5;
Station.Count := 0;

The value must have the same type as the variable, or a type that converts implicitly to it. A value converts implicitly when no information can be lost, such as an INT to a DINT, or a REAL to an LREAL. Other conversions require one of the conversion functions, such as LREAL_TO_INT.

Selection Statements

IF Statements

The IF statement executes statements when a condition is true. Any number of ELSIF branches may follow, along with an optional ELSE branch.

IF Level > 90.0 THEN
    Valve := FALSE;
ELSIF Level < 10.0 THEN
    Valve := TRUE;
ELSE
    Alarm := FALSE;
END_IF;

CASE Statements

The CASE statement selects statements based on the value of an integer or enumerated expression. Each case can have a list of values or ranges. The ELSE branch is executed when no case matches.

CASE Step OF
    0:
        Motor := FALSE;
    1, 2:
        Motor := TRUE;
    3..9:
        Motor := Sensor;
ELSE
    Step := 0;
END_CASE;

A CASE statement is commonly used to implement a state machine, where an integer or enumerated variable holds the current step of a sequence.

Iteration Statements

FOR Loops

The FOR statement repeats statements while a control variable counts from a start value to an end value. The end value is inclusive, so FOR I := 1 TO 10 runs ten times, with I from 1 to 10. The optional BY clause sets the increment, which defaults to 1 and may be negative.

FOR I := 1 TO 10 DO          // I is 1, 2, ..., 10.
    Sum := Sum + Values[I];
END_FOR;

FOR I := 10 TO 0 BY -2 DO    // I is 10, 8, 6, 4, 2, 0.
    Values[I] := 0;
END_FOR;

FOR I := 0 TO 9 BY 4 DO      // I is 0, 4, 8.
    Values[I] := 1;
END_FOR;

The statements are only executed while the control variable is within the range. When the increment does not land exactly on the end value, the last iteration uses the last value within the range, such as 8 in the third example. If the start value is already past the end value, the statements are not executed at all.

The control variable, and any variable used as the start, end or increment, cannot be modified inside the loop. After the loop, the control variable holds the value that ended the loop, which is one increment past the last iteration (12 in the third example), or the start value if the statements were not executed.

WHILE Loops

The WHILE statement repeats statements while a condition is true. The condition is checked before each iteration.

WHILE Index < 10 AND Values[Index] <> 0 DO
    Index := Index + 1;
END_WHILE;

REPEAT Loops

The REPEAT statement repeats statements until a condition is true. The condition is checked after each iteration, so the statements are executed at least once.

REPEAT
    Index := Index + 1;
UNTIL Values[Index] = 0
END_REPEAT;

EXIT and CONTINUE

EXIT ends the innermost loop, and CONTINUE skips to the next iteration of the innermost loop.

FOR I := 1 TO 10 DO
    IF Values[I] < 0 THEN
        EXIT;
    END_IF;
    IF Values[I] = 0 THEN
        CONTINUE;
    END_IF;
    Count := Count + 1;
END_FOR;

A PLC program must finish each scan quickly, so loops should never wait for a signal to change. Use a state machine that checks the signal once per scan instead.

RETURN

The RETURN statement ends the execution of the current POU or method. In a function, the result is the value last assigned to it before RETURN. In a program, RETURN skips the rest of the current scan, and the program starts from the top again in the next scan.

FUNCTION FindFirst : INT
VAR_IN_OUT
    Values : ARRAY[*] OF INT;
END_VAR
VAR_INPUT
    Target : INT;
END_VAR
VAR
    I : DINT;
END_VAR

FindFirst := -1; // The result when the target is not found.
FOR I := LOWER_BOUND(Values, 1) TO UPPER_BOUND(Values, 1) DO
    IF Values[I] = Target THEN
        FindFirst := DINT_TO_INT(I);
        RETURN; // Stops searching once the target is found.
    END_IF;
END_FOR;
END_FUNCTION
PROGRAM Main
VAR
    Enabled AT %IX0.0 : BOOL;
END_VAR

IF NOT Enabled THEN
    RETURN; // Skips the rest of the scan while the machine is disabled.
END_IF;

// The machine logic follows here.

END_PROGRAM

Calls

Functions are called with named arguments, using := for inputs and => for outputs, or with positional arguments in the order they are declared.

Result := LIMIT(MN := 0, IN := Value, MX := 100);
Result := LIMIT(0, Value, 100);

Function blocks are called through an instance. Inputs that are not assigned keep the value from the previous call. The outputs are read from the instance after the call.

Timer(IN := Start, PT := T#2s);
IF Timer.Q THEN
    Lamp := TRUE;
END_IF;

EN and ENO

EN (enable) and ENO (enable out) control whether a call is executed. EN is a boolean input that defaults to TRUE, and ENO is a boolean output that reports whether the call was executed. They are mainly used in graphical languages, where they allow a chain of blocks to be enabled by a single signal, but they can also be used in Structured Text.

When EN is FALSE, the call is not executed and ENO is FALSE. A function then returns the default value of its result type, which is 0 for numbers. The outputs of a function block keep their values from the previous call. When EN is TRUE, the call is executed as normal and ENO is TRUE, unless the call causes a runtime error.

VAR
    Value : REAL := 9.0;
    Root : REAL;
    Executed : BOOL;
END_VAR

Root := SQRT(EN := TRUE, IN := Value, ENO => Executed);     // Root is 3.0, and Executed is TRUE.
Root := SQRT(EN := FALSE, IN := Value, ENO => Executed);    // Root is 0.0, and Executed is FALSE.

Since a disabled function returns 0 rather than leaving the variable unchanged, avoid assigning the result of a function that may be disabled. Use an IF statement instead, which leaves the variable unchanged:

IF Valid THEN
    Root := SQRT(Value);
END_IF;

The standard functions and function blocks always have EN and ENO. A user-defined function or function block only has them if it declares them. When it declares EN, the body is skipped while EN is FALSE. When it declares ENO, the body can set ENO to FALSE to report that it could not complete its work:

FUNCTION SafeDivide : REAL
VAR_INPUT
    EN : BOOL := TRUE;
    Dividend : REAL;
    Divisor : REAL;
END_VAR
VAR_OUTPUT
    ENO : BOOL;
END_VAR

IF Divisor = 0.0 THEN
    ENO := FALSE; // Reports the failure instead of dividing by zero.
    SafeDivide := 0.0;
ELSE
    SafeDivide := Dividend / Divisor;
END_IF;
END_FUNCTION

Speed := SafeDivide(Dividend := Distance, Divisor := Duration, ENO => Valid);

ENO is also FALSE when the call causes a runtime error, such as a negative value for SQRT or a division by zero inside the body of a function block. Connecting ENO does not suppress the error, which is still reported. Please see the program organization units page for more details on declaring and calling functions and function blocks.

Libraries

Structured Text can be shared between models as a library, by publishing it in a package. The Structured Text files of an installed package are compiled together with the Structured Text files of the model, so the functions, function blocks and data types that a package declares can be used in any file of the model.

A library should only declare functions, function blocks, classes and data types. Without a configuration, every program in the project is executed once per scan, so a program declared in a package would run in every model that installs it. Since the files of a package share one project with the files of the model, declaring the library in a namespace avoids clashes between their names. For example, a package could provide the following file:

NAMESPACE Acme.Valves
    // Opens a valve on command, and reports a fault if its feedback does not follow within the time limit.
    FUNCTION_BLOCK Valve
    VAR_INPUT
        Open : BOOL;
        Feedback : BOOL;
        TimeLimit : TIME := T#2s;
    END_VAR
    VAR_OUTPUT
        Output : BOOL;
        Fault : BOOL;
    END_VAR
    VAR
        Timer : TON;
    END_VAR

    Output := Open;
    Timer(IN := Open <> Feedback, PT := TimeLimit);
    Fault := Timer.Q;
    END_FUNCTION_BLOCK
END_NAMESPACE

A program in a model that installs the package can then use the function block:

USING Acme.Valves;

PROGRAM Main
VAR
    Inlet : Valve;
    OpenInlet AT %IX0.0 : BOOL;
    InletOpen AT %IX0.1 : BOOL;
    InletOutput AT %QX0.0 : BOOL;
END_VAR

Inlet(Open := OpenInlet, Feedback := InletOpen);
InletOutput := Inlet.Output;
END_PROGRAM

A package of Structured Text still needs the package.json and index.ts files that every package requires. When the package contains no TypeScript, the index.ts file only needs to contain export {};.