Clear all

[Solved] Get Battery voltage in Python? (Witty Pi 4 L3V7)

3 Posts
3 Users
Posts: 1
New Member
Topic starter

I have a wittypy4 l3.7
Is there any way to get the battery voltage in a python program?



Posted : 07/11/2023 7:28 am
Posts: 145
Member Admin

The VIN on Witty Pi 4 L3V7 is close to what you need, but it is not always the battery voltage. 

If USB power is connected, the VIN equals to 5V (from USB power) minus the voltage drop on an diode. When USB power is remove, the VIN is the battery voltage. Although not 100% sure, you can still tell by seeing the voltage value, if it is higher than 4.2V, then most probably it is the voltage from USB power.

With that said, it is impossible to know the battery voltage when USB power is connected.

VIN can be obtained from two I2C registers, and you can port the get_input_voltage function (written in BASH) to Python.

Posted : 07/11/2023 1:45 pm
Posts: 7
Active Member

I used this code to read the battery voltage on the witty pi 4 using the bash script. Should be similar/identical for the l3v7:

# Battery voltage
def get_battery_voltage_witty_pi_4():
    '''Gets the battery voltage reading from the Witty Pi 4 in V'''
        command = "cd /home/pi/wittypi && . ./ && get_input_voltage"
        battery_voltage = check_output(command, shell=True, executable="/bin/bash", stderr=STDOUT, universal_newlines=True, timeout=5)
        battery_voltage = battery_voltage.replace("\n", "")
        print(f"Battery voltage: {battery_voltage} V")
        return battery_voltage
    except Exception as e:
        print(f"Could not get battery voltage: {str(e)}")
        return "-"
Posted : 12/11/2023 12:15 pm