Dieses Bild zeigt ein komplexes Stateflow-Modell mit mehreren hierarchischen Unterebenen.
Bild: Ein komplexes Stateflow-Modell mit mehreren hierarchischen Unterebenen

How To Bring Stateflow Under Control with Modeling Guidelines

Dieser Artikel ist derzeit nur auf Englisch verfügbar.

Stateflow is a powerful tool in model-based development, particularly in industries like automotive, where precise control of state machines and complex logic is essential. However, effectively using Stateflow requires overcoming recurring challenges, such as syntax issues and performance considerations.

In this article, we explore key insights from a survey conducted by MES and provide actionable tips to optimize your Stateflow models for improved performance, reliability, and maintainability.

Dieses Bild zeigt die Ergebnisse der Umfrage über die Verwendung von Stateflow in den Modellen der Teilnehmer.
Bild: Anteil von Stateflow in Ihren Modellen

How Do Industry Professionals Use Stateflow: Survey

Level of Stateflow Adoption in Model-Based Development


As part of our ongoing efforts to understand industry practices, we conducted a Stateflow-focused survey in 2022 in collaboration with 30 experts from companies including Go to Mercedes-Benz Group AG, Go to Bosch Group, Go to Continental AG, and others.


We started by asking whether they, as professionals working with model-based development, use Stateflow. As shown in the bar chart below, most users incorporate Stateflow in 20% to 50% of their models.

Diese Abbildung zeigt den Anteil der Teilnehmer an der Umfrage, die hauptsächlich C oder MATLAB als Aktionssprache verwenden.
Bild: Welche Aktionssprache verwenden die Teilnehmer?

Preferred Action Language for Stateflow

The second question we asked was which action language they used. The pie chart below highlights that most users prefer MATLAB over C language for action scripting, reflecting its simplicity and integration with the Simulink ecosystem.

Dieses Bild zeigt die Hindernisse, auf die die Teilnehmer bei der Nutzung von Stateflow am häufigsten stoßen.
Bild: Hindernisse für die Teilnehmer bei der Nutzung von Stateflow

Common Obstacles in Using Stateflow

Third, we asked participants about the challenges they face when using Stateflow. The most common obstacle was a lack of knowledge, with a notable number of users reporting no difficulties at all. Missing features were the least cited concern, suggesting that training and documentation improvements could help users overcome their hurdles.

Dieses Bild zeigt, ob die Teilnehmer in Stateflow arithmetische Berechnungen durchführen oder nicht.
Bild: Verwendung von arithmetischen Berechnungen durch die Teilnehmer in Stateflow

Use of Stateflow for Arithmetic Calculations

The fourth inquiry was regarding the use of Stateflow for arithmetic calculations. A majority of 56% responded affirmatively. This highlights the tool's versatility in handling complex calculations often needed in automotive systems.

Dieses Bild zeigt die Elemente und Muster, die die Teilnehmer am häufigsten verwenden.
Bild: Verwendung von Stateflow-Elementen und -Mustern

Most Commonly Used Stateflow Elements/Patterns

Finally, we inquired about the most frequently used Stateflow elements and patterns. The results indicated a relatively uniform distribution, with Statecharts and Condition Actions showing a slightly higher usage rate, while Boxes exhibited the lowest adoption. This suggests a preference among participants for structured, condition-based modeling, particularly for implementing decision logic within their systems.

Key Takeaways From the Survey

Our survey reaffirms that Stateflow is part of the toolset used by professionals in model-based development. However, the responses also reveal several challenges users face when using it.
Based on this feedback, the MES team identified common pain points and areas for improvement. In this article, we will explore these challenges in detail and provide best practices to enhance the efficiency and reliability of Stateflow modeling.

 

What Challenges Make Model-Based Development With Stateflow Difficult?

Model-based development with Stateflow offers powerful capabilities, but it also comes with challenges that can impact maintainability and efficiency. Key difficulties include:

  • Increasing complexity: As state transitions grow, managing them becomes more difficult.
  • Scalability issues: State machines can quickly expand, making models harder to read and maintain.
  • Syntax constraints: Strict syntax rules are necessary to ensure consistency and prevent errors.
  • Careful design required: A structured approach and disciplined use of Stateflow are essential to avoid unexpected behavior and improve model clarity.
Dies ist ein Beispiel für eine korrekte Syntax für eine Übergangsbezeichnung
Bild: Beispiel für eine korrekte Syntax für Übergangsbezeichnungen

10 Strategies to Master Stateflow

1. Ensure Proper Syntax for Transition Labels

Proper transition label syntax in Stateflow improves readability, maintainability, and predictability while ensuring accurate code generation in tools like TargetLink. A structured approach helps create clear, reliable, and easy-to-maintain models.

