Chapter 11 / 36

Build a state model

Describe what happens next, what allows it, and what must always remain true.

Four-state transfer model with acceptance, completion, interruption, acknowledgement and eligible reset arrows
Audit the exits. For every waiting state, identify normal progress, interruption, a time bound where needed, and a permitted recovery route. A box without an exit is unfinished design.

Try a useful review trick: cover the state names and read only the arrow conditions. Could two arrows be eligible at once? If so, circle that pair and write the priority. Then uncover the names and ask whether the selected transition tells the truth about the physical work. A state named COMPLETE should not be reachable merely because you removed an output.

State says what the machine is trying to do now

Imagine reading a program with twelve memory bits: seeking, filling, waiting, releasing, stopped, ready, and several variations of busy. Four are true. Is that a legitimate combination or a bug? If the answer requires searching the whole project, the representation is making the machine harder to understand.

A state model gives a sequence one current state from a defined set. The state describes an activity or situation, not merely an output. “SeekingCarton” explains why the conveyor is requested and what event matters next. “MotorOn” does not tell you whether the conveyor is bringing a carton in or taking one out.

This does not mean an entire factory should have one enormous state variable. Independent equipment can have independent state owners. The important rule is to represent mutually exclusive situations as mutually exclusive, and coordinate independent activities through explicit interfaces.

Build the model from the behaviour contract

For our simplified cell, begin with these states:

StatePurposeNormal way out
ReadyWait for an accepted cycle requestStart event with required permissives
SeekingBring a carton to the fill positionPosition confirmed
PositionedHold the carton while fill-entry conditions are establishedFilling permitted with position still confirmed
FillingDeliver the required amountTarget reached
ReleasingMove the completed carton awayExit completion confirmed
CompleteRecord the finished cycleExplicit preparation for another cycle
FaultedPreserve the reason for interruptionEligible reset and recovery assessment

Add entry assumptions, requested outputs, timeouts, and interruption responses to each state. A state without a defined exit may be intentional waiting, but it should have a visible reason. A transition without evidence is a guess.

“Exit completion confirmed” requires more thought than NOT CartonAtFill. A carton can leave the fill sensor and still jam farther downstream. If the contract promises full discharge, the sensing and event sequence must prove that promise. State design often reveals missing hardware evidence.

Write transitions as guarded decisions

A transition has a source state, a condition, and a destination. For Seeking, define Stop to an interrupted state, confirmed arrival to Positioned, and timeout to Faulted. Positioned then waits for fill-entry permission with the conveyor stopped. Do not assume that every condition has equal priority.

For clarity, the following excerpt isolates normal seeking logic and operational faults. It omits the rest of the machine and is not a safety function. NextState starts equal to State; the timer output has already been updated this invocation.

NextState := State;

CASE State OF
    STATE_SEEKING:
        IF StopRequest THEN
            NextState := STATE_INTERRUPTED;
        ELSIF OperationalFault THEN
            NextState := STATE_FAULTED;
        ELSIF CartonAtFill THEN
            NextState := STATE_POSITIONED;
        ELSIF ArrivalTimeout THEN
            NextState := STATE_FAULTED;
        END_IF;

    STATE_POSITIONED:
        IF StopRequest THEN
            NextState := STATE_INTERRUPTED;
        ELSIF OperationalFault OR NOT CartonAtFill THEN
            NextState := STATE_FAULTED;
        ELSIF FillEntryPermitted THEN
            NextState := STATE_FILLING;
        END_IF;
END_CASE;

State := NextState;

If the carton arrives while FillEntryPermitted is false, the sequence enters Positioned and removes the seeking request. It does not drive the carton past its destination while waiting for another condition. Losing position while waiting faults this model. Define an appropriate diagnostic reason and any maximum permitted wait in the complete application.

Choose when new-state outputs take effect

One clear pattern is to evaluate transitions, commit the new state, and then derive output requests from that committed state. Entering Filling can then remove the seeking conveyor request in the same invocation's command calculation.

SeekConveyorRequest := (State = STATE_SEEKING) AND NOT CartonAtFill;
ReleaseConveyorRequest := State = STATE_RELEASING;
FillRequest := State = STATE_FILLING;

