Example Code for Raspberry Pi-Check UPS Battery Percentage

Last revision 2026/01/06

This article explains how to check the UPS battery percentage using Raspberry Pi with a detailed guide on hardware setup, enabling I2C interface, and executing Python sample code for monitoring battery capacity and percentage.

Hardware Preparation

Wiring Operation

Connect the DFRobot Raspberry Pi UPS HAT to the Raspberry Pi via the 40-pin GPIO socket. Ensure the UPS HAT is properly aligned with the Raspberry Pi's GPIO header.

Other Preparation Work

  1. Enable I2C Interface on Raspberry Pi:

    1. Input command to the terminal: sudo raspi-config
    2. Select Interfacing Options (or Advanced Options) → I2CYesOK
      Enable I2C Interface1
      Enable I2C Interface2
      Enable I2C Interface3
      Enable I2C Interface4
    3. Reboot Raspberry Pi using the command: reboot
  2. Verify I2C Interface:

    1. Check if I2C is enabled using lsmod

      Ismod

    2. Install i2c-tools with:

      sudo apt-get install i2c-tools
      
    3. Test I2C with:

      sudo i2cdetect -y 1
      
  3. Troubleshoot I2C Detection:

    If a problem like this appeared:
    problem

    Then change raspi-blacklist.conf configuration, raspi-blacklist.conf is under /etc/modprobe.d/ directory, input command:

    sudo nano /etc/modprobe.d/raspi-blacklist.conf
    

    Add “#” to i2c device driver, such as:#blacklist i2c-bcm2835. Now I2C interface is enabled.

Sample Code

Create ups.py file, and input the following the content:

import smbus
addr=0x10 #ups i2c address
bus=smbus.SMBus(1) #i2c-1
vcellH=bus.read_byte_data(addr,0x03)
vcellL=bus.read_byte_data(addr,0x04)
socH=bus.read_byte_data(addr,0x05)
socL=bus.read_byte_data(addr,0x06)

capacity=(((vcellH&0x0F)<<8)+vcellL)*1.25 #capacity
electricity=((socH<<8)+socL)*0.003906 #current electric quantity percentage

print("capacity=%dmV"%capacity)
print("electricity percentage=%.2f"%electricity)

Result

Run the script using python3 ups.py in the terminal. The output will display:

  • capacity=XXXXmV (battery voltage in millivolts)
  • electricity percentage=XX.XX (current battery percentage, rounded to two decimal places)

Was this article helpful?

TOP