Skip to content

Commit 9925e5b

Browse files
committed
fix: battery percentage showing unavailable when fully charged
When battery voltage slightly exceeds 4.2V (e.g., 4.25V when fully charged), the previous code returned NAN, causing HA to display 'unavailable'. Now only return NAN for truly invalid readings (voltage < 2.75V or NaN). Voltage above 4.2V will correctly show 100% instead of unavailable.
1 parent 8b12492 commit 9925e5b

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

arduino/SeeedHADiscovery/examples/IoTButtonV2_DeepSleep/IoTButtonV2_DeepSleep.ino

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -463,11 +463,21 @@ float readBatteryVoltage() {
463463
* Calculate battery percentage from voltage
464464
* 从电压计算电池百分比
465465
* Formula: percentage = ((voltage - 2.75) / (4.2 - 2.75)) * 100
466+
*
467+
* Note: When fully charged, voltage may slightly exceed 4.2V (e.g., 4.25V).
468+
* We should return 100% instead of NAN in this case.
469+
* 注意:充满电时,电压可能略微超过 4.2V(如 4.25V)。
470+
* 此时应返回 100% 而不是 NAN。
466471
*/
467472
float calculateBatteryPercentage(float voltage) {
468-
if (isnan(voltage) || voltage < BATTERY_VOLTAGE_MIN || voltage > BATTERY_VOLTAGE_MAX) {
473+
// Only return NAN for invalid readings (too low or not a number)
474+
// 仅对无效读数返回 NAN(过低或非数字)
475+
if (isnan(voltage) || voltage < BATTERY_VOLTAGE_MIN) {
469476
return NAN;
470477
}
478+
479+
// Calculate percentage and clamp to 0-100 range
480+
// 计算百分比并限制在 0-100 范围内
471481
float percentage = ((voltage - BATTERY_VOLTAGE_MIN) / (BATTERY_VOLTAGE_MAX - BATTERY_VOLTAGE_MIN)) * 100.0f;
472482
return constrain(percentage, 0.0f, 100.0f);
473483
}

0 commit comments

Comments
 (0)