Skip to content

Running ST in DES

Commercial

Included in the public demo Compare editions

In discrete-event simulation (DES), write logic that waits for a signal or a timer and then settles: another scan with unchanged inputs leaves the same state.

Continuous simulationDES (event-driven)
When a program scansOnce per simulation tickOn start, when a signal it reads changes, at a timer deadline, and again at the same time after its own change
Built-in and your own functionsSupportedSupported, same results (ST Functions)
Standard and your own function blocksSupportedSupported if their state settles (Function Blocks & Libraries)
PLCopen MC_ blocksSupportedSupported, robot groups included: a fixed motion cycle advances the moves, and the program scans again when a command finishes (PLCopen Motion)
ArraysSupportedSupported: an array counts as one variable; a[i] := a[i] + 1 without a guard is D1
DES check (D1–D6)Not applicableD1, D2, D5 and D6 make a program not DES-ready; D3 and D4 are hints
Experiment batchesNot applicableRefuse a model with a program that is not DES-ready

In event-driven DES, your program scans when it starts, after a cold reset, when a signal it reads changes, or when one of its timers reaches a deadline. A write-only signal does not wake it. If a scan changes its memory, a function block’s state or an output it reads, it scans again at the same simulated time. Other programs that read a changed output also wake. Programs run in their configured order, once per round, until the state is stable.

The limit is 64 rounds at one time. If the state keeps changing, the affected programs enter error and Problems reports des-settle-overflow. The scan watchdog still limits time spent inside a single scan. RV_FirstScan is true only in the first scan after a cold start, not at every event.

Signal writes reach each program in order. Here, batch means a setMany write is seen as its end state: all values in that write arrive together, and only the last value for each signal is visible. Separate writes can cause separate scans, even at the same simulated time.

The examples below are program fragments. Put the declarations in your program’s variable blocks and the statements in its scan body.

Change a counter on an edge or a step change. A level condition can remain true for several scans at the same time.

Bad: counts every scan while a part remains at the sensor.

IF PartPresent THEN cnt := cnt + 1; END_IF;

Good: counts each arriving part once.

VAR_EXTERNAL
PartPresent : BOOL;
ResetBatch : BOOL;
END_VAR
VAR
edge : R_TRIG;
parts : CTU;
cnt : INT;
END_VAR
edge(CLK := PartPresent);
parts(CU := edge.Q, R := ResetBatch, PV := 10);
cnt := parts.CV;

A timer’s Q is also a level. Use R_TRIG on it, or reset the same timer with IN := FALSE on every path through the counting branch. A step guard also protects a counter when every path after the increment leaves that step. You can use RV_FirstScan for one-time initialization. A stable self-hold such as motor := start OR (motor AND NOT stop) is allowed.

Use TON, TOF or TP for elapsed simulation time. Scans per second are no measure of time in DES.

Bad: assumes 120 scans mean two seconds.

IF Enabled AND waitScans < 120 THEN
waitScans := waitScans + 1;
END_IF;
Ready := waitScans >= 120;

Good: waits two simulated seconds.

