Computer Science

Finite State Machines (FSM)

A computational model that represents a system with a fixed number of states and rules for switching between them based on inputs. Used to design predictable behavior in software, games, and devices.

finite state machine FSM states transitions Mealy Moore machines
Created: December 18, 2025

What is a Finite State Machine?

A finite state machine (FSM) is a computational model consisting of a finite number of states, transitions between those states, and rules determining state changes based on inputs. FSMs provide a mathematical framework for modeling sequential logic in systems where behavior depends on event sequences or specific conditions.

Core Principles:

  • System exists in exactly one state at any given time
  • Inputs trigger transitions between states
  • Rules define valid state changes
  • Outputs may depend on states and/or inputs

Analogy:
A door lock operates as a simple FSM with two states: locked and unlocked. A correct key transitions the lock from locked to unlocked, while an incorrect key maintains the current state. The lock’s behavior is entirely predictable based on its current state and input received.

Core Components

States

Definition: Distinct configurations or modes in which a system can exist.

Characteristics:

  • System occupies exactly one state at any moment
  • States represent meaningful operational modes
  • Each state may have associated outputs or behaviors
  • Number of states is finite and predetermined

Examples:

  • Vending machine states: Idle, Waiting for Selection, Dispensing Item, Out of Service
  • Network connection states: Disconnected, Connecting, Connected, Error
  • Game character states: Idle, Walking, Running, Jumping, Attacking

Transitions

Definition: Rules governing movement from one state to another based on input conditions.

Key Properties:

  • Triggered by specific inputs or events
  • Instantaneous (no intermediate states)
  • May include guard conditions
  • Can trigger actions during execution

Transition Notation:

Current_State + Input β†’ Next_State [/ Action]

Example:

Idle + "Insert Coin" β†’ Waiting_for_Selection / "Display Menu"

Inputs and Outputs

ComponentDescriptionExamples
InputsExternal signals triggering transitionsButton presses, sensor readings, timer events, network packets
OutputsActions or signals produced by FSMDisplay updates, motor controls, network responses, status indicators

Output Types:

  • Mealy Machine: Outputs depend on current state AND input
  • Moore Machine: Outputs depend ONLY on current state

State Diagrams

State diagrams provide visual representation of FSM structure and behavior.

Visual Elements:

  • Circles/Nodes: Represent states
  • Arrows/Edges: Represent transitions
  • Labels: Show triggering inputs and outputs
  • Initial State: Arrow from nowhere pointing to starting state
  • Final States: Double circles (in accepting automata)

Example State Diagram Elements:

[State A] --input/output--> [State B]
    |                           |
    +--input/output-------------+

Types of Finite State Machines

1. Deterministic Finite State Machine (DFSM/DFA)

Definition: FSM where each state/input combination leads to exactly one next stateβ€”no ambiguity exists.

Characteristics:

  • Predictable behavior guaranteed
  • Single transition per state/input pair
  • Easier to implement and debug
  • Lower computational complexity

Applications:

  • Digital circuit design
  • Lexical analyzers in compilers
  • Protocol implementations
  • Password validation systems

Example - Binary String Validator:

States: {q0, q1}
Input alphabet: {0, 1}
Transitions:
  q0 + 0 β†’ q0
  q0 + 1 β†’ q1
  q1 + 0 β†’ q0
  q1 + 1 β†’ q1
Accept: q0 (strings with even number of 1s)

2. Non-Deterministic Finite State Machine (NDFSM/NFA)

Definition: FSM allowing multiple possible next states for the same state/input combination.

Key Features:

  • Multiple transition options per state/input
  • Epsilon (Ξ΅) transitions possible (state changes without input)
  • Useful for pattern matching
  • Can be converted to equivalent DFA

Advantages:

  • More compact representation
  • Easier initial design for complex patterns
  • Natural for certain problem types

Applications:

  • Regular expression engines
  • Pattern matching algorithms
  • Parallel state exploration
  • Ambiguous language recognition

3. Mealy Machine

Output Generation: Based on current state AND input.

Characteristics:

