mathematical-modeling-in-engineering
How to Use Structured Text for Complex Mathematical Calculations in Plcs
Table of Contents
Structured Text (ST) is a high-level programming language defined in the IEC 61131-3 standard for programmable logic controllers (PLCs). Unlike graphical languages such as Ladder Diagram or Function Block Diagram, ST uses syntax similar to Pascal or C, making it especially powerful for implementing complex mathematical algorithms, data analysis routines, and computation-heavy control logic. This article explains how to leverage Structured Text for sophisticated mathematical calculations in industrial automation, covering environment setup, language constructs, practical examples, and best practices for reliable production code.
What Is Structured Text?
Structured Text is one of the five programming languages specified in the IEC 61131-3 standard, which harmonizes PLC programming across manufacturers. ST is a text-based language that allows clear expression of conditional logic, iterative loops, and mathematical operations. It is particularly well suited for tasks that involve:
- Real-time numeric simulations and modeling
- PID controller tuning and adaptive control
- Signal processing (filters, FFT, interpolation)
- Motion profile generation and path planning
- Data conversion and scaling between engineering units
Advantages Over Ladder Logic
Ladder Logic (LD) is intuitive for discrete binary logic but becomes cumbersome for arithmetic-heavy algorithms. ST offers several benefits:
- Concise syntax – a single line of ST can replace multiple rungs of LD.
- Native support for arrays and structures – ideal for matrix operations or handling large data sets.
- Built-in mathematical functions – SQRT, SIN, COS, ABS, LOG, EXP, and many others are available.
- Easier debugging – text-based breakpoints and watch windows allow step-by-step examination of variable values.
- Reusability – write functions and function blocks that can be instantiated and called repeatedly.
Limitations
ST is not a replacement for LD in every scenario. It may be less intuitive for electricians or technicians accustomed to relay logic, and some PLC platforms impose execution time limits on ST routines (e.g., maximum scan cycle). However, for mathematical workloads, ST is the clear choice.
Setting Up Your Programming Environment
To begin working with Structured Text, you need an IEC 61131-3 compliant development environment and a PLC that supports the ST language. Below are the most common ecosystems.
Siemens TIA Portal (SIMATIC S7-1200, S7-1500)
TIA Portal provides full support for ST (called "SCL" – Structured Control Language) within the S7-1200 and S7-1500 families. You create an SCL block, which is functionally equivalent to ST. The environment includes a code editor with syntax highlighting, a library of standard math functions, and integrated simulation (PLCSIM). To start:
- Create a new block and select the language "SCL".
- Define the interface (input, output, in/out, static variables) in the block's declaration section.
- Write your algorithm in the code section using SCL syntax.
- Download and test on the PLC or in simulation.
Siemens offers official SCL programming guides for advanced topics.
Rockwell Studio 5000 (ControlLogix, CompactLogix)
Rockwell Automation supports a variant of Structured Text (Add-On Instructions and Structured Text routines) in Studio 5000. The syntax follows IEC 61131-3 with minor deviations. You can create a "Structured Text" routine within a task; the editor provides auto‑complete, parameter help, and online monitoring. Rockwell supplies a standard math library, and you can also create custom Add-On Instructions (AOIs) in ST to encapsulate reusable calculation blocks.
CODESYS (Cross‑Platform)
CODESYS is a widely used IEC 61131-3 development system that runs on many PLC brands (Wago, Beckhoff, IFM, etc.). It fully supports ST for any controller that uses the CODESYS runtime. The environment includes a rich set of math libraries, real‑time trace, and integrated visualisation. CODESYS also supports object‑oriented extensions (methods, interfaces) that can be leveraged for complex mathematical modeling. Refer to the CODESYS documentation for the complete language specification.
Core Elements of Structured Text for Mathematics
Mastering ST for calculations starts with understanding its data types, operators, and built‑in functions.
Variables and Data Types
Common numeric data types in ST include:
- BOOL – boolean (0/1).
- INT, DINT, SINT – signed integers.
- WORD, DWORD – unsigned bit strings (often used for bitwise operations).
- REAL – 32‑bit floating‑point (IEEE 754).
- LREAL – 64‑bit double‑precision floating‑point (available on higher‑end PLCs).
- ARRAY – fixed‑size collection of elements (e.g., ARRAY[0..99] OF REAL).
- STRUCT – user‑defined grouping of variables.
Arithmetic, Relational, and Logical Operators
ST operators are similar to high‑level languages. The following table shows the most important ones:
- Add (
+), subtract (-), multiply (*), divide (/). - Modulo (
MOD) – returns remainder of integer division. - Exponentiation – some IEC environments use
**; in others you call theEXPTfunction. - Relational:
=,<>,<,>,<=,>=. - Logical:
AND,OR,XOR,NOT. - Assignment:
:=(e.g.,result := a + b;).
Built‑in Mathematical Functions
IEC 61131-3 defines a standard set of functions available in ST. The exact names may vary slightly by vendor, but the following are almost universally supported:
- SQRT(x) – square root of x (x must be non‑negative).
- ABS(x) – absolute value.
- SIN(x), COS(x), TAN(x) – trigonometric functions (x in radians).
- ASIN(x), ACOS(x), ATAN(x) – inverse trigonometric functions.
- LN(x) – natural logarithm (x > 0).
- LOG(x) – base‑10 logarithm (x > 0).
- EXP(x) – exponential e^x.
- EXPT(base, exponent) – exponentiation for real numbers.
- TRUNC(x) – truncate to integer.
- REAL_TO_INT(x) – explicit type conversion (may be a built‑in in some environments).
Additionally, many PLC vendors supply extended libraries (e.g., Siemens LIdentity, LScan for string math or matrix operations).
Writing Complex Calculations in Structured Text
Let’s examine practical examples that demonstrate how to combine variables, conditional logic, and math functions to solve common industrial problems.
Example 1: Quadratic Equation Solver with Edge Cases
Building on the basic example from the original article, we add handling for a = 0 (linear case) and negative discriminant (complex roots not supported in REAL – we output zero and set a status flag).
FUNCTION_BLOCK QuadraticSolver
VAR_INPUT
a : REAL;
b : REAL;
c : REAL;
END_VAR
VAR_OUTPUT
root1 : REAL;
root2 : REAL;
valid : BOOL;
END_VAR
VAR
disc : REAL;
END_VAR
IF a = 0.0 THEN
// Linear case: b*x + c = 0
IF b <> 0.0 THEN
root1 := -c / b;
root2 := root1;
valid := TRUE;
ELSE
root1 := 0.0;
root2 := 0.0;
valid := FALSE; // No solution or infinite solutions
END_IF;
ELSE
disc := b * b - 4.0 * a * c;
IF disc >= 0.0 THEN
root1 := (-b + SQRT(disc)) / (2.0 * a);
root2 := (-b - SQRT(disc)) / (2.0 * a);
valid := TRUE;
ELSE
root1 := 0.0;
root2 := 0.0;
valid := FALSE;
END_IF;
END_IF;
END_FUNCTION_BLOCK
This block can be instantiated in a cyclic task and called each scan. The valid flag allows the calling logic to ignore invalid results.
Example 2: Trigonometric Calculation for Machine Kinematics
Suppose you need to calculate the end‑effector position of a two‑link robotic arm given joint angles θ1 and θ2 (in radians) and link lengths L1 and L2.
FUNCTION PositionFromAngles : ARRAY[0..1] OF REAL
VAR_INPUT
theta1 : REAL;
theta2 : REAL;
L1 : REAL;
L2 : REAL;
END_VAR
VAR
x, y : REAL;
END_VAR
x := L1 * COS(theta1) + L2 * COS(theta1 + theta2);
y := L1 * SIN(theta1) + L2 * SIN(theta1 + theta2);
PositionFromAngles[0] := x;
PositionFromAngles[1] := y;
END_FUNCTION
This function returns an array of two reals. You may also want to add clamping or singularity detection (e.g., when arm is fully stretched).
Example 3: Custom PID Function Block with Anti‑Windup
PID controllers are a classic application for ST. A complete implementation includes proportional, integral, and derivative terms, plus clamping of the integral sum to prevent windup.
FUNCTION_BLOCK PID_Controller
VAR_INPUT
setpoint : REAL;
feedback : REAL;
Kp : REAL;
Ki : REAL;
Kd : REAL;
Ts : REAL; // sample time in seconds
upper_limit : REAL;
lower_limit : REAL;
END_VAR
VAR_OUTPUT
output : REAL;
END_VAR
VAR
error : REAL;
integral : REAL;
derivative : REAL;
previous_error : REAL;
END_VAR
error := setpoint - feedback;
// Integral term with anti‑windup
integral := integral + Ki * error * Ts;
IF integral > upper_limit THEN
integral := upper_limit;
ELSIF integral < lower_limit THEN
integral := lower_limit;
END_IF;
// Derivative term (using high‑pass filter for noise reduction is optional)
derivative := Kd * (error - previous_error) / Ts;
// Compute output
output := Kp * error + integral + derivative;
// Clamp output
IF output > upper_limit THEN
output := upper_limit;
ELSIF output < lower_limit THEN
output := lower_limit;
END_IF;
// Store for next cycle
previous_error := error;
END_FUNCTION_BLOCK
This block computes the PID output each scan. The integral term uses clamping to prevent windup when the actuator saturates. You can extend it with a deadband, feed‑forward, or derivative filter.
Error Handling and Edge Cases
Real‑world PLCs operate in safety‑critical environments. ST code must account for:
- Division by zero – always check the denominator before dividing.
- Square root of a negative number – use
ABS()on the argument or test it first. - Logarithm of non‑positive numbers – enforce domain checking.
- Overflow and underflow – REAL and LREAL can overflow; use limits if necessary.
- NaN (Not a Number) – some operations (e.g., 0/0) produce NaN, which can propagate silently. Use the
NaNtest function (if available) to detect it. - Timeouts – if a calculation takes longer than the scan time, it may trigger a watchdog. For heavy computations (e.g., iterative solvers), split the work across multiple scans or move to a lower‑priority task.
Best Practices for Production Code
The following guidelines help ensure that your ST math routines are reliable, maintainable, and efficient.
- Use descriptive variable names – e.g.,
current_temperatureinstead oftemp1. - Comment every nontrivial calculation – explain the formula and any assumptions.
- Parameterise constants – use named constants or input parameters instead of magic numbers.
- Test with known values – simulate using a test harness (e.g., in a separate ST function) to validate results before deploying.
- Limit side effects – avoid modifying global variables inside a math function; pass all required data through the interface.
- Use local scope – declare temporary variables inside the function or block to avoid cluttering the global namespace.
- Modularize – break large calculations into smaller functions or function blocks. Each unit should have a single responsibility.
- Version control – store ST source code in a version control system (Git) along with test vectors.
- Perform static analysis – many IDE tools can detect unused variables, unreachable code, or type mismatches.
Example: Calling a ST Function from Ladder
Often, the main program is written in Ladder or FBD, and ST is used only for calculation blocks. In TIA Portal, you can call an SCL function from a Ladder network using a CAL instruction or by placing the function block as a coil. In Studio 5000, you call a Structured Text routine from a JSR (Jump to Subroutine) instruction. This hybrid approach leverages each language’s strengths.
Performance Considerations
While ST is efficient, heavy math routines can consume significant scan time. Keep these points in mind:
- Use REAL instead of LREAL unless double precision is strictly required (LREAL operations are slower and use more memory).
- Avoid function calls inside loops if the function is simple; inline the expression.
- Precompute constants – e.g.,
pi := 3.14159265359is better than callingACOS(-1.0)each scan. - Use integer arithmetic when possible – integer operations are faster than floating‑point on many PLCs.
- Be mindful of array bounds – accessing outside the array may cause a runtime fault or memory corruption.
- Consider multi‑tasking – move non‑critical calculations to a slower periodic task to free up the fast task for I/O and safety logic.
Conclusion
Structured Text provides PLC programmers with a high‑level, readable syntax for implementing complex mathematical calculations that would be impractical in graphical languages. By mastering variable types, operators, built‑in functions, and error handling, you can build robust algorithms for PID control, kinematic computations, signal processing, and more. Setting up your development environment correctly, adhering to best practices, and testing thoroughly will ensure your ST code performs reliably in production. For further reading, consult the IEC 61131-3 standard or the PLCopen organization, which offers free educational materials on ST and other IEC languages.