Developing Battery Cell Balancing Logic Using Stateflow - MATLAB & Simulink
Video length is 37:26

Developing Battery Cell Balancing Logic Using Stateflow

Overview

Using battery cell balancing as an example, learn how to use Stateflow® for designing, testing, and implementing decision logic. You will see how to build complex logic using Stateflow, test it using Simulink Test™, and deploy it to various hardware or software platforms.

Highlights

  • Introduction to Stateflow
  • Modeling and simulating cell balancing logic for a battery
  • Designing and simulating parallel states
  • Testing and deploying decision logic
  • User success with Stateflow
  • How to get started

About the Presenters

Ed Marquez is a Simulink Product Manager at MathWorks. He supports automated report generation and Model-Based Design applications.  Ed is experienced in automotive system modeling and controls. He holds a MS and BS in Mechanical Engineering from Virginia Tech.

Karanjodh Singh Meen has a MS in Mechanical Engineering from Arizona State University and BE form Punjab Engineering College, India. He specializes in the area of control systems, modeling of physical systems and robotics. He has experience working with drones and Automobiles. In 2018, he joined Technical Support at MathWorks and later moved to the Application Engineering Group in 2019.

Recorded: 10 Dec 2021

Hello, everyone. Thank you for joining us for this session on Stateflow for designing and testing decision logic. Let's imagine for a moment that you're building a Battery Management System, or BMS. A BMS is a controller that implements complex decision logic. And you'll find logic like this in multiple applications, like electric vehicles, medical devices, and many more.

As you engineer this system, how do you design the supervisory logic that defines the state and operation of the system? And how do you test and deploy that logic onto your embedded hardware while minimizing rework? Today, we'll show you the closed loop model of a BMS in a battery plant. And you'll see how Simulink and Stateflow can help us answer these questions.

My name is Ed Marquez. I'm a product manager for Simulink and model-based design at MathWorks. And today, Karan is with me.

Hey, everyone. My name is Karanjodh. And I'm an application engineer at MathWorks. I also focus on Simulink and model-based design workflow. So to answer those two questions, we are going to look at the example of a battery management system. Now, in this model, on the left, we have the BMS logic. And this is what we will talk about today. And on the right, we have a plant model of a six cell battery pack. We will not be talking about plant modeling today.

So the job of a BMS is to continuously monitor each cell in the battery pack. And depending on the desired state, such as driving mode, charging mode, standby mode, fault mode, BMS has to control the battery to get it and to keep it at the desired state in a safe and reliable manner. And at the same time, make sure that we get the optimal performance from the battery and prolong its life.

So as you can probably imagine, this would require complex decision logic to do that. And as the BMS has to monitor feedback data coming from estimators, sensors, things like cell voltages, temperatures, and depending on these inputs, it has to make a decision on what to do. So today, we will see how we can construct this complex decision logic that incites BMS using Stateflow, as shown here, for example.

And if you zoom in to the top left corner in here, you can see inside the main state chart we decide what to do when we are driving mode, charging mode, or standby mode. Now, I want to say that this is just an example. And the same ideas that we present today can be extended to other applications as well. But before we jump into the details of this particular example, let's look at the agenda for today.

So we'll start by answering some basic questions like what is Stateflow, and where does it sit in MathWorks product family. After that, we'll transition into showing you the actual tool, how we can use Stateflow by showing some demos. After that, we'll share some success stories of our customers who have used Stateflow to build real world applications. And finally, we'll summarize the session and share some resources that you can leverage to learn more about the tool and get started. So Ed, why don't you start by telling us what a Stateflow and where does it sit in MathWorks product family?

Yes, Stateflow is a graphical environment that allows you to design and simulate decision logic for things like supervisor control, task scheduling, and fault management applications. And it can also be used for communications protocols, user interfaces, and much more. And what that means is that with Stateflow, you have an intuitive way to create state transition diagrams, flowcharts, and truth tables.

Now, the graphical design, debug, and analysis piece is important because it makes it easy to handle complexity in your state machines or state diagrams. So that can help you save time when compared to writing and debugging an equivalent amount of C code. Also, simulating your Stateflow models helps you find design issues earlier in the process. And you can increase how rigorous your testing and analysis are by doing coverage and trying different scenarios or test cases.

