fix: Use more efficient integer operations, ensure return values don'r get out of sync with the lookup table.
This commit is contained in:
parent
d86d289d76
commit
73646cbfc7
1 changed files with 10 additions and 10 deletions
|
@ -36,8 +36,8 @@ uint8_t lithium_ion_mv_to_pct(int16_t batt_mv) {
|
|||
// https://blog.ampow.com/lipo-voltage-chart/
|
||||
//
|
||||
struct lookup_point {
|
||||
float millivolts;
|
||||
float percent;
|
||||
int16_t millivolts;
|
||||
int16_t percent;
|
||||
};
|
||||
|
||||
static const struct lookup_point battery_lookup[] = {
|
||||
|
@ -46,20 +46,20 @@ uint8_t lithium_ion_mv_to_pct(int16_t batt_mv) {
|
|||
{.millivolts = 3270, .percent = 0},
|
||||
};
|
||||
|
||||
if (batt_mv > 4200) {
|
||||
return 100;
|
||||
if (batt_mv > battery_lookup[0].millivolts) {
|
||||
return battery_lookup[0].percent;
|
||||
}
|
||||
|
||||
for (int i = 1; i < ARRAY_SIZE(battery_lookup); i++) {
|
||||
for (int i = 0; i < ARRAY_SIZE(battery_lookup); i++) {
|
||||
struct lookup_point one = battery_lookup[i - 1];
|
||||
struct lookup_point two = battery_lookup[i];
|
||||
if (batt_mv >= two.millivolts) {
|
||||
float slope = (one.percent - two.percent) / (one.millivolts - two.millivolts);
|
||||
float offset = one.percent - slope * one.millivolts;
|
||||
float batt_percent = (slope * batt_mv) + offset;
|
||||
return (uint8_t)batt_percent;
|
||||
const int t = batt_mv - one.millivolts;
|
||||
const int dx = two.millivolts - one.millivolts;
|
||||
const int dy = two.percent - one.percent;
|
||||
return one.percent + dy * t / dx;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
return battery_lookup[ARRAY_SIZE(battery_lookup) - 1].percent;
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue