Exploring how systems evolve from hardware to integration.
Deploying neural networks and intelligent decision loops on raw silicon targets.
How to design predictable firmware states without operating system schedulers.
Our previous explorations built a sequential superloop and taught it to coordinate tasks at precise intervals using hardware timers. The machine now has heartbeat and timing structure. But a critical question remains: even if the system knows exactly when to run a task, how does it decide what behaviour is appropriate at this exact millisecond?
Consider a motor-driven industrial system. It receives a single input: a Start button press. If the system is idle, pressing Start should engage the power relays and initiate a startup sequence. If the motor is already running, pressing Start should be ignored. If the system is in a fault state due to an overcurrent trigger, pressing Start must be rejected for safety.
The physical input is identical in all three cases. Yet, the required software reaction is entirely different. This is because input alone does not determine behaviour. Behaviour is a function of both the current input and the historical context of the system. We call this context the system's State.
In poorly structured firmware, state is often stored in scattered boolean flags: bool is_running = false;, bool has_fault = false;, bool is_starting = false;. As features grow, these flags multiply. Contradictory states accidentally become possible: what happens if both is_running and has_fault are true? The code enters an undefined territory.
To avoid this complexity, we define mutually exclusive modes of operation using an explicit enumeration:
By declaring a single current_state variable, we guarantee that the firmware can occupy exactly one state at any given moment. This is the foundation of a Finite State Machine.
The most common bare-metal state machine pattern utilizes a switch statement inside a periodic superloop task:
This switch-case structure maps our states, events, and transitions. It organizes code into modular, isolated blocks, preventing feature additions from degrading into a tangle of conditional statements.
A state transition is the act of switching from one state to another. In our motor example, transitions are conditional:
By validating transitions only within specific states, we ensure that out-of-order events (such as pressing Start while the machine is already running or faulted) are ignored, maintaining safety and operational constraints.
Transitioning to a state often requires one-time configurations. For example, entering STATE_STARTING requires enabling a motor relay, clearing a fault log, and setting a boot timer. If we place this logic inside the state handler:
These routines execute repeatedly on every iteration of the superloop. This wastes execution cycles and resets timers continuously, preventing the system from progressing. We must divide state actions into distinct phases:
1. On Entry: Runs exactly once when entering the state. 2. While Active (Run): Runs repeatedly while the state remains active. 3. On Exit: Runs exactly once when leaving the state.
In modular systems, transitions are routed through a dedicated state-setter function that enforces this lifecycle:
Let's connect this state model with the timing engine we built in our previous exploration. Suppose our startup process must wait in STATE_STARTING for exactly 500 milliseconds before transitioning to STATE_RUNNING. The naive approach uses blocking delay:
This delay freezes the superloop. The CPU cannot check sensors, handle communications, or evaluate safety limits for half a second, exposing the machine to catastrophic failure modes if a fault occurs during boot.
Instead of blocking, we integrate state with our non-blocking tick counter: On entering STATE_STARTING, we record the start timestamp: startup_begin_time = system_ticks;. Then, inside the active state checks, we evaluate the duration:
By checking elapsed time instead of waiting passively, the processor is released. The loop continues to run, keeping communication layers flowing and safety interrupts fully armed while the startup period progresses. The machine doesn't wait; it remembers.
We can now examine how the entire bare-metal architecture comes together inside our main application loop:
State transitions can be driven by a variety of asynchronous event sources: - Hardware Input Events: Button presses, optical sensor triggers, limit switch closures. - Timer Expired Events: Software timeout completions (like our non-blocking 500 ms wait). - Sensor Thresholds: Temperature crossing safety ranges. - Communication Messages: Host system packet arrivals. - Interrupt Signals: Critical peripheral hardware updates.
In a clean cooperative architecture, background interrupts capture and queue these events, leaving the foreground logic to evaluate and execute the state transitions at a safe, unified execution level. This limits context-switch issues and race conditions.
State machines are a powerful structuring tool, but they have a scaling bottleneck: state explosion. A basic application starts with 4 states. As features are added, you introduce new states: STOPPING, CALIBRATING, DIAGNOSTIC, UPDATE_FW, LOW_POWER. The number of states grows, and the paths between them multiply exponentially.
If transition paths are modified from multiple locations in the file without clear boundaries, states can trigger unexpectedly, causing hidden bugs. Designing state machines requires caution: keep state counts bounded, keep state modification unified, and enforce strict ownership of state-variable updates.
A state machine is a conceptual model used to organize code, not a representation of the entire system. Real-world systems also contain continuous physical processes, asynchronous hardware registers, packet streams, and interrupt lines. Trying to model every single variable and condition as a state will make the code unmanageable. State should be reserved for representing the system's primary operating modes.
We have reached the end of our foundational path. Our bare-metal machine now possesses a complete execution architecture, built step-by-step across four key stages:
1. Before main(): How silicon boots, configures vectors, migrates memory segments, and constructs the C environment. 2. The Infinite Loop That Runs a Machine: How the core commits to perpetual execution, performing background and foreground cycles. 3. Teaching Time to an Infinite Loop: How independent counters and timer interrupts segment execution, scheduling tasks periodically. 4. When Behaviour Becomes State: How explicit enums and transitions organize behaviors, ensuring the machine reacts safely to inputs.
This simple timed superloop and state machine architecture can support highly sophisticated products—from medical devices to aerospace sensor nodes. It operates directly on the silicon with zero kernel overhead, minimal memory foot print, and complete predictability.
But as system complexity continues to scale, this cooperative model reaches a boundary. What happens when multiple tasks must block for external events, or task execution times collide? When sequential cooperation is no longer enough, a new way of organizing execution is waiting.
PrajnaEdge is an interactive engineering platform where complex concepts become experiences—through visual explorations, simulations, and practical understanding.
Engineering is often taught as a collection of isolated concepts.
A processor here.
A protocol there.
An operating system somewhere else.
But real systems are built by connecting these layers.
PrajnaEdge exists to make those connections visible.
Each exploration starts with a question, builds an intuition, and gradually reveals the system underneath through visualizations, simulations, practical scenarios, and connections between concepts.
PrajnaEdge is designed around exploration rather than passive reading.
Concepts are introduced progressively, visualized when they benefit from seeing them, and brought to life through interactive EdgeCases and simulations where appropriate.
The goal is not simply to explain what a system does, but to help the learner understand why it works the way it does.
I am the engineer behind the design, development, and content of PrajnaEdge. I build low-level systems where code directly controls hardware, bridging the gap between register-level silicon behavior and intelligent edge decision loops.
I am an Embedded Firmware Engineer focused on developing software for resource-constrained systems. My experience spans bare-metal firmware, device drivers, microcontroller peripherals, and communication protocols, working across the boundary between hardware and software.
My work has involved microcontroller-based systems, real-time behaviour, hardware interfaces, and communication technologies such as CAN, CAN FD, UART, SPI, and I²C. I am particularly interested in understanding systems from the lowest level upward—from registers and peripherals to intelligent edge systems.
Engineering is not just about writing code; it is about managing constraints, timings, and physical hardware characteristics. True mastery of complex systems comes from understanding the interactions across different layers of the stack.
This conviction is why I built PrajnaEdge—to bridge the gap between conceptual theory and direct, register-level physical reality.
Software that runs directly on hardware without an operating system.
"Every embedded application begins long before main()."
An Operating System manages hardware and software resources so complex applications can work efficiently.
"When one loop is no longer enough to carry the burden."
PrajnaEdge is an independent education platform built to make knowledge freely accessible.
If you find PrajnaEdge useful, you can support its continued development.
Your support helps fund the time, tools, infrastructure, and experimentation that go into building and maintaining PrajnaEdge.
Product Terms & Licensing
PrajnaEdge is an interactive learning platform designed for systems engineers, developers, and technology enthusiasts. The educational materials, simulation blocks, and visual code tracers are provided for instruction and concept validation. We make no warranty regarding their completeness or applicability to real-world industrial systems.
The software, interactive widgets, diagrams, illustrations, custom SVG architectures, and textual documentation on this site are copyright © 2026 PrajnaEdge. All rights reserved. Reproduction, modifications, or scraping of this content without prior written permission is strictly prohibited.
PrajnaEdge is committed to learning privacy. We do not sell user data. Analytical event tracking is used solely to study click telemetry and help improve visual guides.