Writing ST for DES
Section titled “Writing ST for DES”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 simulation | DES (event-driven) | |
|---|---|---|
| When a program scans | Once per simulation tick | On 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 functions | Supported | Supported, same results (ST Functions) |
| Standard and your own function blocks | Supported | Supported if their state settles (Function Blocks & Libraries) |
PLCopen MC_ blocks | Supported | Supported, robot groups included: a fixed motion cycle advances the moves, and the program scans again when a command finishes (PLCopen Motion) |
| Arrays | Supported | Supported: an array counts as one variable; a[i] := a[i] + 1 without a guard is D1 |
| DES check (D1–D6) | Not applicable | D1, D2, D5 and D6 make a program not DES-ready; D3 and D4 are hints |
| Experiment batches | Not applicable | Refuse a model with a program that is not DES-ready |
When a scan runs
Section titled “When a scan runs”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.
Count edges, not scans
Section titled “Count edges, not scans”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_VARVAR edge : R_TRIG; parts : CTU; cnt : INT;END_VARedge(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.
Measure time with timers
Section titled “Measure time with timers”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_VARVAR delay : TON;END_VARdelay(IN := Enabled, PT := T#2s);Ready := delay.Q;Wait between scans
Section titled “Wait between scans”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_VARVAR step : INT := 10;END_VARCASE step OF 10: Conveyor := TRUE; IF SensorAtStop THEN Conveyor := FALSE; step := 20; END_IF; 20: Conveyor := FALSE;END_CASE;Hold commands until feedback arrives
Section titled “Hold commands until feedback arrives”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_VARVAR step : INT := 10;END_VARCASE 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_VARVAR warningDelay : TON; dwell : TON;END_VARwarningDelay(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_VARVAR step : INT := 10;END_VARCASE step OF 10: IF StationReady THEN step := 30; END_IF;END_CASE;What the editor reports
Section titled “What the editor reports”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 / rule | Message |
|---|---|
| Info — RETAIN/PERSISTENT | RETAIN/PERSISTENT is accepted but not simulated yet — the variable behaves like VAR (no warm/cold start retention) |
| Info — AT | AT 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 polling | timer '<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 block | FB '<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 incomplete | construct 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.
Differences from cyclic scanning
Section titled “Differences from cyclic scanning”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.
Continuous simulation and DES
Section titled “Continuous simulation and DES”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.
| Construct | Continuous simulation | DES |
|---|---|---|
Multiple names (a, b : INT) | Independent variables with the same declared start value | Same variables; persistent changes participate in settling |
| Pragmas | Enum qualified_only/strict and GVL qualified_only are evaluated; other attributes/regions/unknown pragmas are ignored; {error ...} and conditional compilation produce errors | Same compilation; no events scheduled |
Leading _ in names | Accepted; __ and underscore-only names rejected | Same name rules |
| LREAL | Same double precision as REAL, distinct type name | Same values and calculations |
Based literals (2#, 8#, 16#) | Width-checked bit patterns, signed two’s-complement interpretation; wider patterns are errors | Same constants and width checks |
Typed literals (INT#5, WORD#16#8000) | The named type determines range/width | Analysed as the same typed constants |
| CASE ranges | Inclusive intervals; overlaps/reversed ranges are errors | Ranges participate in step-change guards and repeating-step checks |
FB input assignment (fb.IN := x; fb();) | Assignment stores the input; the call evaluates the block | Host/user FB input changes participate in settling; assignment alone does not evaluate the block |
| TIME multiplication/division by a number | Whole-ms TIME result; TIME / TIME rejected; zero divisor errors | Same result; constant timer presets feed D4 |
| MUL_TIME | Scales TIME, truncated to whole ms | Same calculation; constant presets feed D4 |
| DIV_TIME | Divides TIME, truncated to whole ms; zero divisor errors | Same calculation and errors; constant presets feed D4 |
| VAR_TEMP | Reinitialized on every scan/invocation | Excluded from the persistent journal, snapshots and D1 candidates |
| RETAIN / PERSISTENT | Accepted with info; ordinary VAR lifetime | Same lifetime; persistent VAR changes still participate in settling |
| CONTINUE | Next iteration of the innermost FOR/WHILE/REPEAT | Same flow; D2 ignores condition updates unreachable after unconditional CONTINUE |
TO_<T> | Infers the source conversion; existing rounding | Same calculations and input dependencies |
| MOVE | Returns its argument unchanged, including its type | Same value; persistent self-dependencies still count for D1 |
Power operator (**) | Right-associative REAL/LREAL result, above multiplication | Same calculation and constant folding |
| Integer/bit-string types and wrap | Finite 8/16/32-bit stores wrap, including INT/DINT; 32-bit register intermediates | Same arithmetic/folding; wrapping back to the current step is not a step change |
| LINT / ULINT / LWORD | Finite values limited to exact integers within magnitude 2^53 - 1; unsafe intermediate/store stops the PLC | Same exact range and runtime errors |
| STRING / WSTRING | Assignment truncates to the declared length; comparison by UTF-16 value | Same values; a text signal change wakes readers like any other signal |
Bit access (w.3) | Read BOOL or update one bit within the declared width | Per-bit dependencies: setting TRUE is idempotent; unguarded toggling triggers D1 |
| Bitwise AND / OR / XOR / NOT | Integer/bit-string width and signedness; BOOL stays logical | Same values and bit dependencies |
| SHL / SHR / ROL / ROR | Operate in IN’s width; signed SHR sign-extends, unsigned SHR zero-fills | Same values, widths and errors |
| NaN / ±Infinity conversion/storage | Pass through every integer type unchanged; only finite values wrap/check | Same policy in process-image normalization and folding; non-finite constants rejected |
| Integer/bit-string externals | Existing Int signals, normalized to the ST width; CONNECT transports signed 32-bit Int | Same normalization in the process image; input changes wake readers |
| TYPE / ENUM in programs/libraries | Numeric states with enum defaults and base-width stores; watch shows names or E_State#17 | Same values/defaults; enum CASE transitions protect state only when they leave the active step |
| Enum externals | Existing Int signals; reads normalize to the enum base | Same normalization and signal wakeups |
| VAR_GLOBAL / GVL | Internal signals under PLC/GVL/; later programs see earlier writes in Order | Changes wake programs that read the GVL signal |
| GVL initialization/reset | Restore declaration values once per signal; library initializer edits apply on next Reset | Same values, independent of runner deployment order |
| AT declarations | Address is syntax/direction only: %I read-only, %Q output, %M internal; bind by name/pragma, with info | Same direction/normalization; input changes wake readers |
| Identified output writers | One writer per program occurrence for all outputs | Same writer identity; committed signal changes wake readers |
| D6 analysis finding | ST still compiles and can run continuously | Unanalysed construct or incomplete analysis makes the program not DES-ready |
| Arrays | Element values are kept; copied by value into your own blocks | Same values; one variable for settling; a self-dependent element write without a guard is D1 |
PLCopen MC_ blocks | Motion advances once per simulation step, right after the scan | Motion 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.