VAR_EXTERNAL
Enabled : BOOL;
Ready : BOOL;
END_VAR
VAR
delay : TON;
END_VAR
delay(IN := Enabled, PT := T#2s);
Ready := delay.Q;

A sensor cannot change while a scan waits inside a loop. Use a step chain that returns control and resumes when the input changes. Loops for calculations are fine when their own body advances the exit condition.

Bad: waits for the conveyor sensor inside one scan.

WHILE NOT SensorAtStop DO
Conveyor := TRUE;
END_WHILE;

Good: holds the conveyor on until the sensor arrives.

VAR_EXTERNAL
SensorAtStop : BOOL;
Conveyor : BOOL;
END_VAR
VAR
step : INT := 10;
END_VAR
CASE step OF
10: Conveyor := TRUE;
IF SensorAtStop THEN
Conveyor := FALSE;
step := 20;
END_IF;
20: Conveyor := FALSE;
END_CASE;

For a level-controlled actuator, keep the command active until its feedback confirms the movement. Advancing to the next step does not guarantee that simulated time passes.

Bad: clears the command in the next scan, which can occur at the same time.

CASE step OF
10: Extend := TRUE; step := 20;
20: Extend := FALSE;
IF IsExtended THEN step := 30; END_IF;
END_CASE;

Good: keeps the command active until the cylinder reaches its end position.

VAR_EXTERNAL
Extend : BOOL;
IsExtended : BOOL;
END_VAR
VAR
step : INT := 10;
END_VAR
CASE step OF
10: Extend := TRUE;
IF IsExtended THEN
Extend := FALSE;
step := 30;
END_IF;
30: Extend := FALSE;
END_CASE;

Use a second timer for an intermediate deadline

Section titled “Use a second timer for an intermediate deadline”

ET updates only when its timer is evaluated at an event. Reading ET does not schedule a scan at the threshold you compare it with.

Bad: expects a one-second event from a five-second timer.

dwell(IN := Running, PT := T#5s);
Warning := dwell.ET >= T#1s;

Good: gives each deadline its own timer.

VAR_EXTERNAL
Running : BOOL;
Warning : BOOL;
Done : BOOL;
END_VAR
VAR
warningDelay : TON;
dwell : TON;
END_VAR
warningDelay(IN := Running, PT := T#1s);
dwell(IN := Running, PT := T#5s);
Warning := warningDelay.Q;
Done := dwell.Q;

Wait for a signal instead of polling with short timers

Section titled “Wait for a signal instead of polling with short timers”

A repeating 20 ms timer creates about 50 timer events per simulated second. Wait directly for a signal level when you need no actual delay.

Bad: repeatedly checks readiness through a timer loop.

CASE step OF
10: poll(IN := TRUE, PT := T#20ms);
IF poll.Q THEN
poll(IN := FALSE);
step := 20;
END_IF;
20: IF StationReady THEN step := 30; ELSE step := 10; END_IF;
END_CASE;

Good: resumes when the readiness signal changes.

VAR_EXTERNAL
StationReady : BOOL;
END_VAR
VAR
step : INT := 10;
END_VAR
CASE step OF
10: IF StationReady THEN step := 30; END_IF;
END_CASE;

The editor shows compiler errors, warnings and infos separately in its Errors / Warnings / Infos row. RETAIN/PERSISTENT and the AT address binding message are information messages and do not block deployment. DES findings have separate information markers; their messages start with DES: . D1, D2, D5 and D6 give the program a not DES-ready badge in the status and program list. When you start DES, Problems reports PLC program cannot run on events, naming the program and line. Interactive DES start reports this error without a hard stop; experiment batches refuse the run. D3 and D4 are hints and do not block a run. D5 applies only to a motion program in a DES run that has no motion cycle: it goes into error at its first scan. PLCopen MC_ blocks themselves run in DES.

The compiler info rows below have no DES: prefix. DES rule messages follow that prefix. Placeholders identify your variable, timer or loop; n is the timer preset in milliseconds.

Kind / ruleMessage
Info — RETAIN/PERSISTENTRETAIN/PERSISTENT is accepted but not simulated yet — the variable behaves like VAR (no warm/cold start retention)
Info — ATAT address %IX0.0 is not used for binding; the variable binds by name (uses the written address)
D1 — state changes on every scan'<v>' changes on every scan without an edge, timer or step change — never settles in DES. Use R_TRIG, CTU or a timer.
D2 — waiting inside a scan<WHILE|REPEAT> loop condition never changes inside the loop — it waits within one scan and never ends in DES. Use a step chain instead.
D3 — elapsed-time read'<inst>.ET' is only current at event times in DES — compare against a second timer instead.
D4 — short timer pollingtimer '<inst>' (PT <n> ms) restarts in a step chain without an input condition — costs about <round(1000/n)> events per second in DES. Wait for a signal level instead.
D5 — continuous-only blockFB '<inst>' (<type>) needs continuous simulation and is not available in DES. (no built-in block today) or, for a motion program without the DES motion cycle, D5: PLC motion in DES needs the fixed motion cycle (Core.Cycle), which is not available in this run.
D6 — analysis incompleteconstruct not analysed by the DES check (<construct>) or DES analysis incomplete (<reason>)

D4 checks TON and TP timers with a constant preset below 100 ms, including a preset from the declaration, a member assignment (t.PT := T#40ms * 2;) or a call. It looks for IN := TRUE in a CASE step, including range labels, without an additional condition that reads a signal your program does not write, and only reports it when the step chain comes back to that step without a step that waits for a signal. A one-time delay, for example a valve switching time, is not reported.

D1 tracks individual integer bits: w.3 := TRUE settles, while w.3 := NOT w.3 needs a guard. Constant folding and step-change checks use the same wrap and 32-bit intermediate arithmetic as execution. If an INT step expression wraps back to the same step, it does not protect a counter.

D2 accounts for CONTINUE: WHILE flag DO CONTINUE; flag := FALSE; END_WHILE never reaches the assignment that would end the loop. D6 reports an unknown construct or incomplete analysis, including an analysis limit or internal failure. D6 blocks DES suitability without blocking ordinary ST compilation; review the source before using continuous simulation.

If you have checked that a flagged statement settles, add (* @des: allow *) on the same line as the assignment or the opening WHILE/REPEAT keyword. It suppresses D1 or D2 for that statement only. It does not suppress D3/D4/D5/D6, change execution or remove the runtime limits. The checker cannot prove that several programs together settle; a step cycle or conflicting programs can still reach the round limit.

Step chains can pass through several steps without advancing time. An output set in one scan and cleared in the next can therefore form a zero-time pulse. Signal subscribers can see separate writes; a consumer that only checks the level during a movement tick can miss the pulse. Hold level commands until feedback, and use a timer when a pulse needs a duration.

Between events, timer ET values can stay unchanged and there is no fixed scan rate. Use simulation time, timer outputs and plant feedback to judge progress. Continuous/Live operation keeps cyclic scanning.

The same language constructs run in both modes. Continuous simulation scans each tick; DES scans on events and repeats at the same simulated time until persistent state settles.

ConstructContinuous simulationDES
Multiple names (a, b : INT)Independent variables with the same declared start valueSame variables; persistent changes participate in settling
PragmasEnum qualified_only/strict and GVL qualified_only are evaluated; other attributes/regions/unknown pragmas are ignored; {error ...} and conditional compilation produce errorsSame compilation; no events scheduled
Leading _ in namesAccepted; __ and underscore-only names rejectedSame name rules
LREALSame double precision as REAL, distinct type nameSame values and calculations
Based literals (2#, 8#, 16#)Width-checked bit patterns, signed two’s-complement interpretation; wider patterns are errorsSame constants and width checks
Typed literals (INT#5, WORD#16#8000)The named type determines range/widthAnalysed as the same typed constants
CASE rangesInclusive intervals; overlaps/reversed ranges are errorsRanges participate in step-change guards and repeating-step checks
FB input assignment (fb.IN := x; fb();)Assignment stores the input; the call evaluates the blockHost/user FB input changes participate in settling; assignment alone does not evaluate the block
TIME multiplication/division by a numberWhole-ms TIME result; TIME / TIME rejected; zero divisor errorsSame result; constant timer presets feed D4
MUL_TIMEScales TIME, truncated to whole msSame calculation; constant presets feed D4
DIV_TIMEDivides TIME, truncated to whole ms; zero divisor errorsSame calculation and errors; constant presets feed D4
VAR_TEMPReinitialized on every scan/invocationExcluded from the persistent journal, snapshots and D1 candidates
RETAIN / PERSISTENTAccepted with info; ordinary VAR lifetimeSame lifetime; persistent VAR changes still participate in settling
CONTINUENext iteration of the innermost FOR/WHILE/REPEATSame flow; D2 ignores condition updates unreachable after unconditional CONTINUE
TO_<T>Infers the source conversion; existing roundingSame calculations and input dependencies
MOVEReturns its argument unchanged, including its typeSame value; persistent self-dependencies still count for D1
Power operator (**)Right-associative REAL/LREAL result, above multiplicationSame calculation and constant folding
Integer/bit-string types and wrapFinite 8/16/32-bit stores wrap, including INT/DINT; 32-bit register intermediatesSame arithmetic/folding; wrapping back to the current step is not a step change
LINT / ULINT / LWORDFinite values limited to exact integers within magnitude 2^53 - 1; unsafe intermediate/store stops the PLCSame exact range and runtime errors
STRING / WSTRINGAssignment truncates to the declared length; comparison by UTF-16 valueSame values; a text signal change wakes readers like any other signal
Bit access (w.3)Read BOOL or update one bit within the declared widthPer-bit dependencies: setting TRUE is idempotent; unguarded toggling triggers D1
Bitwise AND / OR / XOR / NOTInteger/bit-string width and signedness; BOOL stays logicalSame values and bit dependencies
SHL / SHR / ROL / ROROperate in IN’s width; signed SHR sign-extends, unsigned SHR zero-fillsSame values, widths and errors
NaN / ±Infinity conversion/storagePass through every integer type unchanged; only finite values wrap/checkSame policy in process-image normalization and folding; non-finite constants rejected
Integer/bit-string externalsExisting Int signals, normalized to the ST width; CONNECT transports signed 32-bit IntSame normalization in the process image; input changes wake readers
TYPE / ENUM in programs/librariesNumeric states with enum defaults and base-width stores; watch shows names or E_State#17Same values/defaults; enum CASE transitions protect state only when they leave the active step
Enum externalsExisting Int signals; reads normalize to the enum baseSame normalization and signal wakeups
VAR_GLOBAL / GVLInternal signals under PLC/GVL/; later programs see earlier writes in OrderChanges wake programs that read the GVL signal
GVL initialization/resetRestore declaration values once per signal; library initializer edits apply on next ResetSame values, independent of runner deployment order
AT declarationsAddress is syntax/direction only: %I read-only, %Q output, %M internal; bind by name/pragma, with infoSame direction/normalization; input changes wake readers
Identified output writersOne writer per program occurrence for all outputsSame writer identity; committed signal changes wake readers
D6 analysis findingST still compiles and can run continuouslyUnanalysed construct or incomplete analysis makes the program not DES-ready
ArraysElement values are kept; copied by value into your own blocksSame values; one variable for settling; a self-dependent element write without a guard is D1
PLCopen MC_ blocksMotion advances once per simulation step, right after the scanMotion advances on a fixed motion cycle; a command is first integrated at the following cycle point; a change of a command status or InVelocity scans the program again

See Writing ST for DES for event timing, settling and diagnostic details.