Skip to content

Function Blocks and Libraries

Commercial

Included in the public demo Compare editions

A FUNCTION_BLOCK keeps inputs, outputs and local state in each instance between calls and scans. Reuse the same definition for independent machines or sequences. Put shared TYPE enums, VAR_GLOBAL declarations, FUNCTION and FUNCTION_BLOCK declarations in PLCLibrary components on model nodes.

Each PLCProgram has its own instances and memory. A PLCLibrary supplies definitions; it has no scan or Run state. VAR_GLOBAL values are shared through internal signals, independently of instance memory.

One definition, many instances A PLC Library on a model node holds FUNCTION and FUNCTION_BLOCK definitions but never scans. Every active library is visible to every PLC Program of the model. Each program declares its own instances of a function block, such as two Gate instances in Line1 and one in Line2, and each instance keeps its own inputs, outputs and state between scans. One definition, many instances PLC Library definitions only, no scan FUNCTION_BLOCK Gate FUNCTION Scale Active includes it, Order sorts the libraries PLC Program Line1 gateIn : Gate own state gateOut : Gate own state PLC Program Line2 gate : Gate own state k := Scale(…) fresh on every call Every active library, including those in placed content, is visible to every program of the model.
The library supplies the definition; each program owns its instances. Stop → Run keeps instance state; Deploy and Reset start every instance cold.
PLCLibrary propertyTypeDefaultPurpose
NamestringemptyDisplay label; required valid IEC namespace when Code contains VAR_GLOBAL
CodeST sourceemptyTYPE enum / VAR_GLOBAL / FUNCTION / FUNCTION_BLOCK declarations
ActiveBooleantrueInclude this source in the model-wide library set
Ordernumber, unitless0Ascending compile inventory order

Active and Order use standard inspector editors; Name labels the source in the PLC editor title (for example CellBlocks.st). Edit opens Code in the shared PLC editor, with autosave and undo/redo. Save the document to retain the source.

A PLC Library selected in the editor: the inspector shows its Code, Active and Order, and Edit has opened the source with a FUNCTION_BLOCK and a FUNCTION in the PLC editor

All programs see all active model libraries, including placed content. The runtime sorts by Order, then source identity, then scene path; signatures are collected before bodies, so forward references work. Order does not allow same-name overrides.

  1. Add a PLCLibrary component to a model node and choose Edit.
  2. Enter this definition:
FUNCTION_BLOCK DelayCell
VAR_INPUT Enable : BOOL; Delay : TIME := T#1s; END_VAR
VAR_OUTPUT Ready : BOOL; END_VAR
VAR timer : TON; END_VAR
timer(IN := Enable, PT := Delay);
Ready := timer.Q;
END_FUNCTION_BLOCK
  1. Add a PLCProgram and open its editor:
PROGRAM Main
VAR cell : DelayCell; END_VAR
VAR_EXTERNAL Start : BOOL; Ready : BOOL; END_VAR
cell(Enable := Start, Ready => Ready);
END_PROGRAM
  1. Deploy and Run the program. Bind Start/Ready to model signals.

The instance retains Delay = T#1s until a call supplies another value. Read cell.Ready after a call, or copy it with Ready => Ready. Instance initialization can override inputs, for example cell : DelayCell := (Delay := T#2s);. You can also assign an input directly, then call the instance:

cell.Enable := Start;
cell.Delay := T#2s;
cell();
Ready := cell.Ready;

This is the same input pattern as fb.IN := x; fb(); for standard blocks. Assignment only stores the input; it does not run the block. The next call evaluates the block with its retained inputs. A call changes only the inputs it supplies; omitted inputs keep their values. Every VAR_IN_OUT argument is still required on every call. Direct assignment to an instance’s VAR_OUTPUT or private local is rejected. For PLCopen motion blocks, setting an input also does not start motion or validate an axis handle; these happen when the block is called.

Use VAR_INPUT for retained input values, VAR_OUTPUT for readable outputs, VAR for private state, and VAR_IN_OUT for references to caller variables. Calls always use named FB parameters: := for inputs/IN_OUT, => for output copies. RETURN; exits the current invocation. Constants use VAR CONSTANT. Use elementary VAR_TEMP for scratch values that start fresh on every invocation. They do not become retained instance state or appear in snapshots. VAR RETAIN and VAR PERSISTENT are accepted with an info message and behave like ordinary VAR; remanence is not simulated.

Every IN_OUT argument is required on every call and must have exactly the declared type. Allowed actual variables:

  • In PROGRAM: its VAR or VAR_EXTERNAL scalar, including a qualified GVL scalar or writable AT variable.
  • Inside an FB: its own VAR, VAR_OUTPUT or VAR_IN_OUT scalar, including pass-through.

Constants, expressions, literals, FB member expressions and FB inputs cannot be IN_OUT actuals. A qualified GVL member resolves as an external scalar and follows the same exact-type/write rules. One variable cannot serve two IN_OUT parameters of the same call. References are transient; do not bind IN_OUT in an initializer. External effects propagate through nested calls and participate in signal reads, writes and conflict checks.

Put enum definitions in the library’s Code to use the same named states in every program:

{attribute 'qualified_only'}
{attribute 'strict'}
TYPE
E_Step : (Idle := 0, Run, Done := 10) UINT;
END_TYPE

