Core Topics route · TFA-102

State Machines & Scheduling

Model device behaviour explicitly, then choose a scheduling approach that makes transitions, priorities and timing constraints controllable.

Foundation8 min reading + 25 min practiceWorked example

← Back to the learning library

Before you begin: Basic control flow and the component/interface concepts in TFA-101.

Reading time and practice time are estimates. Examples use fictional products and illustrative engineering values, not approved product limits.

Learning objectives

By the end of this module, you should be able to:

  • Express product behaviour using states, events, guards and actions.
  • Distinguish cyclic, cooperative and pre-emptive scheduling models.
  • Identify illegal transitions, timeouts and recovery paths.
  • Derive behavioural verification from the state model.

Lesson 1

1. State describes what is permitted now

A state machine is valuable when the same event must produce different behaviour depending on context. A state should represent a stable mode with defined permitted events, outputs and invariants. Events describe what happened; guards decide whether a transition is allowed; actions perform bounded work.

Avoid states that are merely points in a procedural flow. If a “state” is entered and immediately left without waiting for an event, it may be an action rather than a meaningful state.

Lesson 2

2. Define the abnormal path at the same time

For each state, consider timeout, cancellation, loss of communication, invalid sensor data and reset. Specify what must be made safe before entering an error state and what evidence is required before recovery. An error flag bolted onto the end of the design rarely captures these obligations.

Transition tables are often easier to review than diagrams because they can show current state, event, guard, action, next state and requirement identifier in one record.

Lesson 3

3. Scheduling is an architectural choice

A cyclic executive is simple and analysable when work is short and periodic. Cooperative scheduling adds flexibility but one badly behaved task can delay every other task. A pre-emptive RTOS improves responsiveness and isolation of rates, but introduces priorities, shared-resource hazards and more complex timing analysis.

Select the simplest model that satisfies latency, throughput and isolation needs. “We already use an RTOS” is not a scheduling rationale.

Lesson 4

4. Connect logical and run-time models

The state machine defines allowed behaviour; the scheduler determines when events and actions run. Document how events are queued, whether duplicates are coalesced, what happens when a queue is full and which context executes transition actions. Long-running actions should normally be split or delegated so the machine remains responsive.

Lesson 5

5. Make transition semantics reviewable

A transition table should identify the current state, event, guard, action and next state. Add the requirement or risk-control identifier when traceability matters. A guard should answer a question without changing state; otherwise checking whether a transition is allowed can itself alter behaviour.

Define run-to-completion explicitly: one event is handled before the next event changes the same machine. This does not mean actions may take unlimited time. Delegate long operations and return a completion event tagged with the initiating operation ID. Ignore or diagnose a late completion from a cancelled operation so it cannot move a new cycle into the wrong state.

State / eventCondition and actionNext state
Ready / StartConfiguration valid: issue bounded start request.Starting
Starting / StartedMatching operation ID: begin deadline monitoring.Running
Starting / TimeoutCancel operation and inhibit output.Fault
Any active / StopInvalidate operation ID and command safe response.Stopping

Lesson 6

6. Turn scheduling into a capacity argument

For periodic work, a first capacity check is utilisation: add each execution budget divided by its period. Tasks needing 1 ms every 10 ms and 2 ms every 20 ms consume 20% of a processor before interrupts and overhead. Utilisation below 100% is necessary in this simple model but does not prove deadlines: blocking, priorities, release jitter and burst arrivals may still make a task late.

Separate the period from the deadline. A service may run every 100 ms yet have to respond to a particular event within 10 ms. Choose an event-driven activation, a faster polling interval or a different allocation rather than pretending a 100 ms loop satisfies that requirement.

Specify missed-cycle behaviour. Catching up by executing many stale control steps immediately can be worse than skipping to the next valid time. State whether the task uses actual elapsed time, rejects stale work or enters a degraded mode.

Lesson 7

7. Control event overload and recovery

Event queues store outstanding work, not infinite processing capacity. Classify events: a current temperature display can often coalesce updates, whereas transaction completion and safety shutdown events must not be silently discarded. Reserve capacity or provide a separate path where a high-volume event could otherwise prevent urgent control.

After reset, choose a justified initial state using trustworthy persisted information and hardware observations. A retained state byte saying Running is insufficient authority to resume an actuator operation. Reconcile incomplete transactions, invalidate stale completion events and define which conditions must be re-established by self-test or an authorised user.

Decision guide

Which scheduling model fits?

ModelBest fitWatch for
Cyclic executiveFew periodic activities with short bounded execution.One slow activity stretches the complete cycle.
Cooperative tasksModerate complexity with deliberate yield points.Hidden blocking and starvation.
Pre-emptive RTOSMultiple rates, priorities or isolation needs.Races, priority inversion and difficult analysis.

Worked example

Worked example — reagent measurement cycle

Problem

A controller must warm, wait for a sample, stir, acquire data, stop safely and report completion.

Engineering approach

The behavioural model uses Idle, Warming, Ready, Measuring, Completing and Fault states. Every active state has a timeout. Loss of host communication allows the current safe step to complete and then transitions to Safe Stop. Periodic temperature control runs separately from the event-driven assay state machine.

Result

Product behaviour is not hidden in task timing. Nominal, timeout, abort and communication-loss scenarios can be tested directly from the transition table.

Engineering evidence

What should the work produce?

State diagram and transition table

Defines permitted behaviour and abnormal transitions.

Scheduling design

Records tasks, rates, priorities and blocking rules.

Event-interface specification

Defines queueing, overflow and execution context.

Behavioural test set

Covers each transition, guard and timeout.

Common failure patterns

What goes wrong?

  • Using boolean flags as an undocumented state machine.
  • Performing slow I/O inside a transition action.
  • Ignoring events that are unexpected in a state without recording them.
  • Assigning RTOS priorities by intuition rather than response-time needs.

Applied exercise · approximately 25 minutes

Review a valve cycle under delayed events

The sequence is Idle, Opening, Holding and Closing. Opening must complete within 100 ms. A Stop command can arrive at any time, and the actuator completion may arrive after Stop.

  1. Write transitions for Start, Opened, Stop, Timeout and Closed.
  2. Decide how a late Opened event is distinguished from a current operation.
  3. Allocate a 10 ms supervision task and explain whether a timeout response can occur exactly at 100 ms.
Review a suggested approach

Use an operation identifier and invalidate it when stopping or faulting. A stale Opened event must not enter Holding. Closing needs its own completion deadline and a defined response if closure cannot be confirmed. A global Stop transition still needs state-specific actions when an output is already safe.

With 10 ms polling, detection can occur almost one polling period after the threshold, plus scheduling and execution delay. Either allocate that delay within the system limit or use an appropriate timer/event design. Test Stop just before completion, timeout at the polling boundary and a reset while Closing. Preserve the expected final output in each case.

Completion criteria

  • All active states have timeout, cancellation and failure handling.
  • Late events cannot affect a later operation.
  • The timing argument includes detection granularity and scheduler delay.

This is a self-directed engineering exercise, not an accredited examination. Compare the rationale as well as the final answer.

Practical check

Questions for your next design review

  • Does each state have a clear invariant?
  • Are timeout and cancellation defined for every active operation?
  • Are illegal events rejected and observable?
  • Is the maximum work per scheduler activation bounded?
  • Can tests demonstrate every transition and guard outcome?
Key takeaway

Model what the device may do independently from when the processor happens to run the code.

References and further reading

Educational guidance only. Apply the authorised standards editions, regulations and approved procedures relevant to your product and market. Linked publications support further study; the fictional exercises do not demonstrate compliance.