Example Code for Raspberry Pi-Read Electric Quantity

Last revision 2026/01/06

This article guides users through the process of reading electric quantities using a Raspberry Pi with DFR0528 UPS HAT. It details the necessary hardware setup, enabling the I2C interface, troubleshooting common issues, and provides sample Python code for execution. Users can easily measure battery voltage and electric quantity percentage with the provided instructions.

Hardware Preparation

Wiring Operation

Connect the DFR0528 UPS HAT to the Raspberry Pi by aligning and inserting it into the Raspberry Pi's 40Pin GPIO socket. No additional wiring is required for basic functionality.

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