AspectDetails
Response TimeImmediate (outputs change with inputs)
State CountGenerally fewer states needed
Output StabilityLess stable (changes during transitions)
HardwareMore combinational logic required

Example - Turnstile Controller:

State: Locked
Input: Coin β†’ Output: Unlock β†’ Next State: Unlocked

State: Unlocked  
Input: Push β†’ Output: Lock β†’ Next State: Locked

Use Cases:

  • Systems requiring immediate responses
  • Communication protocols
  • Control systems with feedback
  • Event-driven applications

4. Moore Machine

Output Generation: Based ONLY on current state.

Characteristics:

AspectDetails
Response TimeOne cycle delay (outputs change on state transitions)
State CountGenerally more states needed
Output StabilityHighly stable (constant within states)
HardwareMore sequential logic (flip-flops)

Example - Traffic Light Controller:

State: Red β†’ Output: STOP (constant)
State: Yellow β†’ Output: CAUTION (constant)
State: Green β†’ Output: GO (constant)

Use Cases:

  • Sequential systems
  • Safety-critical applications
  • Timing-sensitive circuits
  • Systems prioritizing output stability

Mealy vs. Moore Comparison

FeatureMealy MachineMoore Machine
Output depends onState + InputState only
Response timeImmediateNext clock cycle
Number of statesFewerMore (typically)
Output timingAsynchronousSynchronous
Glitch susceptibilityHigherLower
Design complexityLogic complexityMore states
Best forFast responseStable outputs

How FSMs Work: Step-by-Step Process

FSM Construction Workflow

1. State Identification

  • List all distinct operational modes
  • Define meaningful state names
  • Identify initial and final states (if applicable)
  • Ensure states are mutually exclusive

2. Input Definition

  • Enumerate all possible inputs/events
  • Define input alphabet or event types
  • Consider edge cases and invalid inputs
  • Document input format and ranges

3. Transition Mapping

For each state:
  For each possible input:
    Define next_state
    Define action (if any)
    Add guard conditions (if needed)

4. State Table Creation

Current StateInputNext StateOutput/Action
State_AInput_1State_BAction_1
State_AInput_2State_AAction_2
State_BInput_1State_CAction_3

5. Implementation

  • Choose representation (table, switch-case, state pattern)
  • Initialize to starting state
  • Implement transition logic
  • Add output generation
  • Handle edge cases and errors

6. Execution Cycle

Loop:
  1. Wait for input
  2. Look up transition: current_state + input
  3. Execute transition action (if any)
  4. Update current_state to next_state
  5. Generate output (Moore: state-based, Mealy: state+input)
  6. Repeat

Implementation Examples

Example 1: Traffic Light Controller (Python)

States: Green, Yellow, Red
Trigger: Timer expiration

class TrafficLight:
    def __init__(self):
        self.state = 'Green'
        self.state_durations = {
            'Green': 30,
            'Yellow': 5,
            'Red': 25
        }
    
    def transition_table(self):
        return {
            'Green': 'Yellow',
            'Yellow': 'Red',
            'Red': 'Green'
        }
    
    def on_timer(self):
        transitions = self.transition_table()
        self.state = transitions[self.state]
        print(f'Light: {self.state}')
        return self.state_durations[self.state]

# Usage
light = TrafficLight()
for _ in range(6):
    duration = light.on_timer()
    print(f'Duration: {duration} seconds\n')

Example 2: String Parser (JavaScript)

Task: Validate strings ending with β€œ01”

class StringParser {
  constructor() {
    this.state = 'start';
  }
  
  transition(input) {
    const table = {
      'start': {'0': 'got_0', '1': 'start'},
      'got_0': {'0': 'got_0', '1': 'got_01'},
      'got_01': {'0': 'got_0', '1': 'start'}
    };
    
    if (table[this.state] && table[this.state][input]) {
      this.state = table[this.state][input];
      return true;
    }
    return false;
  }
  
  isValid() {
    return this.state === 'got_01';
  }
  
  reset() {
    this.state = 'start';
  }
}

