State machines in PLC programs
Writing sequences as explicit state machines with CASE and enumerations: entry actions, transitions, timeouts, error states — readable, testable and easy to diagnose.
Why
Sequences built from dozens of set/reset flags become impossible to debug: several flags are TRUE at once and nobody knows the real state. A state machine keeps exactly one current state and explicit transitions.
Pattern in ST
TYPE E_Fill : (Idle, Filling, Settling, Draining, Fault); END_TYPE
VAR
State : E_Fill := Idle;
LastState : E_Fill := Idle;
StepTime : TON;
END_VAR
StepTime(IN := (State = LastState), PT := T#1H); (* time in current state *)
LastState := State;
CASE State OF
Idle:
InletValve := FALSE; OutletValve := FALSE;
IF StartCmd AND Permissive THEN State := Filling; END_IF;
Filling:
InletValve := TRUE;
IF LevelHigh THEN State := Settling;
ELSIF StepTime.ET > T#120S THEN State := Fault; END_IF; (* timeout *)
Settling:
InletValve := FALSE;
IF StepTime.ET > T#30S THEN State := Draining; END_IF;
Draining:
OutletValve := TRUE;
IF LevelLow THEN State := Idle; END_IF;
Fault:
InletValve := FALSE; OutletValve := FALSE;
IF ResetCmd AND NOT LevelHigh THEN State := Idle; END_IF;
END_CASE;
Rules that pay off
- Outputs are a function of the state (and interlocks), not set in many places.
- Every waiting state has a timeout leading to a fault state.
- A global stop / emergency condition is checked before the CASE and forces a safe state.
- Show the state (number and text) on the HMI — commissioning becomes much faster.
- For complex parallel sequences use SFC (GRAPH in TIA Portal) or split into several cooperating state machines.
Connections
Open in Knowledge Graph →Loading the map…
Sources
Updated 2026-10-02