# Calculate battery percentage remaining

Posted on
• I've got an MDBT42Q connected to a LiPo battery. Is there any way to calculate the percentage of the battery that's remaining? The build-in function only works for Puck, Pixl and Bangle.

Can I do something similar to what they have?

``````JsVarInt jswrap_puck_getBattery() {
int pc = (v-2.2)*100/0.6;
if (pc>100) pc=100;
if (pc<0) pc=0;
return pc;
}
``````

Thanks.

• The MDBT42Q breakout?

Unfortunately the problem is it's connected to a voltage regulator, so it only 'sees' the regulated voltage. You'll be able to use code like that to see when the voltage starts to drop from 3.3v (meaning the LiPo voltage is near or below that), but by that time the battery is only 10% full or so.

Best bet is to add two 1MOhm resistors to the battery voltage to create a 'potential divider', then feed the new (halved) voltage into an analog pin - and then you can use some code a bit like you posted (even in JS) to work out how much battery is left

• Thanks... I was wondering which 'side' the battery level would be reading if I connect to 12v leisure battery (ie unregulated).

I'm going to build a simple campervan battery monitor when I receive my pixl.js.

• Thanks. Yes, I'm using the breakout board.

So, with the potential divider, you're just measuring the voltage of the battery? What's the difference between that and using `NRF.getBattery()`?

• Hmm. `NRF.getBattery()` says 3.27 for my LiPo, but my voltmeter says 4.08.

• I think Gordon already mentioned this:

The MDBT42Q breakout?

Unfortunately the problem is it's connected to a voltage regulator, so it only 'sees' the regulated voltage. You'll be able to use code like that to see when the voltage starts to drop from 3.3v (meaning the LiPo voltage is near or below that), but by that time the battery is only 10% full or so.

`NRF.getBattery()` measures the voltage of the immediate source, which in your case is coming from the linear regulator which would then produce 3v3 for voltages higher than 3v3 (like your lipo for example).

How do I measure battery voltage on devices that don't have E.getBattery?

• @parasquid thanks for explaining that. I totally missed it, somehow.

I guess I need to find those parts for the potential divider. I'll report back if I get something working...

• You can also refer to http://forum.espruino.com/conversations/­353421 which is similar to your issue. I would again recommend the INA219 or INA226 for voltage detection if you're not familiar with voltage dividers, because there is a big risk of you frying your device if you mess up the voltages.

At least with the INA219/INA226 they're cheap so even if you fry them they don't cost that much :P