More correct algorithm for calculating battery percent
This commit is contained in:
@@ -11,7 +11,7 @@ public:
|
||||
_battery_data_switch_pin = battery_data_switch_pin;
|
||||
}
|
||||
|
||||
void initialize() {
|
||||
void initialize() const {
|
||||
pinMode(_battery_data_switch_pin, OUTPUT);
|
||||
digitalWrite(_battery_data_switch_pin, HIGH);
|
||||
analogReadResolution(12);
|
||||
@@ -19,19 +19,21 @@ public:
|
||||
adcAttachPin(_battery_pin);
|
||||
}
|
||||
|
||||
float measureVoltage() {
|
||||
return analogRead(BATTERY_DATA_PIN) * 3.3f / 4096.f;
|
||||
}
|
||||
|
||||
int percent(const float minVoltage = 7.2f, const float maxVoltage = 8.4f,
|
||||
const float r1 = 3.3f, const float r2 = 2.f, const float k = 2.87f) {
|
||||
auto batteryVoltage = measureVoltage() * ((r1 + r2) / k);
|
||||
auto percent = ((batteryVoltage - minVoltage) / (maxVoltage - minVoltage)) * 100;
|
||||
return constrain(round(percent), 0, 100);
|
||||
const float r1 = 3.f, const float r2 = 2.f, const float k = 2.85f) {
|
||||
// It's magic. I will return and refactor it.
|
||||
float pinVoltage = analogReadMilliVolts(_battery_pin) / 1000.f;
|
||||
// k = (r1 + r2) / r2
|
||||
float batteryVoltage = pinVoltage * k;
|
||||
return constrain(_map(batteryVoltage, minVoltage, maxVoltage, 0, 100), 0, 100);
|
||||
}
|
||||
|
||||
private:
|
||||
uint16_t _battery_pin;
|
||||
uint16_t _battery_data_switch_pin;
|
||||
static constexpr const char *_tag = "BatteryController";
|
||||
|
||||
static float _map(float x, float in_min, float in_max, float out_min, float out_max) {
|
||||
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user