Stateflow Tutorial: How Charts Execute, With a Turn-Signal Example
What Stateflow is, how a chart executes each time step, entry/during/exit actions, transition label syntax, after(), and a simulated turn-signal chart.
Stateflow is MathWorks' graphical language for control logic: you draw states and the transitions between them (plus flow charts, state transition tables and truth tables), and the chart runs as a block inside a Simulink model. Engineers use it for mode logic such as gear selection, battery charging phases, fault handling and turn signals, then generate C code from the same chart for an ECU. This guide explains how a Stateflow chart actually executes, the label syntax you type, and two worked examples whose behaviour we simulated step by step.
In short
- Stateflow gives you four notations: state transition diagrams, flow charts, state transition tables and truth tables (MathWorks Stateflow product page, read 17 Nov 2026).
- A transition label has four optional parts:
trigger[condition]{condition_action}/{transition_action}(MathWorks documentation, read 17 Nov 2026).- On every time step an active state checks its outer transitions first; its
duringactions run only if none of them is valid (MathWorks, "Execution of a Stateflow Chart", read 17 Nov 2026).- By default a chart takes only one transition per simulation step; super step semantics lets it take all valid transitions in one step (MathWorks, "Super Step Semantics", read 17 Nov 2026).
- Our flasher chart below (0.4 s on, 0.4 s off) flashes 75 times a minute, and a single-threshold version of the old "Max/Min" example switched 53 times in 10 s on a noisy signal, against 4 times with a 9/11 hysteresis band (our simulation, 17 Nov 2026).
What is control logic, and why model it as a state machine?
Control logic is the part of a program that decides what the system should be doing right now: which mode it is in, when to switch modes, and what to do on a fault. It reacts to commands (a driver moves a lever) and to conditions it monitors itself (a timer runs out, a voltage crosses a limit). A state machine is the natural way to write it down.
Typical jobs for control logic are supervising switches between operating modes, sequencing tasks (pre-charge, then close the main contactor, then enable the inverter), and fault detection, isolation and recovery. As the logic grows you need hierarchy (states inside states), flow charts for pure decision logic, and parallel states for parts of the system that run side by side. Stateflow supports all three.
What is a finite state machine?
A finite state machine (FSM) is a model with a fixed list of states, of which exactly one is active at a time, and rules (transitions) that move it from one state to another when a condition becomes true. The active state remembers the relevant past, so the same input can produce a different output depending on the state.
A car's automatic transmission selector is a good example: its states are Park, Reverse, Neutral, Drive and Low, and moving the lever causes a transition from one state to another. A door controller is the smallest useful example: two states, Open and Closed, with "open command" and "close command" as the transitions between them.
Engineers used to describe FSMs with truth tables or hand-drawn state diagrams, then wrote the code by hand. Stateflow keeps the diagram as the source: you simulate it with the plant model in Simulink, test it, and generate code from it.
Mealy or Moore: which kind of chart do you get?
In a Mealy chart the output is a function of inputs and state, and is computed on transitions; in a Moore chart the output is a function only of state, and is computed in states. A new Stateflow chart is neither: the default is a "Classic" chart that mixes both styles with extra Stateflow semantics (MathWorks, read 17 Nov 2026). You choose Mealy or Moore in the chart's State Machine Type property when you need the stricter rules, for example for formal verification.
What can you draw in Stateflow?
Stateflow offers state transition diagrams, flow charts, state transition tables and truth tables. MathWorks lists supervisory control, task scheduling, fault management, communication protocols, user interfaces and hybrid systems as typical uses, and the same chart can be turned into C, C++, VHDL, Verilog or Structured Text for PLCs (Stateflow product page, read 17 Nov 2026).
- State transition diagram: states as rounded boxes, transitions as arrows. Use it for anything with modes.
- Flow chart: junctions and transitions only, no states. It runs from start to end in one step, like an if/else tree. Use it for decision logic that has no memory.
- State transition table: the same state machine written as rows (states) and columns (conditions and destinations). Some teams review tables more easily than drawings.
- Truth table: conditions, decisions and actions in a grid, for combinatorial logic. The Truth Table block uses MATLAB as its action language and needs a Stateflow licence (MathWorks Truth Table block reference, read 17 Nov 2026).
What are entry, during and exit actions in Stateflow?
State actions are statements written inside a state. entry (short form en) runs once when the state becomes active, during (du) runs on each time step while it stays active, exit (ex) runs once when it becomes inactive, and on runs when an event occurs while the state is active (MathWorks, "Define State Actions", read 17 Nov 2026).
You can attach the same statement to several stages, for example en, du: y = 2*u; to compute an output on entry and on every step after. A state label therefore looks like this:
Charging
en: contactor = 1; t0 = 0;
du: current = min(i_set, i_limit);
ex: contactor = 0;
How do you write a transition label in Stateflow?
A transition label follows the pattern trigger[condition]{condition_action}/{transition_action}, and every part is optional. The trigger is an event or message; the condition is a Boolean expression in square brackets; the condition action runs as soon as the condition is found true; the transition action runs only once the whole path to a destination state is valid (MathWorks, read 17 Nov 2026).
The difference between the two actions only shows up on multi-segment paths through junctions: a condition action on the first segment runs even if a later segment turns out to be invalid, while a transition action waits until the chart knows where it is going. In a condition, combine expressions with && and || and never write an assignment.
Every chart (and every state with exclusive substates) needs a default transition: an arrow with no source that marks which substate becomes active first. If a state has two or more exclusive substates, one default path must be unguarded, so the chart always has somewhere to go.
How does a Stateflow chart execute on each time step?
When the chart wakes up for the first time it follows its default transitions and runs the entry actions of the states it enters. On each later step, an active state first checks its outer transitions; if none is valid it runs its during actions, then checks inner transitions, then hands over to its active substate, which repeats the same steps (MathWorks, "Execution of a Stateflow Chart", read 17 Nov 2026).
When a transition is taken, the source state (and its active substates) exits first, then the transition action runs, then the destination is entered with its entry actions and its own default transition. Three rules catch most beginners:
- One transition per step. By default the chart takes a single transition each time it wakes up. If a chain A to B to C is all valid at once, the chart still needs two steps to reach C unless you enable super step semantics (MathWorks, read 17 Nov 2026).
- Order matters. Outgoing transitions are numbered in the order you created them, and the chart takes the first valid one. Change the number from the transition's right-click menu (Execution Order) when two conditions can be true together.
- The parent wins. Because a state checks its outer transitions before its children run, a transition leaving a superstate (such as a fault exit) pre-empts anything happening inside it.
Exclusive (OR) or parallel (AND) states?
Exclusive (OR) substates are alternatives: at one level of hierarchy only one of them can be active, and they are drawn with solid borders. Parallel (AND) substates are all active together, drawn with dashed borders and a number, but they still execute one after another in that order on each step (MathWorks documentation on parallel decomposition, read 17 Nov 2026).
The order of parallel states matters when one writes a variable another reads: put the writer first, or the reader sees last step's value. A common layout is a top level with two parallel states, for example "Mode" and "FaultMonitor", each holding its own exclusive states.
What does a history junction do?
A history junction (an H in a circle) makes a superstate return to the substate that was last active, instead of following its default transition, when the chart re-enters it (MathWorks, "Implement State Memory", read 17 Nov 2026). Use it for "pause and resume" logic, such as a wiper that remembers its speed after the ignition comes back. It has no meaning inside parallel states, because all of them are active anyway.
How do you add time to a Stateflow chart?
Use temporal logic operators. after(n,sec) becomes true once n seconds have passed since the state became active, before(n,sec) is its opposite, duration(C) gives how long condition C has been true, and elapsed(sec) (or et) gives time in the current state. Units are sec, msec, usec, or tick for chart wake-ups (MathWorks, read 17 Nov 2026).
Two practical limits from the same page: temporal operators belong in on actions and on transitions that leave a state, not on default transitions, and with a discrete sample time an action can only happen on a sample hit. With a 0.1 s step, a 5.33 ms delay takes effect at 0.1 s, so pick the chart's sample time to suit the fastest timer you need.
Worked example: a turn-signal and hazard flasher
This is the kind of body-electronics logic a fresher MBD engineer gets as a first task. The requirements we used:
- Lever left or right: that lamp flashes, 0.4 s on and 0.4 s off, while the lever is held.
- A short tap (lever released within 0.5 s): exactly three flashes, the "lane change" behaviour many cars offer.
- Hazard switch on: both lamps flash together, and hazard overrides the lever.
The timings are our design choices for the example. A production design takes the flash-rate limits from the lighting regulation that applies to the vehicle.
How the chart is built
The chart has inputs lever (-1 left, 0 centre, +1 right) and hazard (0 or 1), outputs L and R, and local data n, dir and held. The labels, exactly as you would type them:
Off en: L = 0; R = 0;
Turn en: n = 0; dir = lever; held = false;
on after(0.5,sec): held = held || lever ~= 0;
LampOn en: L = dir < 0; R = dir > 0;
ex: n = n + 1;
LampOff en: L = 0; R = 0;
Hazard (LampOn sets L = 1; R = 1;)
Off -> Hazard 1: [hazard == 1]
Off -> Turn 2: [lever ~= 0]
Turn -> Hazard 1: [hazard == 1]
Turn -> Off 2: [lever == 0 && (held || n >= 3)]
Turn -> Turn 3: [lever ~= 0 && lever ~= dir]
LampOn -> LampOff after(0.4,sec)
LampOff -> LampOn after(0.4,sec)
Hazard -> Turn 1: [hazard == 0 && lever ~= 0]
Hazard -> Off 2: [hazard == 0]
Three design points are worth copying. First, hazard gets execution order 1 everywhere, so it always wins. Second, the flash counter increments in LampOn's exit action, so n counts completed flashes, not started ones; counting on entry would cut the third flash short. Third, held is set by an on after(0.5,sec) action rather than by comparing elapsed on the exit transition. Our first version used elapsed(sec) >= 0.5 there, and the simulation showed the bug at once: a tap stopped after one flash, because time in the Turn state kept running after the lever came back.
What does the simulated trace show?
We have no MATLAB licence on the machine that wrote this, so we re-implemented the chart's semantics in Python at a fixed 0.01 s step: default transition on the first step, parent outer transitions before children, one transition per step, exit then entry. The script asserts every timing quoted here.
- Lever held 0.5 to 3.0 s: the left lamp comes on at 0.5, 1.3, 2.1 and 2.9 s and goes out at 3.0 s, the step the lever returns. That is a period of 0.8 s, so 75 flashes a minute.
- Right tap of 0.2 s at 3.6 s: exactly three full 0.4 s flashes (3.6, 4.4, 5.2 s). The third ends at 5.6 s and the chart is back in Off at 5.61 s, one step later, because the parent's exit check ran before the child's flash ended on that step.
- Hazard 6.0 to 8.0 s: both lamps flash in phase at 6.0, 6.8 and 7.6 s and go dark at 8.0 s.
That one-step delay at 5.61 s is the "one transition per step" rule in action, and it is a good thing to know before an interviewer asks about it.
Why does the classic "Max/Min" example need hysteresis?
A popular first Stateflow exercise has two states: Max outputs 20 when the input is above 10, and Min outputs -30 when it is below 10. At exactly 10 neither condition is true, so the chart stays in whatever state it was in. On a real, noisy signal near 10 it also switches back and forth on almost every step.
Fix it with hysteresis: leave Min only when the input rises above 11, and leave Max only when it falls below 9. We fed both versions the same signal, a 0.2 Hz sine around 10 with amplitude 3 plus random noise of up to ±0.8, for 10 s at a 0.01 s step.
The single-threshold chart switched 53 times; the hysteresis chart switched 4 times, once per real crossing, because the noise (1.6 peak to peak) is smaller than the 2-unit band. In a real controller each of those extra switches might be a relay click or a contactor cycle. Choose the band from the measured noise on the signal, not by guesswork, and test the boundary values (9, 10, 11) explicitly.
Min en: value = -30;
Max en: value = 20;
Min -> Max [u > 11]
Max -> Min [u < 9]
How do you create your first chart in Simulink?
Open a new Simulink model, add a Chart block from the Stateflow library and double-click it to open the Stateflow Editor. The editor has the object palette on the left (states, junctions, default transitions), the canvas in the middle, and the Symbols pane, where you declare each variable as input, output or local data.
- Click the State tool and place a state; type its name and actions.
- Draw a transition by dragging from one state's edge to another's; double-click it to type the label.
- Add the default transition into the first state.
- In the Symbols pane, set every undefined symbol's scope (Input, Output or Local) and type.
- Back in Simulink, connect the chart's ports, for example a Repeating Sequence or Signal Editor block as input and a Scope on the output, set a fixed-step solver, and run.
Use the chart's animation (active states highlight as the model runs) to see the logic step by step; it is the quickest way to catch a wrong execution order.
How does Stateflow compare with PLC programming languages?
PLCs are programmed in the languages of IEC 61131-3: Ladder Diagram, Function Block Diagram, Structured Text and Sequential Function Chart, plus the older Instruction List, which the third edition (2013) marked as deprecated. The fourth edition was published on 22 May 2025 and lists added, removed and deprecated features in its Annex B (IEC webstore, read 17 Nov 2026).
Sequential Function Chart is the closest relative of a Stateflow chart: steps and transitions instead of states and transitions. Stateflow can also generate Structured Text, so the same logic can be simulated in Simulink and then deployed to a PLC (Stateflow product page, read 17 Nov 2026).
How does a Stateflow chart become ECU code?
Charts are turned into C or C++ by MathWorks' code generators: Simulink Coder generates C and C++, and Embedded Coder, which builds on Simulink Coder, is the variant teams use for production ECU code. HDL Coder produces VHDL or Verilog and PLC Coder produces Structured Text (MathWorks Truth Table block reference and Stateflow product page, read 17 Nov 2026). Production teams pair this with modelling guidelines and model-level testing, then run the generated code through the usual software verification.
That workflow, requirements to model to tests to code, is what model-based development (MBD) means in automotive jobs. If you want to practise it on EV and ADAS problems, Skill-Lync's Introduction to Model-Based Development using MATLAB and Simulink and Software Verification and Validation for Model-Based Development cover the modelling and testing halves, and the MATLAB and Simulink Basics course is the place to start if Simulink itself is new. Two related walk-throughs on our blog: a traffic light simulated with Stateflow and control logic with Stateflow in Simscape.
FAQ: questions engineers also ask
Is Stateflow part of MATLAB or a separate product?
Stateflow is a separate MathWorks product that runs on MATLAB and Simulink, with its own licence. Simulink contains enough Stateflow code to open MathWorks' documentation examples, but opening other models that use Stateflow blocks needs a Stateflow licence (MathWorks, read 17 Nov 2026). Check your college's campus licence: many include it.
What is the difference between a condition action and a transition action?
A condition action, in curly braces after the condition, runs as soon as that condition is true, even if a later segment of the path fails. A transition action, after the slash, runs only when the whole path to a destination is valid, after the source state exits and before the destination's entry actions.
Why does my chart take two steps to reach a state?
Because by default a Stateflow chart takes only one transition per time step. If A to B and B to C are both valid at once, B is active for one step before C. Enable super step semantics in the chart properties if the logic really needs to settle within one step, and set a maximum iteration count to catch loops.
When should I use a flow chart instead of states?
Use a flow chart when the logic has no memory: a decision tree that computes an output from the current inputs and finishes in the same step. Use states when the answer depends on history, such as which mode the system is in or how long something has been true. Many charts combine both, with flow charts inside state actions.
Do automotive companies in India use Stateflow?
Yes, MBD roles in automotive software (body electronics, powertrain, BMS, ADAS) commonly list MATLAB, Simulink and Stateflow alongside AUTOSAR and testing tools. Our AUTOSAR interview questions post covers the software side those roles also test.
Sources and further reading
- Stateflow product page, MathWorks, read 17 Nov 2026.
- Define State Actions, MathWorks documentation, read 17 Nov 2026.
- Transition Between Operating Modes (label syntax, default transitions), MathWorks documentation, read 17 Nov 2026.
- Execution of a Stateflow Chart, MathWorks documentation, read 17 Nov 2026.
- Evaluate Transitions (condition vs transition actions, execution order), MathWorks documentation, read 17 Nov 2026.
- Super Step Semantics, MathWorks documentation, read 17 Nov 2026.
- Control Chart Execution by Using Temporal Logic, MathWorks documentation, read 17 Nov 2026.
- Overview of Mealy and Moore Machines, MathWorks documentation, read 17 Nov 2026.
- Implement State Memory (history junctions), MathWorks documentation, read 17 Nov 2026.
- What Do Semantics Mean for Stateflow Charts? and parallel decomposition, MathWorks documentation, read 17 Nov 2026.
- Truth Table block, MathWorks documentation, read 17 Nov 2026.
- IEC 61131-3:2025, Programmable controllers, Part 3: Programming languages, IEC, edition 4.0, 22 May 2025, read 17 Nov 2026; IEC 61131-3, Wikipedia (Instruction List deprecated in the 3rd edition), read 17 Nov 2026.
- Flasher and hysteresis simulations: Skill-Lync, Python re-implementation of the chart semantics, 17 Nov 2026 (script kept with this article's run notes).