Skip to content

Commit c08b719

Browse files
committed
nicla-system: Improve efficiency of voltage calculation.
1 parent 3d89939 commit c08b719

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
@@ -162,17 +162,13 @@ float nicla::getRegulatedBatteryVoltage(){
162162

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

175-
return milliVolts / 100.0f;
171+
return milliVolts / 1000.0f;
176172

177173
}
178174

@@ -200,9 +196,9 @@ void nicla::setRegulatedBatteryVoltage(float voltage){
200196
+---------+--------------------+
201197
*/
202198

199+
uint16_t voltageAddition = (voltage - 3.6f) * 100;
203200
// Shift one bit to the left because the LSB is not used.
204-
uint16_t additionalMilliVolts = (voltage - 3.6f) * 100;
205-
uint8_t value = additionalMilliVolts << 1;
201+
uint8_t value = voltageAddition << 1;
206202
// e.g. 4.2V - 3.6V = 0.6V * 100 = 60. 60 << 1 = 120 = 01111000
207203

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

0 commit comments

Comments
 (0)