User Tools

Site Tools


mmbasic:ina219_current_sensor

INA219 Current Sensor

This is a port of the INA219 Arduino library originally created by K. Townsend (Adafruit Industries) It has been tested on MMBasic v5.04.04. It also includes corrections to the PowerDivider_mW calculation in the calibration routines as well as converts the negative readings (in 2's complement) to positive. The datasheet for the INA219 can be found here.
The INA219 is a very handy little voltage/current/power sensor that communicates via the I2C databus.

I hope you all find it as handy as I have!

GTG!

'INA219 routine

'Code for a Micromite to communicate with a INA219 current sensing module over I2C.

'Original Author:- K. Townsend (Adafruit Industries)

'Ported to MMBasic by GoodToGo!, TBS forums

'**********************************************************************************
'Software License Agreement (BSD License)

'Copyright (c) 2012, Adafruit Industries
'All rights reserved.

'Redistribution and use in source and binary forms, with or without
'modification, are permitted provided that the following conditions are met:
'1. Redistributions of source code must retain the above copyright
'notice, this list of conditions and the following disclaimer.
'2. Redistributions in binary form must reproduce the above copyright
'notice, this list of conditions and the following disclaimer in the
'documentation and/or other materials provided with the distribution.
'3. Neither the name of the copyright holders nor the
'names of its contributors may be used to endorse or promote products
'derived from this software without specific prior written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
'WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
'DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
'DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
'(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
'LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
'ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'**********************************************************************************

option explicit
option default integer

'Select one of the following four possible INA219 I2C Addresses

const INA219_ADDRESS = &h40    	'&b1000000 = (A0,A1=GND)
'const INA219_ADDRESS = &h41  	'&b1000001 = (A0=+V,A1=GND)
'const INA219_ADDRESS = &h44	'&b1000100 = (A0=GND,A1=+V)
'const INA219_ADDRESS = &h45	'&b1000101 = (A0,A1=+V)

'----------------------------------------------------------------
'       Setup Constants associated with INA219
'----------------------------------------------------------------

const INA219_READ =                         &h01

const INA219_REGISTER_CONFIG =              &h00    'Configuration Register (R/W)
const INA219_CONFIG_RESET =                 &h8000  'Reset Bit

const INA219_CONFIG_BVOLTAGERANGE_MASK =    &h2000  'Bus Voltage Range Mask
const INA219_CONFIG_BVOLTAGERANGE_16V =     &h0000  '0-16V Range
const INA219_CONFIG_BVOLTAGERANGE_32V =     &h2000  '0-32V Range

const INA219_CONFIG_GAIN_MASK =             &h1800  'Gain Mask
const INA219_CONFIG_GAIN_1_40MV =           &h0000  'Gain 1, 40mV Range
const INA219_CONFIG_GAIN_2_80MV =           &h0800  'Gain 2, 80mV Range
const INA219_CONFIG_GAIN_4_160MV =          &h1000  'Gain 4, 160mV Range
const INA219_CONFIG_GAIN_8_320MV =          &h1800  'Gain 8, 320mV Range

const INA219_CONFIG_BADCRES_MASK =          &h0780  'Bus Voltage ADC Resolution and Averaging Mask
const INA219_CONFIG_BADCRES_9BIT_1S =       &h0080  '1 x 9-bit bus voltage sample
const INA219_CONFIG_BADCRES_10BIT_1S =      &h0100  '1 x 10-bit bus voltage sample
const INA219_CONFIG_BADCRES_11BIT_1S =      &h0200  '1 x 11-bit bus voltage sample
const INA219_CONFIG_BADCRES_12BIT_1S =      &h0400  '1 x 12-bit bus voltage sample
const INA219_CONFIG_BADCRES_12BIT_2S =      &h0480  '2 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_4S =      &h0500  '4 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_8S =      &h0580  '8 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_16S =     &h0600  '16 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_32S =     &h0680  '32 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_64S =     &h0700  '64 x 12-bit bus voltage samples averaged together
const INA219_CONFIG_BADCRES_12BIT_128S =    &h0780  '128 x 12-bit bus voltage samples averaged together

const INA219_CONFIG_SADCRES_MASK =          &h0078  'Shunt Voltage ADC Resolution and Averaging Mask
const INA219_CONFIG_SADCRES_9BIT_1S =       &h0000  '1 x 9-bit shunt voltage sample
const INA219_CONFIG_SADCRES_10BIT_1S =      &h0008  '1 x 10-bit shunt voltage sample
const INA219_CONFIG_SADCRES_11BIT_1S =      &h0010  '1 x 11-bit shunt voltage sample
const INA219_CONFIG_SADCRES_12BIT_1S =      &h0018  '1 x 12-bit shunt voltage sample
const INA219_CONFIG_SADCRES_12BIT_2S =      &h0048  '2 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_4S =      &h0050  '4 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_8S =      &h0058  '8 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_16S =     &h0060  '16 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_32S =     &h0068  '32 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_64S =     &h0070  '64 x 12-bit shunt voltage samples averaged together
const INA219_CONFIG_SADCRES_12BIT_128S =    &h0078  '128 x 12-bit shunt voltage samples averaged together

const INA219_CONFIG_MODE_MASK =             &h0007  'Operating Mode Mask
const INA219_CONFIG_MODE_POWERDOWN =        &h0000
const INA219_CONFIG_MODE_SVOLT_TRIG =       &h0001
const INA219_CONFIG_MODE_BVOLT_TRIG =       &h0002
const INA219_CONFIG_MODE_SNBVOLT_TRIG =     &h0003
const INA219_CONFIG_MODE_ADCOFF =           &h0004
const INA219_CONFIG_MODE_SVOLT_CONT =       &h0005
const INA219_CONFIG_MODE_BVOLT_CONT =       &h0006
const INA219_CONFIG_MODE_SNBVOLT_CONT =     &h0007

const INA219_REGISTER_SHUNTVOLTAGE =        &h01 'Shunt Voltage Register (R)
const INA219_REGISTER_BUSVOLTAGE =          &h02 'Bus Voltage Register (R)
const INA219_REGISTER_POWER =               &h03 'Power Register (R)
const INA219_REGISTER_CURRENT =             &h04 'Current Register (R)
const INA219_REGISTER_CALIBRATION =         &h05 'Calibration register (R/W)

dim INA219_currentDivider_mA as float
dim INA219_powerDivider_mW as float
dim INA219_calValue

i2c open 100, 100

'----------------------------------------------------------------
'  Select one of the below to set up the Hardware calibration
'----------------------------------------------------------------

setCalibration_32V_2A
'setCalibration_32V_1A
'setCalibration_16V_400mA

'----------------------------------------------------------------
'                   Main Program
'----------------------------------------------------------------

dim shuntvoltage as float
dim busvoltage as float
dim current as float
dim supplyvoltage as float
dim power as float

do
  shuntvoltage = ShuntVoltage_mV()
  busvoltage = BusVoltage_V()
  current = Current_mA()
  supplyvoltage = SupplyVoltage_V()
  power = Power_mW()
  
  print"Bus Voltage:    "+str$(busvoltage)+"V"
  print"Shunt Voltage:  "+str$(shuntvoltage)+"mV"
  print"Supply Voltage: "+str$(supplyvoltage)+"V"
  print"Current:        "+str$(current)+"mA"
  print"Power:          "+str$(power)+"mW"
  print"Calc. Power:    "+str$(busvoltage*current)+"mW"
  print""
  pause 2000
loop

'----------------------------------------------------------------
'                 Calculation Functions
'----------------------------------------------------------------

function BusVoltage_V() as float  'Gets the bus voltage in volts
  Local Value
  ReadRegister (INA219_REGISTER_BUSVOLTAGE, Value)
  Value =((Value >> 3) * 4) 'Shift to right 3 to drop ConversionReady and OverFlow bits, multiply by LSB
  BusVoltage_V = Value / 1000
End Function

function ShuntVoltage_mV() as float 'Gets the shunt voltage in mV
  local Value
  ReadRegister (INA219_REGISTER_SHUNTVOLTAGE, Value)
  If ((Value >> 15) and 1) = 1 then 'Check for negative reading (2’s complement)
     Value = -((Value xor &hffff) + 1)  'Convert negative reading to a negative integer
  endif	
  ShuntVoltage_mV = (Value / 100)
end function

function SupplyVoltage_V() as float 'The Supply voltage is a combination of the Bus voltage and the Shunt voltage
  SupplyVoltage_V = BusVoltage_V() + (ShuntVoltage_mV()/1000)
end function  

function Current_mA() 'Gets the current value in mA
  local Value
  ReadRegister(INA219_REGISTER_CURRENT, Value)
  If ((Value >> 15) and 1) = 1 then 'Check for negative reading (2’s complement)
     Value = -((Value xor &hffff) + 1)  'Convert negative reading to a negative integer	
  endif	
  Current_mA = Value / INA219_currentDivider_mA
end function
  
function Power_mW() 'Gets the power value in mW
  local Value
  ReadRegister (INA219_REGISTER_POWER, Value)
  Power_mW = Value / INA219_powerDivider_mW
end function

'----------------------------------------------------------------
'             I2C read and write routines
'----------------------------------------------------------------

sub ReadRegister (Register, Value)  'Reads a 16 bit value over I2C
  local GetData(1)
  i2c write INA219_ADDRESS, 0, 1, Register
  i2c read INA219_ADDRESS, 0, 2, GetData()
  Value = ((GetData(0) <<8) or GetData(1))
end sub

sub WriteRegister (Register, Value) 'Writes a 16 bit value (2 x 8 bit) in a register over I2C
  local MSB,LSB
  MSB = Value >> 8
  LSB = Value and &hff
  i2c write INA219_ADDRESS, 0, 3, Register, MSB, LSB
end sub

'----------------------------------------------------------------
'               Various calibration routines
'----------------------------------------------------------------

sub setCalibration_32V_2A

  local Config as integer
  
'Configures to INA219 to be able to measure up to 32V and 2A of current.
'Each unit of current corresponds to 100uA, and each unit of power corresponds to 2mW.
'Counter overflow occurs at 3.2A.
'Note: These calculations assume a 0.1 ohm resistor is present
'-------------------------------------------------------------------------------------

  ' By default we use a pretty huge range for the input voltage,
  ' which probably isn't the most appropriate choice for system
  ' that don't use a lot of power.  But all of the calculations
  ' are shown below if you want to change the settings.  You will
  ' also need to change any relevant register settings, such as
  ' setting the VBUS_MAX to 16V instead of 32V, etc.

  ' VBUS_MAX = 32V             (Assumes 32V, can also be set to 16V)
  ' VSHUNT_MAX = 0.32          (Assumes Gain 8, 320mV, can also be 0.16, 0.08, 0.04)
  ' RSHUNT = 0.1               (Resistor value in ohms)
  
  ' 1. Determine max possible current
  ' MaxPossible_I = VSHUNT_MAX / RSHUNT
  ' MaxPossible_I = 3.2A
  
  ' 2. Determine max expected current
  ' MaxExpected_I = 2.0A
  
  ' 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
  ' MinimumLSB = MaxExpected_I/32767
  ' MinimumLSB = 0.000061              (61uA per bit)
  ' MaximumLSB = MaxExpected_I/4096
  ' MaximumLSB = 0.000488              (488uA per bit)
  
  ' 4. Choose an LSB between the min and max values
  '    (Preferrably a roundish number close to MinLSB)
  ' CurrentLSB = 0.0001 (100uA per bit)
  
  ' 5. Compute the calibration register
  ' Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
  ' Cal = 4096 (0x1000)
  
  INA219_calValue = 4096
  
  ' 6. Calculate the power LSB
  ' PowerLSB = 20 * CurrentLSB
  ' PowerLSB = 0.002 (2mW per bit)
  
  ' 7. Compute the maximum current and shunt voltage values before overflow
  '
  ' Max_Current = Current_LSB * 32767
  ' Max_Current = 3.2767A before overflow
  '
  ' If Max_Current > Max_Possible_I then
  '    Max_Current_Before_Overflow = MaxPossible_I
  ' Else
  '    Max_Current_Before_Overflow = Max_Current
  ' End If
  '
  ' Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
  ' Max_ShuntVoltage = 0.32V
  '
  ' If Max_ShuntVoltage >= VSHUNT_MAX
  '    Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
  ' Else
  '    Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
  ' End If
  
  ' 8. Compute the Maximum Power
  ' MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
  ' MaximumPower = 3.2 * 32V
  ' MaximumPower = 102.4W
  
  ' Set multipliers to convert raw current/power values
  INA219_currentDivider_mA = 10  'Current LSB = 100uA per bit (1000/100 = 10)
  INA219_powerDivider_mW = 0.5     'Power LSB = 2mW per bit (1/2)

  ' Set Calibration register to 'Cal' calculated above	
  WriteRegister(INA219_REGISTER_CALIBRATION, INA219_calValue) 
  
  ' Set Config register to take into account the settings above
  Config = INA219_CONFIG_BVOLTAGERANGE_32V or INA219_CONFIG_GAIN_8_320MV or INA219_CONFIG_BADCRES_12BIT_2S
  Config = Config or INA219_CONFIG_SADCRES_12BIT_2S or INA219_CONFIG_MODE_SNBVOLT_CONT
  WriteRegister(INA219_REGISTER_CONFIG, Config)
end sub

sub setCalibration_32V_1A

  local Config as Integer
  
'Configures to INA219 to be able to measure up to 32V and 1A of current.
'Each unit of current corresponds to 40uA, and each unit of power corresponds to 800uW.
'Counter overflow occurs at 1.3A.
'Note: These calculations assume a 0.1 ohm resistor is present
'-------------------------------------------------------------------------------------
  
  ' VBUS_MAX = 32V		(Assumes 32V, can also be set to 16V)
  ' VSHUNT_MAX = 0.32	(Assumes Gain 8, 320mV, can also be 0.16, 0.08, 0.04)
  ' RSHUNT = 0.1			(Resistor value in ohms)

  ' 1. Determine max possible current
  ' MaxPossible_I = VSHUNT_MAX / RSHUNT
  ' MaxPossible_I = 3.2A

  ' 2. Determine max expected current
  ' MaxExpected_I = 1.0A

  ' 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
  ' MinimumLSB = MaxExpected_I/32767
  ' MinimumLSB = 0.0000305             (30.5uA per bit)
  ' MaximumLSB = MaxExpected_I/4096
  ' MaximumLSB = 0.000244              (244uA per bit)

  ' 4. Choose an LSB between the min and max values
  '    (Preferrably a roundish number close to MinLSB)
  ' CurrentLSB = 0.0000400 (40uA per bit)

  ' 5. Compute the calibration register
  ' Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
  ' Cal = 10240 (0x2800)

  INA219_calValue = 10240
  
  ' 6. Calculate the power LSB
  ' PowerLSB = 20 * CurrentLSB
  ' PowerLSB = 0.0008 (800uW per bit)

  ' 7. Compute the maximum current and shunt voltage values before overflow
  '
  ' Max_Current = Current_LSB * 32767
  ' Max_Current = 1.31068A before overflow
  '
  ' If Max_Current > Max_Possible_I then
  '    Max_Current_Before_Overflow = MaxPossible_I
  ' Else
  '    Max_Current_Before_Overflow = Max_Current
  ' End If
  '
  ' ... In this case, we're good though since Max_Current is less than MaxPossible_I
  '
  ' Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
  ' Max_ShuntVoltage = 0.131068V
  '
  ' If Max_ShuntVoltage >= VSHUNT_MAX
  '    Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
  ' Else
  '    Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
  ' End If

  ' 8. Compute the Maximum Power
  ' MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
  ' MaximumPower = 1.31068 * 32V
  ' MaximumPower = 41.94176W

  ' Set multipliers to convert raw current/power values
  INA219_currentDivider_mA = 25  'Current LSB = 40uA per bit (1000/40 = 25)
  INA219_powerDivider_mW = 1.25  'Power LSB = 800uW per bit (1/0.8)

  ' Set Calibration register to 'Cal' calculated above	
  WriteRegister(INA219_REGISTER_CALIBRATION, INA219_calValue) 

  ' Set Config register to take into account the settings above
  Config = INA219_CONFIG_BVOLTAGERANGE_32V or INA219_CONFIG_GAIN_8_320MV or INA219_CONFIG_BADCRES_12BIT_2S
  Config = Config or INA219_CONFIG_SADCRES_12BIT_2S or INA219_CONFIG_MODE_SNBVOLT_CONT
  WriteRegister(INA219_REGISTER_CONFIG, Config)
end sub

sub setCalibration_16V_400mA

  local Config as integer
  
'Calibration which uses the highest precision for current measurement (0.1mA)
'at the expense of only supporting 16V at 400mA max.
'-------------------------------------------------------------------------------------
  
  ' VBUS_MAX = 16V
  ' VSHUNT_MAX = 0.04          (Assumes Gain 1, 40mV)
  ' RSHUNT = 0.1               (Resistor value in ohms)
  
  ' 1. Determine max possible current
  ' MaxPossible_I = VSHUNT_MAX / RSHUNT
  ' MaxPossible_I = 0.4A

  ' 2. Determine max expected current
  ' MaxExpected_I = 0.4A
  
  ' 3. Calculate possible range of LSBs (Min = 15-bit, Max = 12-bit)
  ' MinimumLSB = MaxExpected_I/32767
  ' MinimumLSB = 0.0000122              (12uA per bit)
  ' MaximumLSB = MaxExpected_I/4096
  ' MaximumLSB = 0.0000977              (98uA per bit)
  
  ' 4. Choose an LSB between the min and max values
  '    (Preferrably a roundish number close to MinLSB)
  ' CurrentLSB = 0.00005 (50uA per bit)
  
  ' 5. Compute the calibration register
  ' Cal = trunc (0.04096 / (Current_LSB * RSHUNT))
  ' Cal = 8192 (0x2000)

  INA219_calValue = 8192

  ' 6. Calculate the power LSB
  ' PowerLSB = 20 * CurrentLSB
  ' PowerLSB = 0.001 (1mW per bit)
  
  ' 7. Compute the maximum current and shunt voltage values before overflow
  '
  ' Max_Current = Current_LSB * 32767
  ' Max_Current = 1.63835A before overflow
  '
  ' If Max_Current > Max_Possible_I then
  '    Max_Current_Before_Overflow = MaxPossible_I
  ' Else
  '    Max_Current_Before_Overflow = Max_Current
  ' End If
  '
  ' Max_Current_Before_Overflow = MaxPossible_I
  ' Max_Current_Before_Overflow = 0.4
  '
  ' Max_ShuntVoltage = Max_Current_Before_Overflow * RSHUNT
  ' Max_ShuntVoltage = 0.04V
  '
  ' If Max_ShuntVoltage >= VSHUNT_MAX
  '    Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
  ' Else
  '    Max_ShuntVoltage_Before_Overflow = Max_ShuntVoltage
  ' End If
  '
  ' Max_ShuntVoltage_Before_Overflow = VSHUNT_MAX
  ' Max_ShuntVoltage_Before_Overflow = 0.04V
  
  ' 8. Compute the Maximum Power
  ' MaximumPower = Max_Current_Before_Overflow * VBUS_MAX
  ' MaximumPower = 0.4 * 16V
  ' MaximumPower = 6.4W
  
  ' Set multipliers to convert raw current/power values
  INA219_currentDivider_mA = 20  'Current LSB = 50uA per bit (1000/50 = 20)
  INA219_powerDivider_mW = 1    'Power LSB = 1mW per bit

  ' Set Calibration register to 'Cal' calculated above 
  WriteRegister(INA219_REGISTER_CALIBRATION, INA219_calValue)
  
  ' Set Config register to take into account the settings above
  Config = INA219_CONFIG_BVOLTAGERANGE_16V or INA219_CONFIG_GAIN_1_40MV or INA219_CONFIG_BADCRES_12BIT_2S
  Config = Config or INA219_CONFIG_SADCRES_12BIT_2S or INA219_CONFIG_MODE_SNBVOLT_CONT
  WriteRegister(INA219_REGISTER_CONFIG, Config)
end sub
mmbasic/ina219_current_sensor.txt · Last modified: 2024/02/24 17:34 by gerry