2016-12-20 21:09:01 +00:00
|
|
|
'''
|
|
|
|
Created on Dec 19, 2016
|
|
|
|
|
|
|
|
@author: klaehn
|
|
|
|
'''
|
|
|
|
import smbus
|
|
|
|
|
|
|
|
class PowerSensor(object):
|
|
|
|
'''
|
|
|
|
Power sensor wrapper
|
|
|
|
'''
|
|
|
|
def __init__(self, bus = 1, addr = 0x40):
|
|
|
|
self.__bus = smbus.SMBus(bus)
|
|
|
|
self.__addr = addr
|
|
|
|
|
|
|
|
value = [(0x1000 >> 8) & 0xFF, 0x1000 & 0xFF]
|
|
|
|
self.__bus.write_i2c_block_data(self.__addr, 0x05, value)
|
|
|
|
config = 0x2000 | 0x1800 | 0x0400 | 0x0018 | 0x0007
|
|
|
|
value = [(config >> 8) & 0xFF, config & 0xFF]
|
|
|
|
self.__bus.write_i2c_block_data(self.__addr, 0x00, value)
|
|
|
|
|
|
|
|
def shunt_voltage_mv(self):
|
|
|
|
''' Read the voltage at the shunt resistor [mV] '''
|
|
|
|
data = self.__bus.read_i2c_block_data(self.__addr, 0x01)
|
|
|
|
voltage = data[0] * 256 + data[1]
|
|
|
|
return voltage * 0.01
|
|
|
|
|
|
|
|
def current_ma(self):
|
|
|
|
''' Read the current [mA] '''
|
|
|
|
data = self.__bus.read_i2c_block_data(self.__addr, 0x04)
|
|
|
|
if data[0] >> 7 == 1:
|
|
|
|
current = data[0] * 256 + data[1]
|
|
|
|
if current & (1 << 15):
|
|
|
|
current = current - (1 << 16)
|
|
|
|
else:
|
|
|
|
current = (data[0] << 8) | (data[1])
|
|
|
|
return current / 10
|
|
|
|
|
|
|
|
def power_mw(self):
|
|
|
|
''' Read the power [mW] '''
|
|
|
|
data = self.__bus.read_i2c_block_data(self.__addr, 0x03)
|
|
|
|
if data[0] >> 7 == 1:
|
|
|
|
power = data[0] * 256 + data[1]
|
|
|
|
if power & (1 << 15):
|
|
|
|
power = power - (1 << 16)
|
|
|
|
else:
|
|
|
|
power = (data[0] << 8) | (data[1])
|
|
|
|
return power / 2
|