// Test
const parser = new StringParser();
'10101'.split('').forEach(bit => parser.transition(bit));
console.log(parser.isValid()); // true

Example 3: Game Character FSM (C++)

enum State {
    STATE_STANDING,
    STATE_JUMPING,
    STATE_DUCKING,
    STATE_DIVING
};

enum Input {
    PRESS_B,
    PRESS_DOWN,
    RELEASE_DOWN
};

class Character {
private:
    State state_;
    
public:
    Character() : state_(STATE_STANDING) {}
    
    void handleInput(Input input) {
        switch (state_) {
            case STATE_STANDING:
                if (input == PRESS_B) {
                    state_ = STATE_JUMPING;
                    yVelocity_ = JUMP_VELOCITY;
                } else if (input == PRESS_DOWN) {
                    state_ = STATE_DUCKING;
                }
                break;
                
            case STATE_JUMPING:
                if (input == PRESS_DOWN) {
                    state_ = STATE_DIVING;
                    yVelocity_ *= 2;
                }
                break;
                
            case STATE_DUCKING:
                if (input == RELEASE_DOWN) {
                    state_ = STATE_STANDING;
                }
                break;
                
            case STATE_DIVING:
                // Can only transition on landing
                break;
        }
    }
    
    void update() {
        switch (state_) {
            case STATE_JUMPING:
            case STATE_DIVING:
                yVelocity_ += GRAVITY;
                yPosition_ += yVelocity_;
                if (yPosition_ <= 0) {
                    state_ = STATE_STANDING;
                    yPosition_ = 0;
                }
                break;
        }
    }
};

Real-World Applications

Software Engineering

UI Event Handling

  • Widget states: Idle, Hovered, Focused, Pressed, Dragging
  • Transitions based on mouse/touch events
  • Output: Visual feedback, callbacks

Network Protocols

  • TCP connection states: CLOSED, LISTEN, SYN_SENT, ESTABLISHED, FIN_WAIT
  • Transitions on packet reception
  • Ensures reliable communication

Compiler Lexical Analysis

  • Token recognition through state traversal
  • Each character input triggers transitions
  • Accept states indicate valid tokens

Hardware and Digital Systems

Application Areas:

DomainFSM Usage
Digital CircuitsCounters, timers, sequence detectors, control units
Embedded SystemsDevice controllers, power management, mode switching
FPGA/ASIC DesignProtocol controllers, data path control, synchronization
MicrocontrollersInterrupt handling, peripheral management, state monitoring

Example - Elevator Controller:

States: Idle, Moving_Up, Moving_Down, Door_Open
Inputs: Call_Button, Floor_Sensor, Door_Sensor, Timer
Outputs: Motor_Control, Door_Control, Display

AI, Chatbots, and Automation

Conversational AI States:

  • Greeting β†’ Information Gathering β†’ Processing β†’ Response β†’ Follow-up β†’ Closing
  • Transitions based on user inputs and intent recognition
  • Context preservation across states

Smart Home Automation:

Security System FSM:
States: Disarmed, Armed_Stay, Armed_Away, Alarm_Triggered
Inputs: User_Command, Sensor_Events, Timer
Outputs: Status_Display, Alarm_Sound, Notifications

Process Automation:

  • Workflow states representing process stages
  • Transitions on task completion or approval
  • Integration with business systems

Game Development

Character AI Behaviors:

StateTriggersActions
IdleNo player detectedPatrol waypoints
AlertPlayer spottedFace player, play alert sound
ChasePlayer in rangeMove toward player
AttackIn attack rangeExecute attack animation
RetreatHealth lowMove away, seek cover

Game Flow Management:

Menu β†’ Loading β†’ Playing ⇄ Paused β†’ Game_Over β†’ Menu

Advanced FSM Concepts

Hierarchical State Machines (HSM)

Concept: States contain nested sub-FSMs, enabling complex behavior composition.

Benefits:

  • Reduced state explosion
  • Better organization of complex systems
  • Reusable sub-behaviors
  • Clearer logical structure

Example Structure:

[Combat_Mode]
  β”œβ”€ [Attacking]
  β”‚    β”œβ”€ Melee_Attack
  β”‚    └─ Ranged_Attack
  └─ [Defending]
       β”œβ”€ Block
       └─ Dodge

Parallel State Machines

Concept: Multiple independent FSMs running simultaneously.

Use Cases:

  • Separate concerns (e.g., movement FSM + animation FSM)
  • Independent subsystem control
  • Concurrent behavior modeling

Example - Game Character:

Movement_FSM: Standing, Walking, Running, Jumping
Animation_FSM: Idle_Anim, Walk_Anim, Run_Anim, Jump_Anim
Combat_FSM: Unarmed, Armed, Attacking, Reloading

State Explosion Problem

Challenge: State count grows exponentially with system complexity.

Mitigation Strategies:

StrategyDescription
Hierarchical FSMGroup related states into super-states
State VariablesUse variables to capture dimensions independently
Parallel FSMsSeparate orthogonal concerns
State MinimizationMerge equivalent states
Guard ConditionsUse conditionals instead of separate states

State Pattern (OOP)

Concept: Encapsulate state-specific behavior in separate classes.

Structure:

class State:
    def handle(self, context): pass

class ConcreteStateA(State):
    def handle(self, context):
        # State A behavior
        context.state = ConcreteStateB()

class Context:
    def __init__(self):
        self.state = ConcreteStateA()
    
    def request(self):
        self.state.handle(self)

Benefits:

  • Open/closed principle compliance
  • Easy to add new states
  • Clear separation of concerns
  • Eliminates complex conditionals

Advantages and Limitations

Advantages

BenefitDescription
ClarityVisual and conceptual clarity of system behavior
PredictabilityDeterministic behavior with defined transitions
MaintainabilityEasy to modify and extend
TestabilityClear test cases for each state/transition
DocumentationState diagrams serve as living documentation
EfficiencyMinimal computational overhead
VerificationFormal methods applicable for correctness proofs

Limitations

LimitationImpactMitigation
State ExplosionToo many states become unmanageableUse hierarchical or parallel FSMs
Limited MemoryNo memory beyond current stateAdd state variables or use pushdown automata
ExpressivenessCan only model regular languagesUse more powerful models (Turing machines) for complex grammars
ScalabilityLarge systems become complexDecompose into smaller FSMs

Not Suitable For:

  • Problems requiring unbounded memory (e.g., matching nested parentheses)
  • Systems with continuous state spaces
  • Highly adaptive or learning systems
  • Problems outside regular language class

Best Practices

Design Guidelines

State Design:

  • Keep states meaningful and distinct
  • Minimize state count while maintaining clarity
  • Name states descriptively (verb-noun or adjective-noun)
  • Ensure mutual exclusivity

Transition Design:

  • Make transitions explicit and well-defined
  • Handle all inputs for all states (or define error states)
  • Avoid circular dependencies without progress
  • Document guard conditions clearly

Implementation:

  • Choose appropriate representation (table, switch, pattern)
  • Validate inputs before processing
  • Log state transitions for debugging
  • Implement timeout mechanisms where needed

Testing Strategies

Coverage Types:

Test TypeTarget
State CoverageExercise every state at least once
Transition CoverageTest every transition
Path CoverageTest common state sequences
Boundary TestingTest edge cases and limits
Error HandlingInvalid inputs and unexpected conditions

Key Terminology

  • Finite State Machine (FSM): Computational model with finite states and defined transitions
  • State: Distinct configuration or mode of operation
  • Transition: Movement from one state to another based on input
  • Input Alphabet: Set of all possible inputs
  • Output: Actions or signals produced by FSM
  • Deterministic FSM: Each state/input pair has exactly one next state
  • Non-Deterministic FSM: State/input pair may have multiple next states
  • Mealy Machine: Output depends on state and input
  • Moore Machine: Output depends only on state
  • State Diagram: Graphical representation of FSM
  • Transition Table: Tabular representation of all transitions
  • Accept State: State indicating valid input sequence (in automata)

References

Related Terms

Γ—
Contact Us Contact