Sequences and State Machines

Step sequencing and state machines, with a traffic light, a tank filler and a pick-and-place cycle.

Why use a state machine

Anything that goes “do A, then B when C happens” is a sequence. The beginner’s way to build one is a chain of latched bits, one per step, each set by the previous one. It works for three steps and becomes unreadable at thirty. A state machine keeps the current step in one variable, so exactly one state is active, you can see what the machine is waiting for, and you can add steps, faults and modes without untangling latches.

  • One state at a time. There is no way for two steps to be active by mistake.
  • Visible. Show the state number on the HMI and the operator and the maintenance technician know what the machine is doing and what it is waiting for.
  • Outputs from one place. The state decides the outputs, so there is one place to look when something moves unexpectedly.
  • Easy to extend. Insert a state, add a transition, and the rest is untouched.

The idea: states, transitions and actions

TermMeaningExample
StateWhat the machine is doing now; identified by a numberS10 Filling
Action (outputs)What is on while the state is activeInlet valve open
TransitionA condition that moves the machine to another stateLevel high
Entry actionSomething done once when the state is enteredReset the mix timer
TimeoutA maximum time allowed in a stateIf filling takes over 120 s, go to Fault
Fault stateA safe state reached from any other on an errorAll off, alarm on; Reset returns to Idle
  • Every state needs an exit, including a timeout, so that a stuck sensor causes a fault instead of a frozen machine.
  • The state variable is the only thing that changes state. Do not set outputs in several places for the same sequence.
  • Think about power-up. Decide the state the machine is in after a power loss: usually Idle, or a Recovery state that checks the position of everything.

Building it in ladder

In ladder, the state is an integer (say State) and each state is a rung with an equal-to compare. A transition rung moves a new number into State. Outputs are driven from rungs that test the state.

RungLogicEffect
1: initializeFirst scan → MOVE 0 to StateStarts in Idle after power-up
2: transition 0 to 10EQU State = 0, Start_PB, Level_Low → MOVE 10 to StateIdle moves to Filling
3: transition 10 to 20EQU State = 10, Level_High → MOVE 20 to StateFilling moves to Mixing
4: outputEQU State = 10 → Inlet_ValveValve is open only in state 10
5: outputEQU State = 20 → AgitatorAgitator runs only in state 20
6: timeoutEQU State = 10, timer done → MOVE 90 to StateFilling takes too long: fault
  • Transitions before outputs. Put all the MOVE rungs in one section, then the output rungs, so the order is clear. If a state changes in the middle of the scan, the output rungs after it already see the new state.
  • Use a one-scan guard so that a MOVE does not cascade through several states in one scan: either only one transition per scan, or accept it knowingly.
  • Reset timers on entry by driving a timer’s IN from the state compare, so that leaving the state resets the timer.
  • Alternative: one bit per state (a “step bit”), where the transition sets the next bit and clears the current one. Works, but the integer is easier to display and to extend.

Building it in Structured Text

A CASE statement makes the state machine compact and readable. Keep the transitions and the outputs separate: first decide the next state, then set the outputs from the state.

(* 1. transitions *)
CASE State OF
    0:  IF Start AND Level_Low THEN State := 10; END_IF;
    10: IF Level_High      THEN State := 20; END_IF;
        IF FillTimer.Q     THEN State := 90; END_IF;     (* timeout *)
    20: IF MixTimer.Q      THEN State := 30; END_IF;
    30: IF Level_Empty     THEN State := 0;  END_IF;
    90: IF Reset AND NOT Fault_Cause THEN State := 0; END_IF;
END_CASE;

