Main Content

Model Battery Management with Custom Code

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).

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.

Battery Management

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.

Chart Sensor Readings with 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.

Simulate Communication with Hardware

The chart Sensor Readings with Fault Detection consists of three parallel states (VoltageSensor, CurrentSensor, and TemperatureSensor) that model the readings of the battery voltage, current, and temperature sensors. The three parallel states contain similar decision logic for choosing between simulation and code generation behavior. For example, when the parameter CODEGEN_FLAG is false, the VoltageSensor contains this logic for simulating the voltage readings.

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.

In each parallel state, the substate SensorFaultDetection handles the error signals returned by the sensors. In the event of a sensor error, SensorFaultDetection 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.

The example includes two custom C code files: batteryMonitorDriver.h and batteryMonitorDriver.c. These 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. For more information, see Code Generation.

To simulate the model with the driver code:

  1. Open the Configuration Parameters dialog box.

  2. In the Simulation Target pane, specify the header file and source file.

  3. Under Advanced parameters, select Import custom code.

For more information, see Configure Custom Code.

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 this code:

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.

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.

The chart represents five 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 (Simulink).

Code Generation

Inputs into the chart Sensor Readings with 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 Control Indicator Lamp Dimmer Using Variant Conditions.

To compile the generated code with the driver code, open the Configuration Parameters dialog box and, in the Code Generation > Custom Code pane, specify the header file and source file. For more information, see Configure Custom Code.


[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