And a great benefit of Stateflow, and also Simulink is that you automatically generate code from the models you already have. And this code can be used for production or rapid prototyping. And this helps you minimize rework and get to the embedded hardware faster.

Now, to help you understand where Stateflow fits in, I also want to bring up MATLAB and Simulink. MATLAB is a programming environment that supports your algorithm development, your data analysis visualization, and numeric computation. And Simulink is a graphical environment that helps you design, simulate, and test dynamic systems. Now, these two are the platforms. And they work together to give you a lot of flexibility.

And on top of those two platforms, we produce more than 100 add-ons that you can use for specialized tasks and different applications. And that's where Stateflow fits in. It's an add-on to help you build complex logic in an intuitive way. And there are other add-ons for things like computer vision, wireless communications, robotics, and autonomous systems, and so on.

So Ed, with that, can you show us how we can get started by, for example, building a simple model of balancing logic for a battery system?

Yes, let's jump into the demo section of this session. So the first demo we're going to see is how to build charge balancing logic. And the challenge here is that as we use the battery pack, some cells fall out of balance. Some cells end up with a lower SOC. And some end up with a higher SOC.

And so the problem with that is that the cells with the lower SOC limit how much we can use the battery. And the cells with the higher SOC limit how much charge we can put into the battery. So we want to equalize that or balance that. And we'll go from something that looks like the situation here in the top to the situation down here in the bottom.

So we have multiple ways to access Stateflow. We can do it from the Simulink start page, by clicking the Simulink icon in the MATLAB tool strip. And I can start with a blank Simulink model and then add a Stateflow chart to that. We'll see how we can do that. But I also want to show you how you can start with templates.

And these templates from the start page are useful. You have multiple options when you search for Stateflow, for example, a blank chart, or a simple chart, a hierarchical chart, and other options as well. In our case, we've already put together a model for this charge balancing challenge that we're trying to address. So we'll start with that model.

So in this model, to the left, we have the inputs. The first input is the BMS state. It's at 1 or 0. And we're controlling that with this switch. We also have the individual cell voltages that's an array of values. And each one of those values is associated with one of these knobs here. And we're also looking at the maximum and minimum cell voltages.

We also look at the balancing command. That's one of the outputs of the supervisory logic. And to insert the Stateflow chart that we'll use to implement our logic, we can go to the library browser in Simulink. And that way we can explore all the blocks that we can use. Or we can simply use quick insert and just type in the Simulink canvas. And when we type Stateflow, the first option is to insert a chart.

So when we insert that, I have this area that I'm using to help me size and align that blocking. With the tool strip, I have multiple format options. So I can match the size and also align my area and my Stateflow chart. So now, I can start making connections.

So I can connect the first input to my Stateflow logic. And you see that the ports are automatically created when I get to the Stateflow chart. And so I can continue making connections. And you see that the ports also inherit the signal names. And I can even edit those port names as I make the connections. So we can continue making our connections. Again, align our chart.

And we can also connect the output, which is the balancing command. So now, we have all the connections that we need. And we can jump into the Stateflow canvas to start developing our logic. So here in the Stateflow canvas, one of the first things you'll notice is to the right, we have the Symbols pane. And this gives us information on the inputs, outputs, constants, parameters that we're working with that our Stateflow charts may need.

We also have this Dashboard panel. And this is a collection of dashboard blocks that when we make them a panel, they can come with me to different levels of the model hierarchy. So very useful when I'm simulating and testing my model. Now as I develop the model, I probably don't need to see it. So I can just double click on the dashboard. And I can minimize it. So that I can build my model while I don't need the dashboard.

So to start inserting states, and transitions, and other elements in Stateflow, I can use the tools that I get here to the left. Or I could just also use quick insert. And in this case, I can just type state, since that's what I want. We can resize this. And one thing you'll notice here is the dark dot at the top, which is the Stateflow default transition.

So when the Stateflow chart wakes up and becomes active, that is the first point that we're going to check. Therefore, it will end up in this first state. Now we want to name this date balancing off. We also want another state called balancing off. So we could just draw in the canvas, select state, and select the name of balancing on.

So once we have the states, I can also use the smart cues or simply draw lines. We'll use the smart cues to insert translations between these states. And these transitions can be events. They can be conditions or even actions that happen as those conditions are evaluated. Now, in this case, we want to use conditions. And the first condition is that the BMS state needs to be set to 1.

