How to Measure Battery Voltage?

Hello,

I would like to learn how to measure the remaining battery charge using GPIO28.

I have tried reading the value on GPIO28 but I may not be doing this correctly and I am also not sure how to convert reading this to the correct voltage using the XRP controller board.

My attempt is below.

from XRPLib.defaults import *
from machine import Pin, ADC
from time import sleep

pinVin = ADC(Pin(28))

while True:
  voltage = (pinVin.read_u16()/65535)  # am unsure about this calculation 
  print(voltage)
  sleep(0.5)

Thanks in advance for any advice/assistance.

You’re close! 2 things you need to add:

  1. Multiply by the reference voltage, which is 3.3V
  2. Multiply by the voltage divider ratio, which is about 4
    1. If you look at the XRP Control Board schematic, the “VIN Measurement” section in the middle includes a voltage divider circuit (just 2 resistors) to allow measurements above 3.3V. Because a 100k and 33k resistors are used, the output voltage is (100 + 33) / 33 = 4.030303... times smaller than the input voltage (4.030303… is close enough to 4 for me :wink:)

So just need to do:

voltage = (pinVin.read_u16() / 65535 * 3.3 * 4)

Note that due to imperfections of the ADC on the XRP, the measured voltage may fluctuate a little, and it may not be exactly the same as what your voltmeter measures.

I’ve also put a feature request into XRPLib for a pre-defined get_input_voltage() function to be added, hopefully we’ll see that in the future!

Hope this helps!

1 Like

Brilliant!

Thanks for taking the time to post such a detailed answer, much appreciated.

1 Like