Skip to content

Commit

Permalink
Update Usermod: Battery
Browse files Browse the repository at this point in the history
Issue:
When taking the initial voltage reading while first powering on, voltage hasn't had chance to stabilize so the reading can be inaccurate, which in turn may incorrectly trigger the low-power preset. (Manifests when the user has selected a low read interval and/or is using a capacitor).

Resolution:
A non-blocking, fixed 10 second delay has been added to the initial voltage reading to give the voltage time to stabilize.
  • Loading branch information
adamsthws committed May 6, 2024
1 parent 197f47b commit d8b76b1
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions usermods/Battery/usermod_v2_Battery.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ class UsermodBattery : public Usermod
unsigned long readingInterval = USERMOD_BATTERY_MEASUREMENT_INTERVAL;
unsigned long nextReadTime = 0;
unsigned long lastReadTime = 0;
// Initial delay before first reading (in milliseconds)
unsigned long initialDelay = 10000;
// Flag to check if the initial delay is completed
bool initialDelayComplete = false;
// Flag to check if the initial reading is complete
bool isFirstReading = true;
// battery min. voltage
float minBatteryVoltage = USERMOD_BATTERY_MIN_VOLTAGE;
// battery max. voltage
Expand Down Expand Up @@ -141,7 +147,6 @@ class UsermodBattery : public Usermod
if (pinManager.allocatePin(batteryPin, false, PinOwner::UM_Battery)) {
DEBUG_PRINTLN(F("Battery pin allocation succeeded."));
success = true;
voltage = readVoltage();
}

if (!success) {
Expand All @@ -152,10 +157,10 @@ class UsermodBattery : public Usermod
}
#else //ESP8266 boards have only one analog input pin A0
pinMode(batteryPin, INPUT);
voltage = readVoltage();
#endif

nextReadTime = millis() + readingInterval;
// Delay the first voltage reading to allow voltage stabilization after powering up
nextReadTime = millis() + initialDelay;
lastReadTime = millis();

initDone = true;
Expand All @@ -182,6 +187,25 @@ class UsermodBattery : public Usermod

lowPowerIndicator();

// Handling the initial delay
if (!initialDelayComplete && millis() < nextReadTime)
return; // Continue to return until the initial delay is over

// Once the initial delay is over, set it as complete
if (!initialDelayComplete)
{
initialDelayComplete = true;
// Set the regular interval after initial delay
nextReadTime = millis() + readingInterval;
}

// Make the first voltage reading once the initial delay has elapsed
if (isFirstReading)
{
voltage = readVoltage();
isFirstReading = false;
}

// check the battery level every USERMOD_BATTERY_MEASUREMENT_INTERVAL (ms)
if (millis() < nextReadTime) return;

Expand Down

0 comments on commit d8b76b1

Please sign in to comment.