So it needs to be on. On the other hand, to go from on to off, we're also going to use a condition. But in this case, the BMS state should be equal to 0. So when that's true, we'll go from on to off. So now we have states, transitions, and now we need to specify what's going to happen in each one of those states. So we're going to do that with actions.

And in Stateflow, you can have entry actions, during actions, and exit actions. And the names are self-explanatory. And I can abbreviate those with just the first two letters of the words. So in this case, when I entered the balancing off state, and during that state, we'll set the balancing command, if you remember that, the output, we'll set that to 0.

In the balancing on state, we'll do the same. So we're copy pasting what we had before. But in this case, we'll set the balancing command to true. So now, we're getting closer to being able to simulate this model. In fact, if we look at the Symbols pane, we have just a few wordings. But these are the symbols that are not being used.

So in this case, I can expand my panel again. And we can run our simulation. So you see there, that with the default translation, we go to the balancing off state. And with the dashboard block, we change that to on. And you see that enables our transition. So that we can go into the balancing on state. And here, you see that the output, which is the balancing command, is set to true or 1.

Now, if we change the BMS state back to 0, you see that we transition back to balancing off. And our balancing command is 0. So at this level, we have some working logic. And we can start adding complexity. So I'll minimize my Dashboard panel. And one of the things that I want to do upon entering and during this state is determining the delta cell voltage, so just the difference between the maximum cell voltage and the minimum cell voltage.

And in fact, I also want to do that when I enter and while I'm in the balancing on state. So we'll just copy that in this second state. Now, I also want to use this delta cell voltage in the transition. Because in addition to the BMS being on, one other criteria I want to look at is if the delta cell voltage is greater than a target delta voltage. And this target delta voltage is just a parameter that we can control.

So now I will add substates in the balancing on state. And what we want to do here is have two substates, one for balancing active, and one where balancing is not active. So we'll start with the balancing active state. And upon entering this state, and while we're in it, here, we want to send a true balancing command for the cells that need to be balanced. And we're simply going to determine that by comparing the level to just to a certain target delta V.

In addition to the balancing command, we also want to specify a flag that tells us when the balancing operation is complete. And so that will happen once all the balancing commands are 0. So now we want to add a balancing not active substate. And we want to be able to transition from the balancing active to the balancing not active state.

In this balancing not active state, nothing is going to happen. So we'll leave it blank. And here, we can use the smart cues to insert the transitions that we want to work with. So to go from balancing active to inactive, we simply will look if the balancing flag is complete. That'll tell us if the operation is done. And to go from balancing not active back to active, we're going to use two criteria. The first one is if our cells fall out of balance, and we'll introduce temporal logic. So that we're not jumping back and forth too quickly.

So now, we can introduce a delay with the word after. So after two seconds of simulation time and the cells falling out of balance, then we'll go back to balancing operation being active. Now, this is a really powerful concept, being able to combine your operational logic with temporal logic. And you see that the syntax is very similar to what you would use in MATLAB. So that's a lot of the power and flexibility that you get with these tools that are built on top of MATLAB.

So now, we can look at the Symbols Manager. And we see that we have a few symbols that we need to resolve. So the flag for balancing completion, we need to specify that that's local data. We'll also specify the delta cell voltage as local data. And then the target delta V is a constant. And we can set the value for that. In this case, we'll set it to three volts. And now I can bring back my dashboard panel to start simulating and testing my model.

So when I run the simulation, you see we go into the balancing off state by default. If I flip the switch to on, we have one of the criterias to go into balancing on. But the other criteria is that the cells have to fall out of balance. Now, as you develop your model, your controller may be connected to a plant that gives you feedback to your controller, or maybe a physical system that reads sensor values and gives you the feedback to your controller.

In this case, we're going to be changing these values manually by adjusting the knobs that we have in our dashboard panel. So if I bring cells 1, 2, and 3 out of balance, you will see that we have transitioned to the balancing on state, we're in the substate of balancing active. And if we go and look at the outputs, you see here that we're sending a command for the cells to balance.

