Skip to content

ST Functions

Commercial

Included in the public demo Compare editions

Use built-in functions for calculations, limits, selection and explicit type conversion in a PLCProgram or user POU. A function returns a value; its local variables start fresh on every call. Use a function block when you need persistent state.

A function call inside a program scan During a scan, a program expression calls a function such as Scale with all inputs given in every call. The function body runs with local variables that start fresh on every call, assigns its result to the function name and returns it to the expression. The program then assigns the result to a signal. A function keeps no state between calls. State that must persist belongs in a function block. Program scan Demand := Scale( value := Raw, factor := 2.0); FUNCTION Scale all inputs required locals start fresh each call Scale := value * factor returns the result; RETURN exits with the current value of Scale A function keeps no state between calls and has no clock. For persistent state use a function block.
A function returns a value and forgets everything between calls.
FamilyFunctionsParameters / result
TrigonometrySIN, COS, TAN, ASIN, ACOS, ATANIN: numeric → REAL; angles in radians
Two-argument angleATAN2IN1 (y), IN2 (x): numeric → REAL
MathSQRT, EXP, LN, LOGIN: numeric → REAL; LOG is base 10
Absolute valueABSIN: numeric → same type
PowerEXPTIN1, IN2: numeric → widest input type
Power operator**Numeric operands → REAL/LREAL; right-associative, above multiplication
ExtremaMIN, MAXIN1, IN2, …: numeric, at least two → widest type
LimitLIMITMN, IN, MX: numeric → min(max(IN, MN), MX)
SelectionSELG: BOOL, IN0, IN1 → IN0 when FALSE, IN1 when TRUE
MultiplexerMUXK: INT, IN0, IN1, … → zero-based selected value
TruncationTRUNCIN: REAL → DINT, toward zero
Conversion<S>_TO_<T>All 256 pairs of the 16 elementary types, including identity and all integer/bit-string types
Inferred-source conversionTO_<T>IN: elementary → any elementary target type; source type inferred
CopyMOVEIN: elementary → same value and type
Duration scalingMUL_TIME, DIV_TIMEIN1: TIME, IN2: numeric → TIME, truncated to whole milliseconds
BitsSHL, SHR, ROL, RORIN: integer/bit-string, N: integer; result: type of IN, operation in IN width

Numeric inputs include SINT, USINT, INT, UINT, DINT, UDINT, LINT, ULINT, BYTE, WORD, DWORD, LWORD, REAL and LREAL. Promotion follows width/signedness; equal-width signed/unsigned operands use the next wider signed type (64-bit combinations use LINT), with LREAL above REAL above integers. LREAL has its own type name and uses the same double-precision representation as REAL. Based literals (2#, 8#, 16#) are bit patterns: if they fit unsigned into the target or promoted context width, signed types interpret them in two’s complement (for example DINT := 16#80000001 gives -2147483647); wider patterns are compile errors, decimal literals keep their numeric range checks, and typed literals use the named type’s width. SEL/MUX values can also all be BOOL or all TIME. MUX requires at least two values, and K must be INT. TIME conversions use milliseconds.

Use either positional arguments or entirely named arguments: LIMIT(0.0, Raw, 1200.0) and LIMIT(MN := 0.0, IN := Raw, MX := 1200.0).

Conversions require the declared source type exactly: REAL_TO_INT(2.5) returns 3; REAL_TO_INT(-2.5) returns -3 (halves away from zero). Use TRUNC to truncate. BOOL targets use nonzero = TRUE, including NaN. Conversion helpers round/truncate; integer storage then wraps to its 8/16/32-bit target width, including INT/DINT (a change from earlier behavior). Finite LINT/ULINT/LWORD operations and storage require exact JavaScript integers within magnitude 2^53 - 1; an unsafe intermediate or result stops the PLC with a RangeError, even when a later operation would reduce it. Unsigned stores reject finite negative values at 64 bits. NaN and ±Infinity are not wrapped or range-checked; they pass through integer conversions and storage unchanged (same policy as before), only finite values wrap. The same rounding applies to every REAL/LREAL-to-integer/bit-string conversion. TO_INT(x) infers x’s source type and applies that same conversion; it does not introduce a different rounding rule. Use TO_<T> for any supported elementary target, for example TO_USINT, TO_WORD, TO_LINT, TO_LREAL or TO_TIME.

MOVE(x) returns x unchanged, including its type and any NaN/Infinity value. MUL_TIME(T#5ms, 1.5) returns T#7ms; DIV_TIME(T#5ms, 2) returns T#2ms. The operators TIME * number, number * TIME and TIME / number use the same whole-millisecond truncation. TIME / TIME is rejected. DIV_TIME and TIME division raise a runtime error for a zero divisor; in a constant/start value that is a compile error.

SINT/USINT/BYTE use 8 bits, INT/UINT/WORD 16, DINT/UDINT/DWORD 32 and LINT/ULINT/LWORD 64. SINT, INT, DINT and LINT are signed; the others are unsigned. Named-variable narrowing requires an explicit conversion.

Use 2.0 ** 3 for powers. ** binds above multiplication and groups from the right: 2.0 ** 3 ** 2 is 2.0 ** (3 ** 2) and returns 512. The result is REAL, or LREAL when an operand is LREAL; EXPT keeps its existing widest-input result type. Domain/range errors use the same NaN/Infinity policy as EXPT.

Integer +, -, unary minus and * through 32-bit types use 32-bit registers; multiplication preserves the exact low 32 bits (DINT 2147483647 * 2147483647 gives 1). Assignment subsequently wraps to the target width. Typed literals outside their declared range are compile errors.

SHL/SHR/ROL/ROR operate in IN’s width: 8, 16, 32 or 64 bits. SHR sign-extends signed integers and zero-fills unsigned/bit-string types. SHL/SHR by N >= width return 0; rotations use N modulo width. Negative/invalid counts raise a runtime error. A 64-bit result outside the exact range also raises a runtime error. SHR(WORD#16#8001, 1) is 16#4000; ROL(WORD#16#8001, 1) is 16#0003.

Read or write individual integer/bit-string bits with w.3 / w.0 := TRUE; the literal/constant index is zero-based and must fit the declared width. Bit reads return BOOL.

Integer/bit-string externals bind to existing Int signals without changing model types. Int signals carry 32 bits (signed) through CONNECT. The local browser store can retain 4294967295 and 2^40, but those values cannot travel unchanged through CONNECT’s signed Int channel.

Open a PLCProgram with Edit, enter this source, then Deploy and Run:

PROGRAM LimitDemand
VAR_EXTERNAL Raw : REAL; Demand : REAL; END_VAR
Demand := LIMIT(MN := 0.0, IN := ABS(Raw), MX := 1200.0);
END_PROGRAM

Bind the external variables to model signals, using matching names or a signal pragma.

To define a reusable function, put this in a PLCLibrary:

FUNCTION Scale : REAL
VAR_INPUT value : REAL; factor : REAL; END_VAR
Scale := value * factor;
RETURN;
END_FUNCTION

Call Scale(value := Raw, factor := 2.0) in a program expression. All FUNCTION inputs are required each call. Assign the result to the function name; RETURN; exits with its current value. Only scalar elementary or enum parameters/results and local variables/constants are supported; a FUNCTION cannot instantiate FBs or use VAR_EXTERNAL, VAR_OUTPUT or VAR_IN_OUT.

Text functions work on STRING and WSTRING values (see Strings). Positions are 1-based and count UTF-16 characters. All text arguments of one call must be of the same kind: you cannot mix STRING and WSTRING, for example in CONCAT.

FunctionSignatureResultNotes
LENLEN(s)INTNumber of characters
LEFTLEFT(s, n)TextThe first n characters; n of 0 or less gives an empty string
RIGHTRIGHT(s, n)TextThe last n characters; RIGHT('ABCDE', 2) is 'DE'
MIDMID(s, n, pos)Textn characters starting at position pos; MID('ABCDE', 2, 2) is 'BC'
CONCATCONCAT(a, b, …)TextTwo or more strings joined
INSERTINSERT(s, ins, pos)Textins inserted after the first pos characters; pos 0 inserts at the start
DELETEDELETE(s, n, pos)Textn characters removed from position pos
REPLACEREPLACE(s, new, n, pos)Textn characters from pos replaced by new
FINDFIND(s, search)INTPosition of the first match, 0 if not found
STRING_TO_WSTRINGSTRING_TO_WSTRING(s)WSTRINGExplicit conversion
WSTRING_TO_STRINGWSTRING_TO_STRING(w)STRINGExplicit conversion

The result is stored in the declared length of the target variable: a longer result is truncated, for example a STRING(4) keeps 'ABCD' of 'ABCDE'. Positions and lengths outside the text are clamped, so these functions never raise a runtime error.

Conversions follow the existing naming: <T>_TO_STRING (for example INT_TO_STRING(42)) and STRING_TO_<T> (for example STRING_TO_REAL('3.5')). TO_STRING(x) infers the source type; a BOOL becomes 'TRUE' or 'FALSE'. An invalid text in STRING_TO_<T> returns 0 (FALSE for BOOL) and logs a runtime warning once per call site. STRING and WSTRING convert to each other only explicitly.

PROGRAM Label
VAR_EXTERNAL Code : STRING; Prefix : STRING; END_VAR
Prefix := LEFT(Code, 3);
IF FIND(Code, 'ERR') > 0 THEN Prefix := 'ERR'; END_IF;
END_PROGRAM

Built-in functions work in both simulation modes and return the same result for the same inputs. Built-in functions have no state or clock; user FUNCTION bodies are analysed for DES suitability even when called through a library. What differs is how often the program that calls them scans:

Continuous simulationDES (event-driven)
Function availableAll built-in and your own FUNCTIONsAll built-in and your own FUNCTIONs
When it is evaluatedOn every scan, once per simulation tickOnly when the program scans: on start, when a signal it reads changes, when one of its timers runs out, or after its own change
ResultSame inputs give the same resultSame inputs give the same result
GVL values passed as argumentsRead the shared internal signal at the calling program’s scanA change of a GVL read wakes the calling program; the function receives the sampled value
Between two evaluationsThe result is at most one tick oldThe result stays at its last value until the next event
String functionsEvaluated on every scan; assignment truncates to the declared lengthSame results; they add no state and schedule no event
TO_<T>Infers source conversion with existing roundingSame conversion and dependency analysis
MOVEPreserves argument value/typeSame value; self-dependencies still count for D1
MUL_TIMETIME × number, truncated to whole msSame result; constant presets feed D4
DIV_TIMETIME / number, truncated to whole ms; zero divisor errorsSame result/errors; constant presets feed D4
Power operator (**)Right-associative REAL/LREAL calculationSame result and constant folding
Based/typed literalsWidth-checked constants; based patterns can use signed two’s complementSame constant values and checks
NaN / ±Infinity conversion/storagePass through integer types unchangedSame process-image normalization and constant policy
Integer storage and register arithmeticWrap at 8/16/32-bit stores; 32-bit intermediatesSame results; constant folding and step guards use the same normalization
LINT/ULINT/LWORDExact up to magnitude 2^53 - 1; unsafe intermediate/store is a runtime errorSame limit and runtime error
Bit access and width-specific shifts/rotatesDeclared type width; bit reads are BOOLSame values; per-bit dependency checks distinguish idempotent sets from unguarded toggles
External integer readsNormalize existing Int signal values to the ST widthSame normalization in the DES process image
DES checkDoes not prevent continuous executionPure built-ins add no state; user FUNCTION bodies are checked, including D6 on incomplete analysis

TO_<T>, MOVE, MUL_TIME, DIV_TIME and ** use the same eager calculations and error behavior in both modes. They do not schedule a DES event or create retained state. Constant duration calculations, such as T#40ms * 2, are included when the DES check examines timer presets for short polling loops. Self-dependencies in assignments still matter: count := MOVE(count) + 1 can trigger D1. D6 marks a program not DES-ready when its analysis is incomplete or encounters an unanalysed construct; ordinary ST compilation remains available.

If a result must follow a value that changes between events, compute it from a signal that changes with it. A function does not wake a program in DES. For elapsed time, use TON, TOF or TP; see Writing ST for DES.

  • Clamp an actuator demand with LIMIT.
  • Calculate geometry with SQRT, ATAN2 and trigonometric functions.
  • Select operating values with SEL/MUX.
  • Convert explicit numeric types before assigning a narrower value.
  • Split, join and compare barcodes and part numbers with the string functions.

The complete language scope and construct comparison also covers CASE ranges, pragmas, CONTINUE, VAR_TEMP, retention, enums, GVL and AT.