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
-
Enable I2C Interface on Raspberry Pi:
- Input command to the terminal:
sudo raspi-config - Select Interfacing Options (or Advanced Options) → I2C → Yes → OK




- Reboot Raspberry Pi using the command:
reboot
- Input command to the terminal:
-
Verify I2C Interface:
-
Check if I2C is enabled using
lsmod
-
Install
i2c-toolswith:sudo apt-get install i2c-tools -
Test I2C with:
sudo i2cdetect -y 1
-
-
Troubleshoot I2C Detection:
If a problem like this appeared:

Then change raspi-blacklist.conf configuration, raspi-blacklist.conf is under /etc/modprobe.d/ directory, input command:
sudo nano /etc/modprobe.d/raspi-blacklist.confAdd “#” 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?