And if we bring the cells back into balance by switching the values to 6, or close to 6, and if we look at the outputs again, what you will see is that now there's no balancing command, because we're in the balancing not active state. So these are all zeros, as you would expect. And when we flip the switch to off, then we evaluate that BMS state equal to 0 condition. And therefore, we transition to the balancing off state.

So that's great, Ed. So I see that the logic is becoming pretty complex as we add more and more states to this. So can you show us a few ways and how we can debug this logic?

Yes, Karan. One of the options that we saw during the simulation is the animation that shows you where you are and that will tell you if the behavior of your state machine is what you expect. So you can definitely use that. You can actually slow down or speed up that animation, depending on your needs.

There are also ways to debug your state logic in the Debug tab. So for example, you can use the Activity Profiler to understand where your logic is spending the most amount of time. You can also add breakpoints as your logic becomes more complex as well.

So what if I have some logic that I've developed, let's say, using MATLAB function and if/else statements. Is there a way I can import or reimplement that logic in here?

Certainly, just because you have some logic in MATLAB doesn't mean you have to throw it away and start everything from scratch with Stateflow. If we look at the tools here that you get. You can actually bring in Simulink functions, Simulink states, and also MATLAB functions into your state charts. So for example, if you already have some code there, you can add it here and call that function with your state logic. And same thing with Simulink functions.

You also mentioned starting with if/else logic. And another thing I want to show you is the Pattern Wizard, because this gives you a starting point for building that kind of logic. So it gives you sort of a template. So if we look at this if/else template here, just to give you a quick example, I can build this and call it my logic.

And so if a is equal to 1, we can set b equal to 10. Otherwise, b will equal 0. And what you'll see here is that it built this flowchart for me, just by giving it those inputs. Now, it's erroring out right now, because you can only have one default transition at one level. But you get the point here.

All right, Karan, so we saw how to build this basic state machine. And right now, most of the logic is sequential. But can you show us an example of a more complex system, perhaps like the BMS we saw in the beginning, where maybe there's a lot more complexity, and some things may need to happen at the same time or in parallel.

So let's jump back into the main example that we saw earlier. So if you go into the BMS ECU subsystem, this is where all the logic exists. And in the bottom here, you can see the balancing logic. This is very similar to what Ed constructed from scratch. And mostly, the difference here is the name of these different variables that we are using.

Now, this balancing logic that we constructed is very sequential. Now, let's transition back to the main state machine on the top here. And this main state machine has a lot more input data coming from either sensors, estimators, or maybe input coming in from users. And it has a bunch of different outputs which control different components, which could be either software components or hardware components.

So in this state chart, we can see that we have multiple states running in parallel. Essentially, we have four different states which run in parallel to each other. So this is required, because we want to be able to monitor and control different things at the same time. So we have the logic partitioned into four parallelly run states.

So if we zoom into the top left, now this is our main state machine. And depending on the input, whether it's in standby mode, driving mode, or charging mode, it sets the appropriate condition of the battery. So on the right hand side, we have fault monitoring state, which monitors different conditions of the battery, like the temperature, current, and voltage. And if there is anything outside the normal, it will throw a fault.

And at the bottom, we have the inverter contactor state and charger contactor state. Now, the purpose of the bottom two states is to make sure that all the physical components are in place when you're either in the driving mode or whether you're in the charging mode. Now, let's look at the top left state a little bit more closely.

This looks kind of similar to what we constructed from scratch. There are different substates present in it, like standby mode, driving mode, charging mode, and inside each one of these states, there could be more substrates. And we transition between these different states based on certain conditions. One thing that I want to highlight is that while the system is running, at the same time, we're monitoring if there is a fault being thrown for example.

While, the battery is being operated, what happens if the temperature of the battery goes outside a certain range? This fault monitoring state, which is running in parallel, would automatically transition to either a high temperature fault if it's at a very high temperature or low temperature vault. And as it transitions to those states, it will set a fault present flag to true.

And our parallel states automatically detect that fault. And you can see, based on if the fault is true, it will automatically transition to whatever state it is in. Maybe it's in standby state. It will transition to the fault state in here, stopping the operation of the battery and making sure that the battery doesn't get damaged. Or if it's already damaged, then it doesn't get damaged more.

