11#pragma once
22#include < cstdint>
33#include < drivers/include/nrfx_saadc.h>
4+ #include < array>
5+ #include < numeric>
46
57namespace Pinetime {
68 namespace Controllers {
9+ /* * A simple circular buffer that can be used to average
10+ out the sensor values. The total capacity of the CircBuffer
11+ is given as the template parameter N.
12+ */
13+ template <int N>
14+ class CircBuffer {
15+ public:
16+ CircBuffer () : arr{}, sz{}, cap{N}, head{} {}
17+ /* *
18+ insert member function overwrites the next data to the current
19+ HEAD and moves the HEAD to the newly inserted value.
20+ */
21+ void insert (const int num) {
22+ head %= cap;
23+ arr[head++] = num;
24+ if (sz != cap) {
25+ sz++;
26+ }
27+ }
28+
29+ int GetAverage () const {
30+ int sum = std::accumulate (arr.begin (), arr.end (), 0 );
31+ return (sum / sz);
32+ }
33+
34+ private:
35+ std::array<int , N> arr; /* *< internal array used to store the values*/
36+ uint8_t sz; /* *< The current size of the array.*/
37+ uint8_t cap; /* *< Total capacity of the CircBuffer.*/
38+ uint8_t head; /* *< The current head of the CircBuffer*/
39+ };
40+
741 class Battery {
842 public:
943 void Init ();
1044 void Update ();
11- float PercentRemaining () const { return percentRemaining ; }
45+ int PercentRemaining () const { return percentRemainingBuffer. GetAverage () ; }
1246 float Voltage () const { return voltage; }
1347 bool IsCharging () const { return isCharging; }
1448 bool IsPowerPresent () const { return isPowerPresent; }
@@ -17,8 +51,9 @@ namespace Pinetime {
1751 static constexpr uint32_t chargingPin = 12 ;
1852 static constexpr uint32_t powerPresentPin = 19 ;
1953 static constexpr nrf_saadc_input_t batteryVoltageAdcInput = NRF_SAADC_INPUT_AIN7;
54+ static constexpr uint8_t percentRemainingSamples = 10 ;
2055 static void SaadcEventHandler (nrfx_saadc_evt_t const * p_event);
21- float percentRemaining = 0 . 0f ;
56+ CircBuffer<percentRemainingSamples> percentRemainingBuffer {} ;
2257 float voltage = 0 .0f ;
2358 bool isCharging = false ;
2459 bool isPowerPresent = false ;
0 commit comments