Skip to content

Commit 444a74d

Browse files
committed
nicla-system: Improve efficiency of voltage calculation.
1 parent d69d3ad commit 444a74d

File tree

1 file changed

+8
-12
lines changed

1 file changed

+8
-12
lines changed

libraries/Nicla_System/src/Nicla_System.cpp

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -159,17 +159,13 @@ float nicla::getRegulatedBatteryVoltage(){
159159

160160
// Read the Battery Voltage Control Register that holds the regulated battery voltage
161161
uint8_t data = _pmic.readByte(BQ25120A_ADDRESS, BQ25120A_BATTERY_CTRL);
162-
int milliVolts = 360; // 3.6V is the minimum voltage
163-
164-
// Loop through bits 1-7. LSB is bit 0 and it's not used
165-
for (int i = 1; i <= 7; ++i) {
166-
if (data & (1 << i)) {
167-
int addition = 1 << (i - 1); // 2^(i-1): 10, 20, 40, 80, 160, 320, 640 mV
168-
milliVolts += addition;
169-
}
170-
}
162+
int milliVolts = 3600; // 3.6V is the minimum voltage
163+
164+
// Shift the data to the right by 1 bit to remove the LSB that is not used.
165+
uint8_t shiftedData = (data >> 1) & 0b01111111;
166+
milliVolts += shiftedData * 10;
171167

172-
return milliVolts / 100.0f;
168+
return milliVolts / 1000.0f;
173169

174170
}
175171

@@ -197,9 +193,9 @@ void nicla::setRegulatedBatteryVoltage(float voltage){
197193
+---------+--------------------+
198194
*/
199195

196+
uint16_t voltageAddition = (voltage - 3.6f) * 100;
200197
// Shift one bit to the left because the LSB is not used.
201-
uint16_t additionalMilliVolts = (voltage - 3.6f) * 100;
202-
uint8_t value = additionalMilliVolts << 1;
198+
uint8_t value = voltageAddition << 1;
203199
// e.g. 4.2V - 3.6V = 0.6V * 100 = 60. 60 << 1 = 120 = 01111000
204200

205201
_pmic.writeByte(BQ25120A_ADDRESS, BQ25120A_BATTERY_CTRL, value);

0 commit comments

Comments
 (0)