And the similar thing exists in the other two parallel states as well, which is the charger contactor state and inverter contactor states. Now, these two states are very sequential. And all they're doing is making sure that all the physical components are in place once we decide to charge the battery. So it's a very step-by-step operation with delays between those steps.

So one thing I want to mention is that even though we are talking in terms of battery systems, these modeling methodologies can be extended to other applications as well. For example, in case where you have multiple inputs, and based on these multiple inputs, you want to decide the state of the machine, this is where Stateflow becomes really useful. Another quick example that comes to mind is a washing machine, where you have multiple inputs that the user can set. And based on those inputs that the user has set, different cycles are operated for that machine.

Karan, this is an excellent overview of this BMS logic that is quite complex. And Stateflow really gives you an excellent way to simplify how you build that complex logic. Just imagine building an equivalent amount of if/else statements. Now, once you've created this logic, how can you test that logic under multiple scenarios, for example?

That's a great question, Ed. So every time you simulate your Stateflow chart, you're testing your logic against the plant model that you designed. Because remember, now, we're not running these Stateflow charts in isolation, but rather in closed loop with your plant model. So every time you run a simulation, you're testing a scenario, and you're testing your logic for a particular scenario.

So now, if you want to test your model for multiple different scenarios and you don't want to modify the model for each scenario, you can wrap your model inside the test harness. And that's what we have done here. And you can find all the test cases in this test harness and choose which test case you want to run.

Now, if you want to automate this to another level, for example, right now, what you have to do is you have to come to the test harness, select the test case you want to run, and run it, and visualize the results. But what if you want to run all the test cases for your system? What you can do is you can pull in all the test cases into one test suite using Simulink Test Manager.

And as you can see, we have defined multiple test cases for that battery management system. And you can test and run all of these tests with the click of a single button from here. And view and analyze the results in one place. Can analyze individual results. Or you can generate reports from these results that you can share across the organization with other people to read and study the system that you have designed. Now imagine you had to find hundreds of test cases for a system. This makes the workflow a lot more fluid in that case.

Right, this is excellent. And also, like you mentioned, it gives you the ability to automate how you run all of these tests. Now, once you've tested under different scenarios, how do you determine whether you have dead logic, meaning parts of your logic that are not being reached? What kind of analysis can you do to determine that?

That's a great question, Ed. So when you're designing complex decision logic with Stateflow, one of the important things is to make sure that you test that logic and there's no dead logic in your system. Because if there's a dead logic that's present inside your system, it means that has not been tested with their test cases. And you don't know how that logic is going to behave if it's executed in the real world. So you want to avoid having dead logic.

So with coverage analysis, it gives us a great way to look at different MCDC coverage, condition coverage, and so on. And if we use this report, we can go back to the model. And it will interactively show which parts of the model are executed and which parts of the model are not. And in this view, on the right hand side, you can see the coverage report. And you can see the details of the coverage analysis.

And if I go inside the model, I'm zoomed into one of the charging substates in here. And you can see the conditions that were executed are highlighted as green. But there are certain conditions in the system that were never executed. And that's why we are viewing this red coloration of the substate. And on the right-- on the left hand side, you can see that there are certain conditions that were never executed. So doing coverage analysis with Simulink Test gives you these kind of interactive reports that you can see. And you can use this to understand what's going on with your logic.

All right, and so once you've simulated and test your logic under different scenarios, performed your coverage analysis to find, maybe, dead logic, how can you easily get to hardware deployment from here?

So once you've designed your logic, and let's say you have tested it, and you're satisfied with the results of your logic, the next step in the process that you want to implement this on some hardware, let's say, an embedded hardware or maybe HDL or BLC based hardware. So most of these hardware don't understand Stateflows, Stateflow charts. So you want to translate this model that you have, this logic that you have designed, to maybe C code, HDL code, or BLC.

So in this particular example, what we're showing is that we have used Embedded Coder with Stateflow to translate our state machine to a C code. And you can see the generated code exists on the right hand side. And you can go through this code and implement this on an embedded processor. In fact, with Embedded Coder, you can even trace back the individual lines of code to your model. And you can trace your model back to the lines of code.

So for example, if I go inside my main state chart and highlight a system, it will automatically highlight the lines of code that are generated from that subsystem, as you can see. And if you highlight something on the right, it will highlight the system on the left.

