36 lines
1.2 KiB
C++
36 lines
1.2 KiB
C++
// This is a personal academic project. Dear PVS-Studio, please check it.
|
|
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: https://pvs-studio.com
|
|
|
|
#include "board_pins.h"
|
|
|
|
class BatteryController {
|
|
public:
|
|
BatteryController(const uint16_t batteryPin, const uint16_t battery_data_switch_pin) {
|
|
_battery_pin = batteryPin;
|
|
_battery_data_switch_pin = battery_data_switch_pin;
|
|
}
|
|
|
|
void initialize() {
|
|
pinMode(_battery_data_switch_pin, OUTPUT);
|
|
digitalWrite(_battery_data_switch_pin, HIGH);
|
|
analogReadResolution(12);
|
|
analogSetWidth(12);
|
|
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);
|
|
}
|
|
|
|
private:
|
|
uint16_t _battery_pin;
|
|
uint16_t _battery_data_switch_pin;
|
|
static constexpr const char *_tag = "BatteryController";
|
|
}; |