Each program can declare step : E_Step; and use CASE step OF E_Step.Idle: step := E_Step.Run; END_CASE;. Enum types also work as FUNCTION results and user FB parameters and locals. The library shares definitions; each program or FB instance keeps its own numeric value. Two libraries defining the same enum name are rejected, with both sources named in the diagnostics, even if their definitions match.

The base defaults to INT. An explicit enum default (:= Idle after the base) takes precedence over the member valued 0 or, if none exists, the first member. A variable initializer overrides that default. qualified_only requires E_Step.Idle outside the type definition; strict allows comparison and CASE but rejects arithmetic, integer assignment and use as a FOR counter. Without strict, integer-to-enum assignments warn and enum-to-integer assignments are allowed. Watch values show member names or E_Step#17 for an unknown number. Enum externals bind to Int signals and normalize reads to the enum base width.

A library can also be a global variable list (GVL). Set Name to a non-empty IEC identifier, such as GVL_Cell, and enter:

{attribute 'qualified_only'}
VAR_GLOBAL
count : INT := 7;
ready : BOOL := TRUE;
END_VAR

Every program can read GVL_Cell.ready and assign GVL_Cell.count. Values are shared through internal signals under PLC/GVL/; function block instance memory remains private to each program. With qualified_only, the signal name is GVL_Cell.count. Without the attribute, count and GVL_Cell.count both bind to signal count. GVL names are compared case-insensitively. Duplicate namespaces or the same unqualified variable name in two GVLs are compile errors. Reserved ST keywords cannot be used as GVL names. A qualified GVL scalar can also be passed to VAR_IN_OUT, following the parameter’s exact type and write rules.

VAR_GLOBAL CONSTANT declares compile-time constants without signals. RETAIN and PERSISTENT are accepted with an information message; remanence is not simulated. Globals are registered even if only read or not used yet. Reset restores declaration values once per signal; edits to library initializers take effect at the next Reset. Removing a library, clearing a model or deactivating the plugin releases generated signal paths and retains model-owned signals. See Virtual PLC for AT declarations, which bind by name and use addresses only for direction and diagnosis.

Use user FBs for repeated cell logic, reusable handshakes and wrappers around standard timers/counters. Nested user and standard FB instances are independent, including reset and snapshot state. Direct/indirect recursion is rejected. MC FBs must be declared in PROGRAM, not inside user FBs.

Library type identity is the defining document + PLCLibrary NodeId + POU name, independent of display name and placement. Repeated placements of one source share its definitions; two different sources defining the same POU name cause a compile error.

Libraries, your own functions and your own function blocks work in both simulation modes. The difference is when an instance runs and what it must do to be DES-ready:

Continuous simulationDES (event-driven)
GVL valuesPrograms exchange internal signals in Order within the same tickA changed GVL signal wakes programs that read it
GVL initial/reset valuesDeclaration values restored once per signal; initializer edits apply at the next ResetSame values, independent of runner deployment order
AT declarationsBind by name or pragma; %I read-only, %Q output, %M internalSame direction and normalization; signal reads wake the program
Function blocks availableStandard FBs, your own FBs and PLCopen MC_ blocksStandard FBs, your own FBs and PLCopen MC_ blocks (a fixed motion cycle advances the moves)
When an instance runsOn every scan, once per simulation tickOnly when its program scans: on start, on a change of a signal it reads, at a timer deadline, or again at the same time after its own change
Instance stateKept between scansKept between events; a change of FB state triggers another scan at the same time until the state is stable
Input member assignment (fb.IN := x; fb();)Stores the input, then evaluates the block at the callInput changes in standard/user FBs participate in settling; assignment alone does not evaluate the block
RETAIN / PERSISTENTAccepted with info; ordinary VAR lifetimeSame lifetime; no remanence simulation
Multiple namesIndependent scalar declarationsSame declarations and state tracking
PragmasEnum/GVL attributes evaluated; unsupported conditional compilation errorsSame compile rules
CASE rangesInclusive range selectionStep guards and D4 cycle detection use intervals
CONTINUENext iteration of the innermost loopSame flow; unreachable condition updates do not prevent D2
Integer/base-type storageFinite 8/16/32-bit wrap, 32-bit register intermediates; checked wide valuesSame arithmetic and step folding; NaN/Infinity conversion/storage policy unchanged
Bit accessRead/write one bit of a declared integer widthPer-bit D1 checks distinguish idempotent sets from toggles
VAR_TEMPReinitialized every invocationReinitialized every invocation; excluded from the persistent journal and D1 candidates
Library TYPE / ENUMAll programs share the type definition; each instance owns its value, wrapped to the enum baseSame defaults and values; enum constants are understood as CASE step labels, and wrapping back to the current step does not count as a step change
Timers (TON, TOF, TP)Advance with simulation timeAdvance with simulation time; the deadline wakes the program
Code that changes on every scanRuns, once per tickNever settles: finding D1, not DES-ready, experiment batches refuse the model
DES checkNot applicableWalks through your FUNCTION/FB bodies; D6 marks unanalysed constructs or incomplete analysis as not DES-ready without blocking ST compilation

Write FB logic that reacts to edges, step changes or timers, so that another call with unchanged inputs leaves the state unchanged. The rules and examples are in Writing ST for DES. CASE ranges participate in the same step-change checks as individual labels, and D2 accounts for condition updates skipped by an unconditional CONTINUE. Temporary values do not trigger persistent-state settling; retained input member writes do, including when the assignment is separate from the call.

See the complete language construct comparison and numeric rules for literals, widths, pure calculations and CONNECT limits.