Main Content

Model Battery Management with Custom Code

With Stateflow® you can integrate your custom C code into charts. Using custom C code in a Stateflow chart allows you to:

  • Reuse existing algorithms that you have already coded.

  • Use C code for low-level hardware operations, which may be difficult to implement with Stateflow.

This example shows how to use custom C code with Stateflow to model a system that manages battery percentage, also known as the state of charge (SOC).

Battery Management

To open the model, in the command prompt type:


This model represents several components of a battery management system. This system is designed to be implemented on a controller for battery powered devices, such as battery powered vehicle or a cell phone. The purpose of the battery management system is to limit the power demands on the battery and to ensure that the SOC does not get too high or too low. An SOC that is too high or too low would be detrimental to the health of the battery. Additionally, the model is designed to limit the discharge of the battery when the charge is low in a trade-off of performance for battery lifetime.

The battery management model achieves these goals with three different charts.

The battery management model.

Chart Sensor Reader w/ Fault Detection reads the sensor values from the battery pack and reports out when the sensors is in a faulted state. Chart Battery State Estimation uses the sensor reading to estimate the SOC of the battery. Chart Battery Power Limit Control conserves the battery, protects the battery health, and keeps the SOC away from either extreme. The chart accomplishes these tasks by setting power limits for the controller.

With this model you can generate code and deploy that code to an embedded controller along with other control code that your system may need.

System Controller design.

Simulate Communication with Hardware

When using the model for simulation, the Dashboard panel allows you to control the sensor readings for the system inputs. If the calls to the battery monitor timeout, an error code of -9999 is returned from the function.

Two C code files are included with Sensor Reader w/ Fault Detection: batteryMonitorDriver.h and batteryMonitorDriver.c. These two files represent the device driver code that would be used to get sensor data from the system, including battery voltage, current, and temperature and are used for code generation. See Code Generation.

Inside the voltage chart.

The Stateflow chart can also handle the error signals returned by the sensors. In the event of a sensor error, the SensorFaultDetection subchart holds the last known valid sensor reading until the error code has been received for a certain amount of time. After this threshold is met, SensorFaultDetection sends a fault message and assumes it will be handled by the other control components of the controller.

In order to simulate the model with the driver code, you must include the header file and specify the source file in the Simulation Target pane of the Configuration Parameters, and the Import custom code option must be selected. For information on the Import custom code option, see Import custom code.

The simulation target pane of the configuration parameters.

Estimate Battery State of Charge by Reusing Custom Code

To estimate the battery state of charge, the model utilizes a custom C code algorithm. The included file estimateSOC.c contains the following code:

Custom C code that estimates the battery state of charge.

With this algorithm, you can easily call the C code function, rather than reimplementing it with Stateflow charts.

In order to account for the sensitivity of noise and change of current in the estimateSOC algorithm, Stateflow logic is used to implement a debouncing algorithm. This logic simplifies the SOC percentage into 5 ranges: MAX, HIGH, NORMAL, LOW, and MIN. These ranges prevent rapid fluctuation between different control states. The exit transitions from the child states go to the edge of the parent state. When these transitions are taken, Stateflow returns to the default transition of the parent state.

Stateflow debouncer logic.

Logic to Control Device State of Charge

It is easier to design this control logic with a Stateflow chart, rather than implementing the logic control through custom code. This chart implements power limit on the battery based on the estimated battery state.

Stateflow control logic chart.

The chart represents 5 possible modes for power limits on the battery.

  1. Performance Mode: Allow high power draw when battery charge is high.

  2. Battery Saver Mode: Limit power draw on the battery for efficiency when charge is low.

  3. Off: Do not allow Power Draw when battery is at state of charge limits.

  4. Fast Charge: Quickly charge the battery when charge is low.

  5. Slow Charge: Slowly charge the battery when charge is high for battery health benefits.

Simulate Using the Dashboard Panel

To test that the model behaves as expected, you can use the dashboard panel to simulate the voltage, current, and temperature readings. The switches allow you to simulate a sensor error to test the fault detection logic. The gauge and plot dashboard blocks are bound to the activity of stateflow charts to visualize internal states and data. You can move and minimize the dashboard panel while navigating the model. For more information on dashboard blocks, see Control Simulations with Interactive Displays.

Dashboard panel to simulate voltage, current, and temperature.

Code Generation

inputs into the state Sensor Reader w/ Fault Detection are provided with two C code files: batteryMonitorDriver.h and batteryMonitorDriver.c. These two files represent the device driver code that would be used to get sensor data from the system, including battery voltage, current, and temperature.

To use this model for code generation, the driver code must communicate with the external hardware. To enable this functionality, a variant transition using the control variable CODEGEN_FLAG allows the Stateflow chart to call the C code directly when generating code and simulate the sensor value with noise. In the Model Explorer, open the Base Workspace and set the value of CODEGEN_FLAG to true. For more information on Stateflow Variants and variant transitions, see Code Generation Using Variant Transitions.

In order to compile the generated code with the driver code, you must include the header file and specify the source file in the Custom Code pane of the Configuration Parameters.

The custom code pane of the configuration parameters.


[1] Ramadass, P., B. Haran, R. E. White, and B. N. Popov. “Mathematical modeling of the capacity fade of Li-ion cells.” Journal of Power Sources. 123 (2003), pp. 230–240.

[2] Ning, G., B. Haran, and B. N. Popov. “Capacity fade study of lithium-ion batteries cycled at high discharge rates.” Journal of Power Sources. 117 (2003), pp. 160–169.

Related Topics