ConveyorCmd := (SeekConveyorRequest OR ReleaseConveyorRequest)
               AND ConveyorPermitted;
DispenserCmd := FillRequest AND DispensePermitted;

Another design may derive outputs from the state at invocation entry and apply transitions for the next invocation. That introduces a different boundary. Either can be made deliberate, but mixing the two styles creates confusing one-scan delays. Document the chosen order and test entry and exit conditions.

Avoid several independent IF statements that repeatedly change the same state in one invocation. They may cascade through multiple states before outputs are published. A CASE over the current state or an explicit next-state calculation makes one transition evaluation easier to inspect.

Invariants tell you what must remain true

An invariant is a rule you expect to hold throughout operation. For the teaching cell, “the dispenser command and release-conveyor command are never simultaneously true” may be an important operational invariant. Another might be “only the sequence owner writes State.”

Use invariants to review the architecture and to design tests. If a new manual feature bypasses the sequence, does the output owner still prevent conflicting requests? If an invalid state value appears, do outputs fall to a defined non-demanding condition and does a diagnostic identify the problem?

An invariant in ordinary application code does not establish a protective safety function. Its value here is making software expectations precise and testable. Physical consequences and required protective measures still need the appropriate engineering process.

Entry actions are events, not permanent conditions

You may need to capture a recipe target once when Filling begins, or increment a cycle record once when Complete is entered. Writing that action on every scan of the state repeats it.

Calculate a state-entry event from a transition, or compare the committed state with its previous value under a documented update order. Keep the previous-state assignment after the consumers that need the comparison. A state-entry flag is another use of the history discipline learned with button edges.

Do not use entry actions to conceal essential continuous supervision. Capturing the target once may be correct; checking measurement validity only once may not be. Separate “initialize this operation” from “continue to permit this operation.”

Try it

A learner models a cylinder with Retracted, Extending, Extended, and Retracting. They transition from Extending to Extended after a fixed two seconds, even though an extended-position switch is available. They also allow ManualRetract to write the retract output directly from another routine.

Identify two design weaknesses. Propose a better normal transition and timeout rule, then describe how manual requests should reach the outputs without creating a second owner.

Work through the answer

Elapsed time does not prove the cylinder reached its position. Use the extended-position observation as the normal completion evidence, with any required signal qualification. Use a maximum travel interval to detect that completion was not observed. Record an “extension not confirmed” fault rather than calling the cylinder extended because time passed.

The second routine creates competing command ownership. Route the manual request through a defined mode and actuator owner. That owner arbitrates extend and retract demands, applies the agreed operational permissives, and writes each physical command once. Manual operation may use a different sequence policy, but it should not silently bypass conflict prevention.

Test absent feedback, both endpoint switches active, a stuck switch at the start, and a mode change during travel. Those cases force the state model to account for more than a perfect stroke. Modes and restarts develops the ownership and recovery decisions behind those tests.

Now make the decision yourself

Use the chapter’s model on a fresh question, then compare your reasoning with the worked decision.

How this becomes a program

What fact gives you permission to leave this state?

A clamp must close before a cylinder extends. Requesting the clamp is not evidence that it has closed.

CLAMPEXTENDRETRACTevent → state → output

Your first artifact

Under each state, write its output requests. On each arrow, write the observed completion condition. Give every wait an interruption path.

Open the worked decision
CASE State OF
  10: IF ClampClosed THEN NextState := 20; END_IF;
  20: IF Extended THEN NextState := 30; END_IF;
END_CASE;

Why this line belongs here

The state names say what is being attempted. The arrow labels say what was observed. The excerpt deliberately omits the fault branches so you can add contradictory limits, lost clamping and missing completion.

Change the task

Both cylinder end switches become true together. Draw the destination of that event, then decide which outputs should be requested there.

Machine notebook experiment

A simplified browser model. Use it to test an idea; it does not execute a vendor PLC runtime.

Start at home. Confirm clamping before extension; change the limit sensors to complete the cycle.

A state says what is happening; feedback grants permission for the next state.