# This example shows how to read the voltage from a LiPo battery connected to a Raspberry Pi Pico via our Pico Lipo SHIM # and uses this reading to calculate how much charge is left in the battery. # It then displays the info on the screen of Pico Display. # Remember to save this code as main.py on your Pico if you want it to run automatically! from machine import ADC, Pin, I2C import time from sh1106 import SH1106_I2C i2c = I2C(1, scl=27,sda=26) oled = SH1106_I2C(128, 64, i2c) oled.rotate(True) vsys = ADC(29) # reads the system input voltage charging = Pin(24 , Pin.IN) # reading GP24 tells us whether or not USB power is connected #plugged = Pin('WL_GPIO2', Pin.IN) conversion_factor = 3 * 3.3 / 65535 full_battery = 4.3 # these are our reference voltages for a full/empty battery, in volts empty_battery = 3.0 # the values could vary by battery size/manufacturer so you might need to adjust them while True: # convert the raw ADC read into a voltage, and then a percentage voltage = vsys.read_u16() * conversion_factor percentage = 100 * ((voltage - empty_battery) / (full_battery - empty_battery)) if charging.value() == 1: # if plugged.value() == 1: # if it's plugged into USB power... print("--- Charging! --") print('{:.2f}'.format(voltage) + "v") print('{:.0f}%'.format(percentage)) oled.fill(0) oled.text("--- Charging! --", 0, 2) oled.hline(0, 12, 128, 10) oled.text("V: " + str(voltage), 5, 25) oled.text("%: " + str(percentage), 5, 35) oled.show() time.sleep(2) else: # if not, display the battery stats print('{:.2f}'.format(voltage) + "v") print('{:.0f}%'.format(percentage)) oled.fill(0) oled.text("V: " + str(voltage), 0, 10) oled.text("%: " + str(percentage), 0, 30) oled.show() time.sleep(2)