11#include " BatteryController.h"
22#include < hal/nrf_gpio.h>
33#include < nrfx_saadc.h>
4- #include < libraries/log/nrf_log.h>
54#include < algorithm>
6- #include < math.h>
75
86using namespace Pinetime ::Controllers;
97
@@ -18,7 +16,6 @@ void Battery::Init() {
1816}
1917
2018void Battery::Update () {
21-
2219 isCharging = !nrf_gpio_pin_read (chargingPin);
2320 isPowerPresent = !nrf_gpio_pin_read (powerPresentPin);
2421
@@ -32,13 +29,13 @@ void Battery::Update() {
3229 nrfx_saadc_sample ();
3330}
3431
35- void Battery::adcCallbackStatic (nrfx_saadc_evt_t const * event) {
32+ void Battery::AdcCallbackStatic (nrfx_saadc_evt_t const * event) {
3633 instance->SaadcEventHandler (event);
3734}
3835
3936void Battery::SaadcInit () {
4037 nrfx_saadc_config_t adcConfig = NRFX_SAADC_DEFAULT_CONFIG;
41- APP_ERROR_CHECK (nrfx_saadc_init (&adcConfig, adcCallbackStatic ));
38+ APP_ERROR_CHECK (nrfx_saadc_init (&adcConfig, AdcCallbackStatic ));
4239
4340 nrf_saadc_channel_config_t adcChannelConfig = {.resistor_p = NRF_SAADC_RESISTOR_DISABLED,
4441 .resistor_n = NRF_SAADC_RESISTOR_DISABLED,
@@ -54,7 +51,6 @@ void Battery::SaadcInit() {
5451}
5552
5653void Battery::SaadcEventHandler (nrfx_saadc_evt_t const * p_event) {
57-
5854 const uint16_t battery_max = 4180 ; // maximum voltage of battery ( max charging voltage is 4.21 )
5955 const uint16_t battery_min = 3200 ; // minimum voltage of battery before shutdown ( depends on the battery )
6056
@@ -69,10 +65,13 @@ void Battery::SaadcEventHandler(nrfx_saadc_evt_t const* p_event) {
6965 // p_event->data.done.p_buffer[0] = (adc_voltage / reference_voltage) * 1024
7066 voltage = p_event->data .done .p_buffer [0 ] * 6000 / 1024 ;
7167
72- percentRemaining = (voltage - battery_min) * 100 / (battery_max - battery_min);
73-
74- percentRemaining = std::max (percentRemaining, 0 );
75- percentRemaining = std::min (percentRemaining, 100 );
68+ if (voltage > battery_max) {
69+ percentRemaining = 100 ;
70+ } else if (voltage < battery_min) {
71+ percentRemaining = 0 ;
72+ } else {
73+ percentRemaining = (voltage - battery_min) * 100 / (battery_max - battery_min);
74+ }
7675
7776 nrfx_saadc_uninit ();
7877 isReading = false ;
0 commit comments