First, let's break down and explain the meaning of each part of a transition label:

  • Event: Specifies an event that causes the transition to be taken
  • Condition: Specifies a Boolean expression that, when true, validates a transition to be taken
  • Condition action: Executes as soon as the condition is evaluated as true
  • Transition action: Executes after the transition destination has been determined to be valid provided the condition


A possible syntax is the following: The format is: trigger [condition] {condition_action} /transition_action.

Keep in mind that you do not have to use all of them. Avoid events and use conditions, as they are standard. Additionally, decide between condition actions and transition actions.

Das Bild zeigt eine historische Kreuzung, die mit dem Symbol ‚H‘ gekennzeichnet ist und Fehler verursachen kann.
Bild: Historische Kreuzung, die zu Fehlern führen kann

2. Adhere to the Safe Modeling Language Subset

Based on modeling guidelines: mes_slsf_3110 | misra_slsf_047_ab | misra_slsf_046_a

History Junctions should be avoided as they can:

  • Lead to misinterpretation of the model.
  • Complicate the validation process.
  • Hide functionality, making the system harder to understand and maintain.

The image below showcases a history junction, marked by the H symbol. This could lead to the mistakes mentioned previously.

Events should also be avoided because they can:

  • Lead to recursion issues.
  • Cause unintended functionality.
  • Hide functionality, making it difficult to comprehend and maintain the model.


Which Stateflow action guidelines are safe to use?
The recommendation is to choose one type of action, either Condition Actions, Transition Actions or State Actions, and use it consistently throughout the model.

Dieses Bild verdeutlicht, dass die Änderung von Variablen während Bedingungs- oder Übergangsaktionen zu unerwartetem Verhalten führen kann.
Bild: Das Ändern von Variablen in Bedingungs-/Übergangsaktionen kann zu Fehlern führen

3. Use Condition and Transition Actions Correctly

Based on modeling guidelines: misra_slsf_045_e | misra_slsf_045_f | misra_slsf_045_g

Avoid Writing Variables in Condition and Transition Actions: Modifying variables within condition or transition actions can lead to unexpected behavior and complicate debugging.

Dieses Bild zeigt, dass das Lesen von Variablen, die in einer Transitionsaktion geändert wurden, in einer nachfolgenden Transition zu Ausführungsinkonsistenzen führen kann.
Bild: Das Lesen von Variablen, die in einer Übergangsaktion geändert wurden, kann zu Ausführungsinkonsistenzen führen

Prevent Reading Transition-Written Variables in Subsequent Transitions: A variable modified in a transition-action should not be read in a subsequent transition, as it can lead to inconsistencies in execution order.

Dieses Bild veranschaulicht, dass zur Gewährleistung eines vorhersehbaren Verhaltens jede Variable während eines Zustandswechsels nur durch eine einzige Übergangsaktion geändert werden sollte.
Bild: Um ein vorhersehbares Verhalten zu erreichen, ändern Sie eine Variable in nur einer Übergangsaktion pro Zustandsänderung

Single Transition-Action Writing: To maintain predictable behavior, a variable should only be modified by a single transition-action when moving between states.

Die Abbildung zeigt einige Beispiele für Übergänge, die parallele Zustandsgrenzen überschreiten.
Bild: Übergänge über parallele Zustandsgrenzen

4. Avoid Crossing Transitions in Stateflow

Based on modeling guidelines: mes_slsf_3109

To maintain clarity and prevent graphical overlaps, avoid transitions that cross state boundaries in Stateflow charts. Crossing transitions can make the chart difficult to read, increasing the risk of misinterpretation and errors.


In addition, a cluttered layout complicates debugging and maintenance, making it harder to track the flow of execution. By organizing transitions logically and keeping paths clear, you can improve model readability, maintainability, and overall reliability.


In the graphs below, transitions crossing parallel state boundaries are evident. It's crucial to avoid such crossings, as they can lead to confusion and potential modeling errors.

5. Do Not Use Equality Operators With Floating-Point Operands

Based on modeling guidelines: jc_0481 | mes_sltl_002

You should avoid the floating-point comparisons with the following equality comparison operators:

  • ==
  • !=
  • ~=
  • <>

Floating-point numbers have small rounding errors due to their binary representation, making exact comparisons unreliable. This can lead to incorrect results because two mathematically equal values may have tiny differences in memory. This is why using hard equality (strict bit-by-bit comparison) for floating points is not recommended.

Dieses Bild zeigt ein Beispiel für ein Problem, das durch Backtracking in Stateflow verursacht wird.
Bild: Beispiel für ein Problem, das durch Backtracking im Stateflow verursacht wird

6. Avoid Backtracking in Stateflow

