#!/usr/bin/env python3 from smbus2 import SMBus from time import sleep ADDRESS = 0x40 CURRENT_LSB = 0.00032 VBUS_LSB = 0.00125 SHUNT_LSB = 0.0000025 class Data: current = 0.0 voltage = 0.0 voltageCorrected = 0.0 power = 0.0 powerCorrected = 0.0 def readReg(bus, reg): regWord = bus.read_word_data(ADDRESS, reg) & 0xFFFF regValue = ((regWord << 8) & 0xFF00) + (regWord >> 8) #print(f'{bin(regWord)}\t{bin(regValue)}') return regValue def writeReg(bus, reg, val): regBytes = [(val >> 8) & 0xFF,val & 0xFF] print(regBytes) bus.write_i2c_block_data(ADDRESS, reg, regBytes) def getData(bus): powerData.current = float(readReg(bus, 0x04)) * CURRENT_LSB powerData.voltage = float(readReg(bus, 0x02)) * VBUS_LSB powerData.voltageCorrected = powerData.voltage / 1.04982 powerData.power = float(readReg(bus, 0x03)) * CURRENT_LSB * 25.0 powerData.powerCorrected = powerData.current * powerData.voltageCorrected with SMBus(1) as bus: powerData = Data() # program calibration register # calibration for double pink: 0x0b60 # cal for pink/blue: 0x08b6 writeReg(bus, 0x05, 0x08b6) sleep(2) while True: print("\033c") getData(bus) #print(f"Vshunt:\t\t{float(readReg(bus, 0x01))*SHUNT_LSB} V") print(f"Vbus:\t\t{powerData.voltage} V") #print(f"VbusC:\t\t{powerData.voltageCorrected} V") print(f"Current:\t{powerData.current} A") print(f"Power:\t\t{powerData.power} W") #print(f"PowerC:\t\t{powerData.powerCorrected} W") #print(hex(readReg(bus, 0x05))) print() sleep(1) # Calibration Calculations # Max of 10A (for solar panel out) # Current_LSB = 10A / 2^15 = 3.0517... uA/bit # go with 320 uA/bit = 0.32 mA/bit # # Shunt resistor value # R_shunt = 5 mOhms = 0.005 Ohms # # Calibration Register # CAL = 0.00512 / (Current_LSB * R_shunt) = 0.00512 / (.00032 * .005) = 3200 # CAL = 0x0C80