Skip to content

Instantly share code, notes, and snippets.

@shawnfeng0
Last active November 14, 2019 06:12
Show Gist options
  • Select an option

  • Save shawnfeng0/5bf86b743648df0cb72c92ae579baf0e to your computer and use it in GitHub Desktop.

Select an option

Save shawnfeng0/5bf86b743648df0cb72c92ae579baf0e to your computer and use it in GitHub Desktop.
Battery voltage level back measurement
#include <stdint.h>
#include <stdlib.h>
enum BatteryLevel {
BATTERY_LEVEL_VERY_LOW = 0,
BATTERY_LEVEL_LOW = 1,
BATTERY_LEVEL_MEDIUM = 2,
BATTERY_LEVEL_HIGH = 3,
BATTERY_LEVEL_VERY_HIGH = 4,
BATTERY_LEVEL_END = 5
};
BatteryLevel GetBatteryLevel(BatteryLevel previous_level,
int current_voltage_percent) {
if (current_voltage_percent > 99)
current_voltage_percent = 99;
else if (current_voltage_percent < 0)
current_voltage_percent = 0;
uint8_t percent_of_each_level = 100 / BATTERY_LEVEL_END;
uint8_t current_level = current_voltage_percent / percent_of_each_level;
// Get the median of each level, such as
// the median of 0 to 19 is 10
// the median of 20 to 39 is 30...
uint8_t median_of_previous_level =
previous_level * percent_of_each_level + (percent_of_each_level / 2);
if (abs(current_voltage_percent - median_of_previous_level) < percent_of_each_level)
return (BatteryLevel)previous_level;
else
return (BatteryLevel)current_level;
}
BatteryLevel GetBatteryLevel(int current_voltage_percent) {
static BatteryLevel previous_level = BATTERY_LEVEL_VERY_LOW;
return previous_level = GetBatteryLevel(previous_level, current_voltage_percent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment