Tiza Group

Home / Guides / Industry and automation

Structured Text (ST) for PLCs: Fundamentals

Fundamentals of Structured Text (IEC 61131-3): variables, IF, CASE, loops, functions, and function blocks, with a motor example.

By Shadai García, CEO and protection engineer at Tiza Group.

ST · a single statementkm1 := (start OR km1) AND stop_ok AND thermal_ok;LD · the same resultstartkm1stop_okthermal_okkm1OR = parallel contacts, AND = series contactsCASE state OF · state machine012startKM1 okstop or faultstate 0: idle, outputs offstate 1: starting, awaiting confirmationstate 2: running, km1 = 1returns to state 0each scan runs only the active state's branchChainInputsST statementState (CASE)Output© tizagrp.comST · a single statementkm1 := (start OR km1) AND stop_ok AND thermal_ok;LD · the same resultstartkm1stop_okthermal_okkm1OR = parallel contacts, AND = series contactsCASE state OF · state machine012startKM1 okstop or faultstate 0: idle, outputs offstate 1: starting, awaiting confirmationstate 2: running, km1 = 1returns to state 0each scan runs only the active state's branchChainInputsST statementState (CASE)Output© tizagrp.com
Structured Text: one statement, its ladder equivalent, and the state machine with CASE. Location in the system and operating principle. Illustrative: real values come from the nameplate and the manufacturer's manual.
Short answer

Structured text (ST) is the high-level textual language of IEC 61131-3, similar to Pascal. It consists of variable declarations, assignments, IF and CASE conditionals, FOR, WHILE, and REPEAT loops, and calls to functions and function blocks. It is the best fit for calculations, data, and complex logic.

Short answer

Structured Text (ST) is the high-level textual language defined in IEC 61131-3. Its syntax resembles Pascal: you declare variables, assign values, and control flow with IF, CASE, and loops. Each manufacturer offers it with slight differences in syntax and name (some call it SCL or another proprietary name). It is the language for what becomes unmanageable in ladder: formulas, arrays, scaling, recipes, and state machines.

Structure of a program

An ST program has two areas: the variable declaration and the body.

PROGRAM Motor1
VAR
  start      : BOOL;
  stop_ok    : BOOL;
  thermal_ok : BOOL;
  km1        : BOOL;
END_VAR

km1 := (start OR km1) AND stop_ok AND thermal_ok;
END_PROGRAM

The statement is equivalent to the start-stop seal-in drawn in ladder: the output holds itself on and is cut by the stop or by the protection. Each instruction ends in a semicolon. Comments are written between (* and *).

Data types and operators

ElementExamplesNote
BooleanBOOLTrue or false
IntegersINT, DINT, UINTDifferent ranges and bit widths
RealsREAL, LREALFloating point; not compared with exact equality
TimeTIME, T#5sTime constants
StringsSTRINGText
CompoundARRAY, STRUCTTables and records
LogicalAND, OR, XOR, NOT
Comparison=, <>, <, >
Arithmetic+ - * /, MOD
Assignment:=Not to be confused with =

Types matter: a division between integers returns an integer, and mixing types without explicit conversion causes compile errors in some environments or truncation in others. See addressing and data types.

Flow control

IF conditional:

IF level < level_low THEN
  pump := TRUE;
ELSIF level > level_high THEN
  pump := FALSE;
END_IF;

This fragment implements hysteresis: between the two levels, the pump keeps its state.

CASE multiple selection: suited to state machines, where an integer variable indicates the current stage.

CASE stage OF
  0: (* idle *)
     IF start THEN stage := 10; END_IF;
  10: (* starting *)
     km1 := TRUE;
     IF t_start.Q THEN stage := 20; END_IF;
  20: (* running *)
     IF stop_btn THEN stage := 0; END_IF;
END_CASE;

A state machine in CASE is the textual equivalent of an SFC or GRAFCET: each value is a step and each IF is a transition.

Loops: FOR (known number of repetitions), WHILE (as long as a condition holds), and REPEAT … UNTIL. They are used to walk through tables, add up values, or find an element. Remember that the loop runs to completion in a single scan.

Functions and function blocks

A function returns a result from its inputs and keeps no state. A function block does keep state and is instantiated. Timers and counters are function blocks, and in ST they are called like this:

