-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatteryMonitor.cpp
More file actions
68 lines (57 loc) · 2.63 KB
/
BatteryMonitor.cpp
File metadata and controls
68 lines (57 loc) · 2.63 KB
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
63
64
65
66
67
68
/*
* MotionHub project
* Copyright (c) 2026 Fedir Vilhota <fredy31415@gmail.com>
* This software is released under the MIT License.
* See the LICENSE file in the project root for full license information.
*/
#include "BatteryMonitor.h"
BatteryMonitor::BatteryMonitor(uint8_t pin, float dividerMultiplier, float referenceVoltage, int adcResolution, float criticalVoltage)
: _pin(pin), _dividerMultiplier(dividerMultiplier), _referenceVoltage(referenceVoltage), _adcResolution(adcResolution), _criticalVoltage(criticalVoltage), _lastReadTime(0), _lastVoltage(0.0), _isFirstRead(true) {
}
void BatteryMonitor::begin() {
pinMode(_pin, INPUT);
// Робимо перший симулятивний апдейт відразу, щоб перевірити напругу
update(true);
}
void BatteryMonitor::update(bool force) {
unsigned long currentMillis = millis();
// Перевіряємо, чи пройшла 1 секунда (1000 мс) або це виклик force
if (force || currentMillis - _lastReadTime >= 1000) {
_lastReadTime = currentMillis;
// Робимо 5 швидких замірів
uint16_t readings[5];
for (int i = 0; i < 5; i++) {
readings[i] = analogRead(_pin);
}
// Сортуємо масив для знаходження медіани
bubbleSort(readings, 5);
uint16_t medianReading = readings[2]; // 3-й елемент у відсортованому масиві з 5 елементів
// Розраховуємо напругу
_lastVoltage = ((float)medianReading / _adcResolution) * _referenceVoltage * _dividerMultiplier;
// Виводимо в Serial
Serial.print("[BatteryMonitor] Level: ");
Serial.print(_lastVoltage);
Serial.println(" V");
// Перевіряємо напругу на критичний рівень (лише виводимо в лог, якщо треба)
if (_lastVoltage > 1.0 && _lastVoltage < _criticalVoltage) {
Serial.println("[BatteryMonitor] Critical voltage level detected!");
}
}
}
float BatteryMonitor::getVoltage() {
return _lastVoltage;
}
bool BatteryMonitor::isCritical() {
return (_lastVoltage > 1.0 && _lastVoltage < _criticalVoltage);
}
void BatteryMonitor::bubbleSort(uint16_t arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
uint16_t temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}