From 2f0027b68b62c2fdfa2ca31c5f6f00232602babb Mon Sep 17 00:00:00 2001 From: Alexander Klein Date: Tue, 21 Feb 2023 11:49:25 +0100 Subject: [PATCH] improve battery tracking --- lib/Battery/battery.cpp | 6 ++++++ lib/Battery/battery.h | 15 +++++++++++++++ src/main.cpp | 8 +++++--- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/Battery/battery.cpp b/lib/Battery/battery.cpp index 3ea195e..1bb1af5 100644 --- a/lib/Battery/battery.cpp +++ b/lib/Battery/battery.cpp @@ -33,6 +33,12 @@ double Battery::getBatteryVoltage() { return (int)(res*100+0.5)/100.0; } +bool Battery::isBatteryLow(uint8_t percent) { + if (this->getBatteryPercent() <= percent && this->batteryVoltage > this->absurdLowVoltage) + return true; + return false; +} + double Battery::readInputVoltage() { // Reference voltage is 3v3 so maximum reading is 3v3 = 4095 in range 0 to 4095 double reading = analogRead(this->pin); diff --git a/lib/Battery/battery.h b/lib/Battery/battery.h index 03911bd..bea1ec5 100644 --- a/lib/Battery/battery.h +++ b/lib/Battery/battery.h @@ -73,13 +73,28 @@ class Battery { */ uint8_t getBatteryPercent() {return this->batteryPercent;} + /** + * @brief Checks if the battery is low. + * + * The function will also return false if the battery voltage is + * absurd low. This is for the case that the uController is powered + * by usb and no battery is connected. + * + * @param percent the limit the battery have to + * @return true if the battery is low + * @return false if the battery is high + */ + bool isBatteryLow(uint8_t percent); + private: double readInputVoltage(); void calculateBatteryVoltage(); void calculateBatteryPercent(); + uint8_t absurdLowVoltage = 5; uint8_t pin; uint8_t batteryPercent; + uint8_t batteryLowPercent = 10; uint16_t delay = 20000; uint32_t r1; uint32_t r2; diff --git a/src/main.cpp b/src/main.cpp index 1680c9a..f4152d7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -142,17 +142,19 @@ void loop() { lcdWrapper->loop(); mainBattery->loop(); - if (mainBattery->getBatteryPercent() <= 10) { + if (mainBattery->isBatteryLow(10)) { moveController.setDrivingStatus(DrivingStatus::stop); moveController.setSpeed(0); moveController.setRotationSpeed(0); + uint16_t voltage = (uint16_t) (mainBattery->getBatteryVoltage() * 100); + lcd->setCursor(0, 0); - lcd->printf("Low Battery..."); + lcd->printf("Low Battery: %u", voltage); lcd->setCursor(0, 1); lcd->print("Please turn off."); - while (1); + while (true); } if (disconnectPs3) {