This is excellent, Karan. And so this code can probably be used, as you said, for hardware deployment. But maybe this is other code that you can integrate in other software frameworks if you're working with those. And another thing that you also mention is the ability to do traceability to model elements. But even if you have requirements, if you're using Simulink requirements, and you have those associated with your model elements, then you can have traceability from the requirements, to the model, all the way to the code.

That sounds great. So far, what we have seen is that how you can use Stateflow to construct complex decision logic, how you can test and validate this logic, and then finally, automatically, how you can generate code for this logic, and maybe deploy to different kinds of hardwares. So Ed, why don't you show us how we can get started with Stateflow and maybe also show people how they can access this particular example, if they want to play with this example?

Absolutely, for that, I want to take us back to the Simulink start page, where we were looking for some of the templates. And one of the ways that you can get started is with examples. So for example, if we search for Stateflow here, you can actually see all of the demos that are available to you. In this case, you get a small sample. But you can actually explore all of them if you click on this View All button. And then you can start with these models, change them, and tailor them to your specific use case.

Another great option to get started is with the Onramps. And again, we have multiple of these Onramps. These are free, interactive tutorials that get you started with the tools in just a couple of hours. We have them for Simscape, Simulink, Stateflow, and so on. And so in this case, you walk through a series of activities.

And the great thing with Onramps is that you get feedback immediately. You get the series of tasks and steps that you're completing. You build them interactively here. And once you submit, you get immediate feedback on whether you got it right or maybe you need to keep trying that. So definitely recommend getting started with the Onramps. And again, these also work with Simulink Online. So you can just start it from your web browser.

You also asked about how people can find this demo that we went over today. And you can find this demo by going to File Exchange. Here's the title of this entry. So you can look for it. And here, you can see the ratings, the downloads. And you simply can click the Download button. And here, it also tells you all the products that are required for this model to run. So feel free to try it out. Give us some feedback on what you think, how we can keep improving it. And again, this is something that you can try today.

That's great. So Ed, can you now share one of our user stories on the how a customer used Stateflow to develop a real world application?

Certainly, we see Stateflow used in the real world all the time. In fact, for that, I want to take you to our User Stories page. Here, you can search for yourself. And if we do a quick search for Stateflow here, we can see multiple user stories. The one that I want to highlight today is this one from Alstom and how they were able to generate production code for a safety critical application.

So again, in this case, they wanted to design and implement a real time power conversion and control system for railways. And they used Simulink, Stateflow, and model based design to again simulate and automatically generate production ready code for that safety critical transportation system. Some really good results, they cut the development time by 50%.

And again, they were able to generate that production ready code. And they established a common language for development for engineering groups that were working across different geographies. And a great thing here is that they mentioned that using Stateflow, the team model, the supervisory control, and the control system states, including startup, slowdown, and also error handling. And the communications protocol between the power conversion control and the system central fault handling unit was also implemented in Stateflow.

And also here, they mention how, after simulating the system in Simulink and Stateflow, they also used automatic code generation to get to production ready code. And again, they integrated that code with a number of real time operating systems as well. So a very compelling use case of Stateflow out there in the real world. So now that we've seen how you can get started, we show you how to see the demo, and some of the use cases in the real world, Karan, what are some of the resources that people have available to get started?

So some of the other resources that you can use is first, the MATLAB Central Community. The File Exchange that Ed just showed is a part of MATLAB Central. This is a user driven community where people come and share their experiences, ask questions. Even MAT workers contribute to this community.

In addition to that, we have a lot of getting started videos. And we have a Training Services Department. Now, the goal of the Training Services Department is to help you learn the tool in an efficient way, but at the same time, make sure that you learn it in a way that's most applicable to your projects and your applications. And finally, we have consulting services as well.

So the consulting services help you finish your projects using our products in a timely manner. And then at the same time, make sure that in future, you will be independent in developing those projects on your own. So with that, Ed, why don't you summarize the session for us?

Yes, today, we saw, in summary, that Stateflow helps you model and simulate decision logic using state machines. And you learned about ways to reduce time and effort by testing early and automatically generating code from Simulink models and Stateflow charts. You also saw how Stateflow is being used today to solve problems in real world applications. And finally, remember that there are multiple resources available to you to help you get started and be successful with your projects. With that, we want to thank you for your time and your attention.