
Master hierarchical state machines to tame complex embedded behavior with a tiny hsm microkernel, clean entry and exit guards, history for deterministic firmware and traceability from requirements to code.
Explore why ad hoc firmware leads to spaghetti code and hidden dependencies, and learn how hierarchical state machines address flat FSM limitations to improve debugging, onboarding, and robust firmware.
Adopt the hierarchical state machine, the state chart, to prevent state explosion and brittle code from duplicating debounce logic and message handlers across states and to centralize transitions.
Learn hierarchical state machines, using a superstate to group shared behavior and orthogonality to run mode and telemetry state machines in parallel, mapping cleanly to firmware.
Adopt a simplified, professional project layout for hierarchical state machines. Organize into root, app, bsp, and core folders with hsm, docs, and host-based unit tests, plus a main.c entry point.
Follow MISRA C guardrails for safety-critical firmware, enforcing a no heap policy and static memory. Use deterministic state machines with no recursion and strongly typed enums for state and event.
Download STM32CubeIDE from STMicroelectronics, accept the license, and log in or register to start the Windows installer download, setting up the next installation lesson.
Extract the downloaded package, run the installer for Cube IDE, accept the license, and choose a location while ensuring SD link drivers and jailing drivers are installed.
Download the STM32 reference manual, datasheet, and board user guides, and set up a workspace and project tree to access registers and develop bare metal firmware.
Set up a bare-metal STM32 project in Cube IDE, configure the workspace, and create an empty project to access peripheral registers via CMSIS headers.
Link chip headers into the project, enable gpio clock, set pa5 as output, and blink the led by toggling the pin; select STM32F4 target, build, and test.
Explore the anatomy of a statechart and the building blocks of hierarchical state machines, including state, event, actions, transitions, guards, and hierarchy, to design robust applications.
Learn how hierarchy elevates a finite state machine into a hierarchical state machine by bubbling events to the super state, enabling shared behavior and exit actions up, entry actions down.
Explore internal transitions, history states, and orthogonal regions within hierarchical state machines, and learn the critical run to completion principle to ensure deterministic, single-event processing.
Develop a modular set of bare-metal drivers for the floating point unit, uart, gpio, and timebase that enable reuse across gsm, gps, and bluetooth courses.
Develop a uart driver by analyzing stm32 documentation, enabling apb1 clocks for usart two, configuring alternate function gpio pins for rx/tx, and understanding usb connections on nucleo vs discovery boards.
Configure PA2 as uart TX with alternate function Af7, enable clocks, set baud rate and transfer direction, then enable the uart module to transmit data.
Enable gpio clock via rcc ahb1enr and configure gpioa pin2 to alternate function af7. Enable usart2 clock on apb1, set baud rate to 115200, and enable transmitter.
Implement uart write function to transmit data by waiting for the tx flag bit 7 to be set and writing to the usart data register; retarget printf to use it.
Test the uart driver by printing via uart2 to the computer at baud rate 115200 with real time or Teraterm. Log the debug output for verification.
Develop a system time base with the stm32 cortex-m4 systick timer to generate precise delays and measure elapsed time, configuring the systick control and status register.
Define symbolic names for registers and implement a systick init to generate a one-second tick by loading the timer, clearing the current value, selecting internal clock, and enabling interrupt.
Develop a system timebase by incrementing a tick with the systick interrupt, exposing a get_tick for atomic reads, and implementing a delay that waits for a tick count using get_tick.
Test the system time base by initializing it and applying a one-second delay, printing a message each cycle. Prepare modular drivers and a board support package for future lessons.
Develop a board support package for stm32f4, implementing gpio drivers for an led on pa5 and a push button on pc13, with bsp.c/h and init on/off/get state.
Develop a gpio based led driver in the bsp, enabling clock access to gpio a and gpio c, and drive pin five as output.
Enable the gpio clock and configure PC13 as an input to drive the push button, then read the active-low state with a bitwise end to detect press.
Test the board support package by initializing and turning on the LED, then verify the push button state via the get button state function in STM32 debugging.
Develop an adc driver and implement an init for adc one on the apb2 bus, configure gpio analog mode for channel one, and read a sensor.
Develop an adc driver by configuring gpio for analog mode, enabling clocks to both gpio and adc, and setting the conversion sequence and length before starting conversions and reading values.
Implement the PA1 ADC init to enable GPIO clock, set PA1 as analog, configure ADC1 on APB2, set up the conversion sequence for channel 1, and turn on the ADC.
Develop and test an adc driver read function by enabling continuous conversion, starting conversion, polling the end-of-conversion flag, and returning the 12-bit data from the 3.3V reference on pa1.
Develop a reusable hierarchical state machine framework in embedded C. Represent states as functions and events as structs with a signal, and define the state contract.
Explain the state handler signature as the contract for hierarchical state machines: a function pointer receives the state machine object and the current event and returns an HSM status.
Understand how the dispatcher orchestrates events in hierarchical state machines, bubbling up via ret super and performing transitions from a source state to common ancestor and down through entry actions.
Copy and rename the generic drivers workspace to hierarchical state machines, open STM32 CubeIDE, set copied path as the workspace, and launch to prepare for building your first HSM project.
Develop the first hsm project by implementing a gpio button toggle with a 20 ms debounce, auditable logging, and deterministic behavior while setting up the project structure and md files.
Organize a state machine project by creating folders (app, core, include, docs, tools) and a model with requirements and specs, plus a Python tool to capture UART traces as CSV.
Create a markdown requirements file that clearly communicates goals, hardware, constraints, acceptance, and deliverables for an embedded project, including PC13 button, PS5 LED, 20 ms debounce, and UART logging.
Implement the spec document for a gpio module, detailing interfaces, semantics, events, and state meanings, including button read active low, led control, and systick timebase.
Create a gpio acceptance file in the checklist to verify coding standards and MISRA/Autosar compliance. The checklist tracks state sequence logs, debounce timing, toggle behavior, and no dynamic memory allocation.
Develop the event dictionary and invariants for a hierarchical state machine, detailing button and systick events, debounce timing, and stable-press handling before led toggling.
Define a state catalog describing state ids, parent relations, entry and exit actions, and responsibilities for running, idle, debounce, and pressed states, including led toggle.
Explains building a state transition table for a hierarchical state machine, detailing source, event, guard, action, and destination states for ideal, debounce, and pressed, including edge and systick transitions.
Define the hsm.h header with include guards, typedefs for readability, create an event type with id and 32-bit payload, and outline the state handler signature for the microkernel.
Define the state handler signature for a hierarchical state machine, create the HSM struct with current state and transition target, and establish enums for return types and events.
Define an enum of state handler return codes—ret_handled, ret_trans, ret_super, and ret_ignored—to drive event entry/exit, event handling, and transitions in a hierarchical state machine.
Define the enum for the event, initialize evt init to one, and outline initialization, entering a state, and exiting state in a hierarchical state machine.
Explore declaring prebuilt constant framework events in the runtime for a hierarchical state machine, including entry, exit, and init events, and implementing the HSM init function in C.
Implement the hsm init function to wire the HSM to the root state, initialize with an init event, clear super and pending target, and defer entry/exit to the first dispatch.
Implement the HSM tran function to request transitions to a target state. Implement the HSM dispatch function to deliver events to the machine.
Implement the hsm dispatch function to deliver a single event to the machine and drive it to completion using run-to-completion principles and the return codes handled, trans, and super.
Invoke the current state handler with an event, check the return code for handled or ignored to end the dispatch cycle, and prepare for super or trans handling next.
Handle the RET_SUPER return code in a hierarchical state machine by climbing to the parent state when available, delegating to the parent if requested, and retrying the same event.
Handle the ret_trans return code by exiting the current state, updating to the target, and entering the new state to begin the init chain after snapshotting and clearing the target.
Chain the init event to reach leaf initial substate and guarantee the machine settles in concrete state after transitions, while inner loop handles ret_trans and continues until no more transitions.
Implement a model dump module that converts the HSM state chart transitions to CSV. Provide no-heap, fixed-stack CSV emission via a user-supplied emit callback.
Design the transition row type for CSV emission in a hierarchical state machine module, defining a typedef struct with source, event, guard, action, destination, and a defer flag.
Implement a static write row function to format a single transition row as a CSV, using snprintf and null-safe fields, with yes/no for defer, forming the model dump CSV.
Implement the model dump csv function for hierarchical state machines, with header creation, per-row emission via a synchronous emit callback, and using trans_t structures.
Validate input with a guard clause, emit a 256-byte CSV header (source, event, card, etc.), and iterate rows to emit each line for the model dump module.
You already interact with hierarchical state machines every day. Android’s own framework ships a hierarchical state machine used in core services like telephony and Wi-Fi. In automotive, statecharts power production control logic via tools such as Stateflow.
Aerospace programs have documented statechart-based development for safety-critical systems.
This course brings that same rigor to your firmware projects in embedded C.
You will replace fragile switch-case logic with a compact hierarchical design that maps requirements to states and events, produces deterministic logs and golden traces that reviewers can replay, and stands up in enterprise audits.
It is a practical, code-first path using direct registers, no HAL, no heap.
By the end, you will ship behavior you can prove, with artifacts that Fortune 500 teams expect: Transition Tables, Event Dictionaries, Invariants, acceptance checklists, and replayable traces from real hardware.
What this skill actually is
HSMs are a rigorous way to describe how a device behaves over time. They extend flat finite state machines with hierarchy, entry and exit actions, guards, internal transitions, history, and orthogonal regions.
In practice this means you express product behavior as states and events, then implement it as a HSM micro kernel plus a clean transition table. The result is code that is easy to reason about, easy to test, and easy to change when requirements evolve.
Why Top Company Teams Care
Traceability end to end. Requirements link to states, events, and actions. Actions link to logs and tests.
Determinism. Run to completion dispatch and timebase produce repeatable behavior and golden traces for QA and compliance.
Maintainability at scale. Superstates eliminate duplication and orthogonal regions prevent state explosion.
Audit readiness. MISRA C 2012 subset, no heap policy, versioned model artifacts, and numeric SWO or UART logs.
How this is different from mastering an RTOS or Design Patterns
RTOS mastery focuses on scheduling threads and sharing resources. Statecharts focus on modeling and controlling device behavior through events.
You can run statecharts with or without an RTOS. This course shows the RTOS free path first, which is ideal for many embedded products at top companies.
Design patterns are reusable, well-established solutions at the code level, such as Strategy or Observer, that help structure interactions and behaviors within components.
Statecharts are an architecture level method that defines the overall shape of behavior. Patterns can live inside actions, but statecharts tell you when and why those actions run.
AUTOSAR or a specific OS gives you a platform checklist. Statecharts give you a product behavior model that stays stable even if the platform changes. That is why large companies pair an OS with a state based design.
What makes this course unique
Pure Embedded C. Direct register programming.
Model artifacts live in the repo as text. State Catalog, Event Dictionary, Transition Table, Invariants, and Golden Traces.
A Hierarchical State Machine (HSM) micro kernel you fully understand. You will write it, test it, and extend it.
Enterprise rigor throughout. Coding standards, review checklists, deterministic logs, and acceptance criteria per module.
What you will learn
Express product behavior with the vocabulary of statecharts. Events, guards, entry and exit actions, internal transitions, hierarchy, history, and orthogonal regions.
Implement a compact HSM kernel in C that enforces run to completion and clean transition choreography.
Build an event driven MCU architecture. ISR posts events, queue feeds dispatcher, timers post timeouts, actions do work.
Achieve practical compliance. Apply a pragmatic MISRA C 2012 subset that fits an HSM based design.
Prove behavior. Generate golden traces, replay them in host tests, and tie them to requirements.
What you will build on hardware
A multi mode device on microcontrollers with hierarchical states.
Event queue and timer service with deferred events and bounded retries.
Robust update flow with CRC checks and recovery to Active.
Telemetry and command processing that run in parallel regions without an RTOS.
Deterministic logging over serial that decodes into human readable traces.
Outcomes you can take to work and interviews
You can convert a messy switch-case state machine into a clean hierarchical design that passes peer review.
You can explain, with code and logs, why a transition occurs, what resources are configured on ENTRY, and what is canceled on EXIT.
You can hand auditors a short set of text files plus golden traces that exactly describe device behavior.
You can ship MCU code that is predictable, testable, and easy to extend. That is what managers at large companies pay for.
Who this is for
Intermediate embedded engineers who can write drivers and want to master complex logic without an RTOS.
Team leads who need a maintainable architecture for multi year products.
Candidates preparing for interviews where you must explain system behavior, not only drivers.