Based on modeling guidelines: mes_sf_002 | misra_slsf_043_h

Stateflow does not support backtracking. This means that all executed actions remain in effect, regardless of whether the transition path reaches the intended final state. If a transition path fails to reach a valid end state, it can lead to unexpected behavior.

To prevent such issues, ensure that each transition path includes an unconditional default path. Additionally, either use condition actions only in the final segment of the transition or opt for transition actions instead.


(As discussed in Section 3, there are valid reasons to choose transition actions.)


Example of a backtracking issue:

 

Die Abbildung zeigt, wie das Hinzufügen des Ereignisses 1 die Reihenfolge der Übergänge ändert und warum eine manuelle Steuerung erforderlich ist.
Bild: Durch das Hinzufügen von Ereignis1 ändert sich die Reihenfolge der Übergänge, daher ist eine manuelle Kontrolle ratsam

7. Follow Best Practices for Setting Execution Orders

Based on modeling guidelines: mes_is_0002

Stateflow defines the execution order clockwise, especially for parallel states. Even slight changes to the graphical arrangement or the addition of a new element can lead to changed execution orders.


The following graph illustrates how the execution order of transitions in a Stateflow chart changes when a new event (Event1) is introduced, highlighting the importance of manually specifying execution orders.

Dieses Bild zeigt die empfohlenen Simulink-Einstellungen, um Stateflow-Funktionen lokal zu halten und globale Exporte zu vermeiden, die Tracing und Datenfluss erschweren.
Bild: Vermeiden Sie die Auswahl der Option 'Exportierte Funktionen dürfen von Simulink aufgerufen werden'

8. Avoid Global Stateflow Functions

Based on modeling guidelines: mes_slsf_3106

Defining Stateflow functions locally within their respective charts is a recommended practice to maintain modularity and prevent unintended interactions.  

Using the "Export Chart Level Functions (Make Global)" feature allows graphical functions to be accessed globally in any chart of the model. However, these functions cannot be easily traced (only by searching for the function name) and result in opaque behavior.

Additionally, enabling 'Allow exported functions to be called by Simulink' (available since R2014b) introduces complexities in function management and data flow, so it should not be selected.

Das Bild zeigt eine rekursive Schleife in Stateflow, in der func1 und func2 sich gegenseitig aufrufen, was eine unendliche Rekursion verursacht.
Bild: Rekursive Schleife in Stateflow, bei der func1 und func2 sich gegenseitig aufrufen, was zu einer unendlichen Rekursion führt

9. Skip Recursive Loops

Based on modeling guidelines: jc_0804

Ensuring that graphical functions in Stateflow are neither defined recursively nor call other graphical functions is crucial to prevent unintended behavior and maintain model integrity. Recursive calls can lead to infinite loops, stack overflows, and increased complexity in debugging and maintenance.


The diagram below illustrates a recursive loop problem in Stateflow graphical functions. When func1(x) is executed, it calls func2(x), which in turn calls func1(x), creating an infinite recursion. To prevent this issue, it is recommended to avoid direct or indirect recursive function calls in Stateflow graphical functions.

Das Bild zeigt die Oberfläche des TargetLink Property Manager von dSPACE.
Bild: TargetLink Property Manager von dSPACE

10. Explicitly Define Input Variables for Seamless Integration

When working with TargetLink, Simulink, and Stateflow, it is essential to explicitly define input variables to maintain a consistent and well-structured interface. dSPACE’s TargetLink Property Manager (as shown in the image below) helps manage these variable definitions, ensuring consistency across the model and final implementation.

Conclusion: Managing Complexity in Stateflow with Modeling Guidelines

Stateflow provides powerful modeling capabilities, but it also introduces risks when not used carefully.

To manage complexity, follow these best practices:

  • Keep it simple! Avoid unnecessary complexity in transitions and state logic.
  • Perform arithmetic operations in Simulink; otherwise, you risk the chart blowing up and becoming uncontrollable.
  • Follow established guidelines to prevent unexpected behavior and error-prone patterns.
  • Ensure a clear and structured layout for better readability and maintainability.
  • Use tools such as Go to MXAM Product Page to automate modeling guidelines compliance.

By adhering to these best practices, you can create robust, efficient, and maintainable Stateflow models that integrate seamlessly with Simulink and TargetLink.

If you would like to access our library of articles, webinars, research projects, and more on model-based development, check out our Go to Knowledge Library. Stay updated, strengthen your expertise, and create simply better models!

 

Kontaktieren Sie uns

Dieses Bild zeigt Elena Bley.
Elena Bley
Senior Manager Marketing & Webinars
Bitte addieren Sie 6 und 2.

* Pflichtfeld

Bitte addieren Sie 1 und 9.