t_start(IN := km1, PT := T#5s);
IF t_start.Q THEN ... END_IF;

The block is invoked with its inputs and the output is read through the instance name (see timers and counters in PLCs). The user’s own blocks are declared with FUNCTION_BLOCK, and each motor, valve, or pump in the plant uses an instance of the same block.

Illustrative example: scaling an analog measurement

Assumed data: a current transmitter on the 15 kW, 400 V motor delivers 4-20 mA proportional to 0-40 A. The analog module converts that signal to an integer between 0 and 27648 (assumed range; each module declares its own).

Linear scaling formula: current = (counts − 0) / (27648 − 0) × (40 − 0) + 0, that is, current = counts × 40 / 27648.

Module countsCalculated current
00 A
1935428 A (motor rated current)
2764840 A

In ST it is written as a single assignment line on a REAL. In ladder, the same operation requires chained calculation blocks. This is a case where text wins on clarity. One design note: the scaling must include detection of an out-of-range signal (below 4 mA indicates a broken wire on a 4-20 mA signal).

Advantages and limits

Advantages: compact, easy to compare with version control, convenient for data and algorithms. Limits: whoever maintains the plant may not be able to read it; online debugging is less visual; and overuse of nested loops makes execution time hard to predict. Many projects combine ST for calculations and ladder for interlocks, with SFC for sequences.

Style and readability in structured text

Text gives freedom, and with it the chance to write unreadable code. Some style rules in common use among automation teams:

  • One statement per line and uniform indentation inside IF, CASE, and loops.
  • Complex conditions split into named intermediate variables, instead of fifteen-term expressions.
  • Declared constants (LEVEL_HIGH_LIMIT) instead of scattered numbers.
  • Short functions, with a single responsibility.
  • Comments at the start of each block with its purpose, inputs, and outputs.
  • Avoid hidden side effects: a function should not write global variables.

State machine as a pattern

The combination of a stage variable and a CASE is the most useful pattern in the language. Each stage defines which outputs are active and which condition leads to the next one. A fault stage reachable from any other, and an explicit reset, are recommended. With that pattern, online diagnosis consists of reading the stage variable: it tells you where the process is.

When not to use text

Text loses to ladder in two cases. One: whoever maintains the plant is electrical staff without programming training. The other: the logic is a short chain of permissives that is better understood drawn. Nor is it suited to what must be viewable “live” contact by contact. Most solid projects split the work: text for calculations and states, ladder for interlocks and visual diagnosis.

Debugging and testing

Online, the environment lets you see the value of each variable next to the line of code, set breakpoints on some controllers, and force test values. To test a block written in text, build a table of cases with inputs and expected outputs. Include the limits (zero, maximum, out-of-range value) and the fault combinations. A scaling calculation, for example, is tested with the minimum, the maximum, an intermediate value, and a signal below 4 mA. When the result does not match what is expected, break the expression into intermediate variables to find the step that fails. Those same case tables form the block’s test evidence and are reused each time it is modified.

Common mistakes

  • Using = instead of :=.
  • Comparing reals with exact equality; compare with a tolerance.
  • WHILE loops without a guaranteed exit, which trip the watchdog.
  • Mixing types without conversion, with loss of precision or overflow.
  • Dividing without checking the divisor.
  • Writing the same variable in several programs.
  • Leaving CASE without a branch for an unexpected value: a corrupted stage variable leaves the machine with no valid state.
  • Not commenting: uncommented text ages badly.
  • Using jumps and constructs that make the flow hard to follow.

Checklist

  • Variables declared with a type and a meaningful name.
  • Named constants, not loose numbers.
  • Loops with a known, bounded limit.
  • Divisions and scalings protected against invalid values.
  • CASE with a default branch and a safe state.
  • Each output is written in only one place.
  • Function blocks reused per piece of equipment.
  • Comments that explain the purpose, not the syntax.

Frequently asked technical questions

  • Can ST be called from ladder? Yes; many environments allow blocks written in ST to be used inside rungs.
  • What is SCL? The name a manufacturer gives to its variant of structured text.
  • Are there tools to practice? There are open-source environments that run ST on a computer; see PLC simulation and tools.
  • Is it valid for safety systems? It depends on the controller and on the certification of the environment; a safety program follows the rules of the certified manufacturer.

How we help

A maintainable control program starts from a good architecture: blocks per piece of equipment, defined states, and verified scalings. At Tiza Group we design the control logic, then test and commission the system. See engineering design and studies and testing and commissioning, or write to us through contact.

References

  • IEC 61131-3, structured text (paid standard).
  • PLCopen, introductory material on ST.
  • OpenPLC, editor and runtime with ST support.

Frequently asked questions

Is Structured Text harder than ladder?

It requires a different way of thinking, closer to general programming, but it is shorter and more readable for calculations, tables, and algorithms. For someone who already programs in another language, the learning curve is short.

Can a loop lock up the PLC?

Yes. A loop runs to completion within one scan cycle. If it does not terminate, or walks through too many elements, the cycle stretches until the watchdog timer stops the controller.

What is the difference between := and = in ST?

:= assigns a value to a variable; = compares two values and returns true or false. Mixing them up is a common mistake for people coming from other languages.

Does ST run faster than ladder?

Not because it is text. Both are compiled and performance depends on the compiler and the hardware. What changes is clarity, depending on the type of problem.

WhatsApp