forked from leeseungcheol/ODROID-GO
-
Notifications
You must be signed in to change notification settings - Fork 36
/
battery.cpp
63 lines (49 loc) · 1.44 KB
/
battery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* battery.cpp
*
* Created on: 5 de jul de 2018
* Author: mdrjr
*/
#include <esp_sleep.h>
#include "battery.h"
Battery::Battery() {
this->_enable_protection = false;
}
void Battery::begin() {
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_0, ADC_ATTEN_DB_11);
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, ESP_ADC_CAL_VAL_EFUSE_TP, &_adc_chars);
}
double Battery::getVoltage() {
uint32_t adc_reading = 0;
for (int i = 0; i < BATTERY_SAMPLES; i++) {
adc_reading += adc1_get_raw((adc1_channel_t) ADC1_CHANNEL_0);
}
adc_reading /= BATTERY_SAMPLES;
return (double) esp_adc_cal_raw_to_voltage(adc_reading, &_adc_chars) * BATTERY_RESISTANCE_NUM / 1000;
}
int Battery::getPercentage() {
int voltage_by_100 = (int)(getVoltage() * 100);
if(voltage_by_100 > BATTERY_VMAX) {
return 100;
} else if(voltage_by_100 < BATTERY_VMIN) {
return 0;
} else {
int res = 101 - (101 / pow(1 + pow(1.33 * (voltage_by_100 - BATTERY_VMIN)/(BATTERY_VMAX - BATTERY_VMIN), 4.5), 3));
if(res > 100)
res = 100;
return res;
}
}
void Battery::setProtection(bool enable) {
this->_enable_protection = enable;
}
void Battery::update() {
if(this->_enable_protection == true) {
int curr_voltage = (int)(getVoltage() * 100);
if(curr_voltage <= BATTERY_CUTOFF) {
esp_deep_sleep(30 * 60 * 1000000);
esp_deep_sleep_start();
}
}
}