Tjoms99 / xiao_sense_nrf52840_battery_lib

A battery management library for the XIAO BLE and XIAO BLE Sense board using Zephyr.
Apache License 2.0
27 stars 6 forks source link

Automatically discover the current battery capacity. #10

Open Tjoms99 opened 4 months ago

Tjoms99 commented 4 months ago

Battery State Determination and Capacity Calculation Enhancement

Summary

Currently, a lookup table is used to determine the battery's charge level based on voltage. This feature can be enhanced by allowing the MCU to determine the battery state dynamically.

Existing Implementation

The lookup table for voltage and capacity in percentage:

static BatteryState battery_states[BATTERY_STATES_COUNT] = {
    {4200, 100},
    {4160, 99},
    {4090, 91},
    {4030, 78},
    {3890, 63},
    {3830, 53},
    {3680, 36},
    {3660, 35},
    {3480, 14},
    {3420, 11},
    {3150, 1}, // 3240
    {0000, 0}  // Below safe level
};

Proposed Feature

Enable the MCU to determine the battery state by running a fully charged battery and discharging it down to just before a safe level. The safe level must be user-defined before running the test.

Discharge Functionality:

Improving Capacity Calculation: Currently, the capacity is determined using linear interpolation:

for (uint16_t i = 0; i < BATTERY_STATES_COUNT - 1; i++)
{
    // Find the two points battery_millivolt is between
    if (battery_states[i].voltage >= battery_millivolt && battery_millivolt >= battery_states[i + 1].voltage)
    {
        // Linear interpolation
        *battery_percentage = battery_states[i].percentage +
                              ((float)(battery_millivolt - battery_states[i].voltage) *
                               ((float)(battery_states[i + 1].percentage - battery_states[i].percentage) /
                                (float)(battery_states[i + 1].voltage - battery_states[i].voltage)));

        LOG_DBG("%d %%", *battery_percentage);
        return 0;
    }
}

Expected Outcome