(* 2. timers: running only in their own states *)
FillTimer(IN := (State = 10), PT := T#120s);
MixTimer (IN := (State = 20), PT := T#120s);

(* 3. outputs from the state *)
Inlet_Valve := (State = 10);
Agitator    := (State = 20);
Outlet_Valve:= (State = 30);
Alarm       := (State = 90);

Because the timers’ IN is State = 10, leaving state 10 automatically resets the timer: no extra logic.

Example 1: a traffic light

A two-way intersection cycles north-south green, then yellow, then an all-red clearance, then east-west green, yellow and all-red. It is the standard first state machine.

North-southgreen 30 sredEast-westredgreen 30 s0 s10 s20 s30 s40 s50 s60 s70 sFour TON timers in sequence (or one state number): each phase starts the next.Both directions are red for 2 s after each yellow (the clearance interval). The cycle time is 30 + 4 + 2 + 30 + 4 + 2 = 72 s.
The timing of one cycle. Each phase is a state; a TON timer moves to the next.
StateNorth-southEast-westTimeNext when
10GreenRed30 sTimer done → 20
20YellowRed4 sTimer done → 30
30RedRed2 sTimer done → 40
40RedGreen30 sTimer done → 50
50RedYellow4 sTimer done → 60
60RedRed2 sTimer done → 10
CASE State OF
    10: IF T.Q THEN State := 20; END_IF;
    20: IF T.Q THEN State := 30; END_IF;
    30: IF T.Q THEN State := 40; END_IF;
    40: IF T.Q THEN State := 50; END_IF;
    50: IF T.Q THEN State := 60; END_IF;
    60: IF T.Q THEN State := 10; END_IF;
END_CASE;
T(IN := TRUE, PT := Preset);          (* one timer, preset set per state *)
NS_Green  := (State = 10);  NS_Yellow := (State = 20);  NS_Red := NOT (NS_Green OR NS_Yellow);
EW_Green  := (State = 40);  EW_Yellow := (State = 50);  EW_Red := NOT (EW_Green OR EW_Yellow);

Worked example: the cycle and the safety

  • Cycle time: 30 + 4 + 2 + 30 + 4 + 2 = 72 s; each direction is green 30 of every 72 s (42 %).
  • Safety design. The two greens must never be on together. Because both are derived from one state, that cannot happen in the program; a hardware conflict monitor still checks the real lamp outputs.
  • Fault state. If a lamp fails or the controller faults, the intersection goes to a flashing-red (or dark) state, defined by the traffic authority, not by the programmer.
  • Pedestrian request. Add a button that sets a flag, and use it to shorten the green in state 10 or 40: another condition on the transition.

Example 2: a tank filler

S0 Idleall offS10 Fillinginlet openS20 Mixingagitator onS30 Drainingoutlet openstart and level lowlevel highmix time donelevel empty: back to IdleS90 Faultall off, alarm onFrom any state: timeout, high-high level,or a stuck sensor. Reset returns to S0.Only the state number (one integer) decides which outputs are on.
States of a tank filler: Idle, Filling, Mixing, Draining, with a Fault state reachable from any state.
  • S0 Idle: all off. Start pressed and the level low moves to S10.
  • S10 Filling: inlet valve open. Level high moves to S20; a 120 s timeout moves to S90.
  • S20 Mixing: agitator on for the mix time. Timer done moves to S30.
  • S30 Draining: outlet valve open. Level empty returns to S0.
  • S90 Fault: everything off, alarm on, with the cause displayed. Reset (when the cause has cleared) returns to S0.

Worked example: how long should the fill timeout be?

  • A 1.5 m diameter tank, filling from 40 % to 80 % of a 3 m range: height 1.2 m, volume π × 0.75² × 1.2 = 2 121 L.
  • The pump supplies 20 L/s while the process takes 5 L/s, so the net rate is 15 L/s and the fill takes 2 121 ÷ 15 = 141 s.
  • Set the fill timeout at about 1.5 times the expected time (212 s, rounded up to 220 s), so a real fault is caught but normal variation does not trip it.

Example 3: a pick-and-place cycle

S10LowerZ down valve onuntil Z_Down sensorS20Gripgripper closesuntil Grip_OK sensorS30RaiseZ up valve onuntil Z_Up sensorS40MoveX forward valve onuntil X_End sensorS50Releasegripper opensuntil Open sensorS60ReturnX back, Z upuntil Home sensorCycle complete: back to step 10 for the next part (if Auto and Part_Present)Every step has a timeout: a missing sensor sets the Fault state instead of waiting forever.
A pneumatic pick-and-place cycle as steps, each waiting for its sensor.
StateOutputs onWaits forTypical time
LowerZ down valveZ_Down sensor0.8 s
GripGripper close valveGrip_OK sensor0.4 s
RaiseZ up valveZ_Up sensor0.8 s
MoveX forward valveX_End sensor1.2 s
ReleaseGripper open valveOpen sensor0.4 s
ReturnX back and Z up valvesHome sensor1.0 s
  • Each step waits for its position sensor, not just for a timer, so that the cycle waits for the real movement. A timer alone would carry on if the gripper jammed.
  • Each step has a timeout of about 2–3 times its normal time that goes to a fault.
  • Sensor-proven transitions are the basis of safe machine sequencing: an action is proven by a sensor, not assumed.

Worked example: the cycle time and the rate

  • The six steps take 0.8 + 0.4 + 0.8 + 1.2 + 0.4 + 1.0 = 4.6 s per part.
  • Rate: 60 ÷ 4.6 = 13.0 parts per minute, or 783 per hour.
  • The cycle is dominated by the slowest movements. To go faster, overlap independent steps that sensors prove are safe, such as starting the return while the gripper is still opening.

Auto, manual, faults and e-stop recovery

Mode or stateWhat it doesNotes
AutoRuns the sequenceStart and stop from the panel; the sequence state machine is active
Manual / jogLets a technician move one actuator at a timeInterlocks still apply: check limits and collisions. Manual should not be able to defeat a guard
Homing / resetBrings the machine to its start positionNeeded after a stop in mid-cycle or an e-stop
FaultA safe state with an alarmStay in Fault until the cause is gone and the operator has reset
E-stopPower to actuators removed in hardwareThe PLC only sees the status; after reset, decide whether to resume or to home
Hold / pauseFreezes the sequence in placeResume from the same state; timers may need care
  • Do not resume blindly. After an e-stop, pneumatic cylinders may have moved and parts may be in unexpected places. Go to a Homing state and check the sensors before restarting.
  • Keep mode logic separate from the sequence logic, so the sequence does not need to know why it was stopped.
  • Alarm states are latched and acknowledged; the machine does not restart by itself.

Debugging sequences

  • Show the state number and the name of what it waits for on the HMI.
  • Watch the transition condition, not the output: if the machine is stuck in S10, look at the level-high bit.
  • Force the transition in a simulator (with care) to test the next state.
  • Log state changes with a timestamp: the history shows where a rare fault occurred.
  • Test the faults, not only the good path: unplug a sensor, jam a cylinder, and press e-stop mid-cycle.

PackML and standard state models

PackML (from the OMAC packaging group, ISA-TR88.00.02) defines a standard set of machine states, so that every machine in a line reports and responds the same way: Idle, Starting, Execute, Holding, Held, Suspended, Aborting, Aborted, Stopping, Stopped, Resetting, Complete. Many packaging and some process machines use it. It is the same state-machine method with agreed names and transitions, plus modes (Production, Maintenance, Manual) and standard counters and times for OEE.

Related

FAQ

What is a state machine?

A way of programming a sequence by keeping the current step in one variable. The program decides what to do from the state, and changes state when a condition is met.

Should I use SFC or a CASE statement?

Both do the same job. SFC shows the sequence graphically and the active step is highlighted online; a CASE statement is compact and works on every platform. Use what your platform and your team prefer.

Why does my sequence jump straight through several steps?

Each state moves on in the same scan because its transition condition is already true. Make each state wait for a new condition (a sensor proving the previous action), or allow only one transition per scan.

How do I handle an emergency stop in a sequence?

The e-stop removes power in hardware. The program should notice the status, drop the outputs, move to a fault or stopped state, and require a reset and a homing or recovery routine before restarting.

Can I run two sequences at once?

Yes. Give each its own state variable (one for filling, one for packing), and have them exchange simple handshakes (“ready”, “done”), not shared latches.

References

  • IEC 61131-3 (SFC); IEC 60848, GRAFCET specification language for sequential function charts.
  • ISA-TR88.00.02 / OMAC PackML, Machine and Unit States; ISA-88 (batch control).
  • Siemens, S7-GRAPH and SIMATIC S7-1500 Programming Guideline; Rockwell Automation, Logix 5000 Sequential Function Chart Programming Manual.
  • Bolton, W., Programmable Logic Controllers, Newnes.

Last reviewed: October 2026. Instruction names, addresses and data sizes differ by manufacturer: confirm against your controller’s manual, and keep safety functions independent of standard PLC logic.