DEV Community

Cover image for A PLC State Machine Is More Than a List of Steps
blessed Jegbefumwen
blessed Jegbefumwen

Posted on

A PLC State Machine Is More Than a List of Steps

When building a small automation sequence, it is tempting to write the logic as a chain of conditions:

if start_button:
    open_valve()

if sensor_active:
    start_pump()

if stop_button:
    stop_pump()
Enter fullscreen mode Exit fullscreen mode

That may work in a quick demonstration, but it becomes difficult to reason about once the process has multiple stages, timeouts, faults and recovery paths. What happens if the sensor is already active when the sequence starts? What if the pump never reaches its expected state? What if the operator requests a stop during a transition?

A state machine makes those behaviours explicit. It gives each operating mode a name, defines which transitions are allowed, and makes it easier to test the sequence before connecting it to real equipment.

This article builds a small, simulated sequence in Python. It is a learning example, not production PLC code: it does not connect to hardware, and its timings and conditions are illustrative.

Define the states before the logic

Consider a simple pump-start sequence:

  1. Wait for a start request.
  2. Check that the permissives are satisfied.
  3. Start the pump.
  4. Wait for feedback confirming the pump is running.
  5. Enter the running state.
  6. Stop safely when requested.
  7. Enter a fault state if feedback does not arrive in time.

These stages can be represented as an enumeration:

from enum import Enum, auto

class State(Enum):
    IDLE = auto()
    CHECK_PERMISSIVES = auto()
    STARTING = auto()
    RUNNING = auto()
    STOPPING = auto()
    FAULT = auto()
Enter fullscreen mode Exit fullscreen mode

Using named states is clearer than scattering numeric values or unrelated Boolean flags throughout the program. A state also gives the sequence a place to define what outputs are appropriate.

Represent inputs and outputs explicitly

A controller reads inputs and sets outputs. Keeping those separate in a simulation helps prevent the sequence logic from silently changing its own sensor readings.

from dataclasses import dataclass

@dataclass
class Inputs:
    start_requested: bool = False
    stop_requested: bool = False
    permissives_ok: bool = False
    pump_running_feedback: bool = False

@dataclass
class Outputs:
    pump_start_command: bool = False
Enter fullscreen mode Exit fullscreen mode

In a real PLC project, the input and output mapping depends on the controller, I/O configuration and site standards. Here, these classes simply make the example easier to inspect and test.

Make each scan a small, predictable step

The sequence can be modelled as a function that reads the current state and inputs, then updates the state and outputs. In a PLC, similar logic runs repeatedly as part of the scan cycle.

@dataclass
class PumpSequence:
    state: State = State.IDLE
    start_elapsed_s: float = 0.0
    feedback_timeout_s: float = 5.0

    def scan(self, inputs: Inputs, dt_s: float) -> Outputs:
        outputs = Outputs()

        if self.state == State.IDLE:
            if inputs.start_requested:
                self.state = State.CHECK_PERMISSIVES

        elif self.state == State.CHECK_PERMISSIVES:
            if inputs.stop_requested:
                self.state = State.IDLE
            elif inputs.permissives_ok:
                self.state = State.STARTING
                self.start_elapsed_s = 0.0
            else:
                self.state = State.IDLE

        elif self.state == State.STARTING:
            outputs.pump_start_command = True
            self.start_elapsed_s += dt_s

            if inputs.stop_requested:
                self.state = State.STOPPING
            elif inputs.pump_running_feedback:
                self.state = State.RUNNING
            elif self.start_elapsed_s >= self.feedback_timeout_s:
                self.state = State.FAULT

        elif self.state == State.RUNNING:
            outputs.pump_start_command = True

            if inputs.stop_requested:
                self.state = State.STOPPING

        elif self.state == State.STOPPING:
            outputs.pump_start_command = False
            self.state = State.IDLE

        elif self.state == State.FAULT:
            outputs.pump_start_command = False

        return outputs
Enter fullscreen mode Exit fullscreen mode

The timeout is deliberately simple. A real implementation would need to use the controller’s timing facilities and follow the project’s requirements for reset, fault indication and restart behaviour.

The state machine also makes an important design decision visible: if permissives are not satisfied, the example returns to IDLE. Another system might remain in a “waiting for permissives” state and show a message to the operator. The right choice depends on the process and its operating requirements.

Test transitions without hardware

Because the sequence is separated from physical I/O, we can exercise it with ordinary test inputs:

sequence = PumpSequence()
inputs = Inputs(start_requested=True, permissives_ok=True)

sequence.scan(inputs, dt_s=0.1)
print(sequence.state)
Enter fullscreen mode Exit fullscreen mode

A proper test suite should check the expected path and the less convenient cases:

  • A start request without permissives must not issue a pump command.
  • Valid permissives should allow the sequence to enter STARTING.
  • Running feedback should move it to RUNNING.
  • Missing feedback should eventually enter FAULT.
  • A stop request during startup should not leave the start command latched on.
  • A fault should not clear unless the defined reset conditions are met.

For example, a simple timeout test might look like this:

def test_missing_feedback_causes_fault():
    sequence = PumpSequence(feedback_timeout_s=0.3)

    sequence.state = State.STARTING
    inputs = Inputs(permissives_ok=True)

    sequence.scan(inputs, dt_s=0.1)
    sequence.scan(inputs, dt_s=0.1)
    sequence.scan(inputs, dt_s=0.1)

    assert sequence.state == State.FAULT
Enter fullscreen mode Exit fullscreen mode

This test checks one specific behaviour. It does not prove that the sequence is safe or suitable for an actual installation. It is a way to catch logic regressions before the logic is translated into a controller project.

Write down the transition table

The code is not the only useful representation. A transition table gives reviewers a compact view of the intended behaviour:

Current state Condition Next state Example output
IDLE Start requested CHECK_PERMISSIVES Pump command off
CHECK_PERMISSIVES Permissives satisfied STARTING Pump command off
STARTING Running feedback received RUNNING Pump command on
STARTING Feedback timeout FAULT Pump command off
RUNNING Stop requested STOPPING Pump command on for this scan
STOPPING Stop sequence complete IDLE Pump command off
FAULT Reset conditions met Defined reset state Pump command off

The table often reveals unanswered questions: Is there a separate reset request? Should the sequence wait for stopped feedback? What should happen if a permissive is lost while running? Those questions are easier to address during design review than after commissioning.

Avoid one state machine for everything

As a sequence grows, it can be tempting to add every operational detail to one large state machine. That can make the logic just as hard to understand as a collection of flags.

Keep the main sequence focused. Reusable checks, alarms and independent equipment behaviour may belong in separate components, depending on the architecture. The key is to define clearly how they interact and which part owns each output.

Also distinguish ordinary sequencing from safety functions. A sample program, a simulator or a unit test does not replace a risk assessment, safety design, controller validation or commissioning process.

Conclusion

A state machine is useful because it makes operating modes and transitions explicit. That helps engineers review the intended behaviour, test edge cases and understand why an output is active.

Start with the states and transition conditions. Keep inputs separate from outputs. Test both the normal sequence and the failure paths. Then review the design against the actual process requirements before implementing it on a controller.

The goal is not to add abstraction for its own sake. It is to make automation logic easier to explain, verify and maintain.

Top comments (0)