Home

Awesome

Raspberry Pi Python Library for Voltage and Current Sensors Using the INA219

Build

codecov

PyPI version

This Python library supports the INA219 voltage, current and power monitor sensor from Texas Instruments on Python 3. The intent of the library is to make it easy to use the quite complex functionality of this sensor.

The library currently only supports continuous reads of voltage and power, but not triggered reads.

The library supports the detection of overflow in the current/power calculations which results in meaningless values for these readings.

The low power mode of the INA219 is supported, so if only occasional reads are being made in a battery based system, current consumption can be minimised.

The library has been tested with the Adafruit INA219 Breakout.

Installation and Upgrade

This library and its dependency (Adafruit GPIO library) can be installed from PyPI by executing:

sudo pip3 install pi-ina219

To upgrade from a previous version installed direct from Github execute:

sudo pip3 uninstall pi-ina219
sudo pip3 install pi-ina219

The Adafruit library supports the I2C protocol on all versions of the Raspberry Pi. Remember to enable the I2C bus under the Advanced Options of raspi-config.

Usage

The address of the sensor unless otherwise specified is the default of 0x40.

Note that the bus voltage is that on the load side of the shunt resistor, if you want the voltage on the supply side then you should add the bus voltage and shunt voltage together, or use the supply_voltage() function.

I2C Bus number

In most cases this will be determined automatically, however if this fails you will see the exception:

Could not determine default I2C bus for platform

In this case just set the bus number in the INA219 constructor, for example:

ina = INA219(SHUNT_OHMS, busnum=1)

This is known to be required with Raspberry Pi 4 and the 'Bullseye' (October 2021) Raspberry Pi OS.

Simple - Auto Gain

This mode is great for getting started, as it will provide valid readings until the device current capability is exceeded for the value of the shunt resistor connected (3.2A for 0.1Ω shunt resistor). It does this by automatically adjusting the gain as required until the maximum is reached, when a DeviceRangeError exception is thrown to avoid invalid readings being taken.

The downside of this approach is reduced current and power resolution.

#!/usr/bin/env python
from ina219 import INA219
from ina219 import DeviceRangeError

SHUNT_OHMS = 0.1


def read():
    ina = INA219(SHUNT_OHMS)
    ina.configure()

    print("Bus Voltage: %.3f V" % ina.voltage())
    try:
        print("Bus Current: %.3f mA" % ina.current())
        print("Power: %.3f mW" % ina.power())
        print("Shunt voltage: %.3f mV" % ina.shunt_voltage())
    except DeviceRangeError as e:
        # Current out of device range with specified shunt resistor
        print(e)


if __name__ == "__main__":
    read()

Advanced - Auto Gain, High Resolution

In this mode by understanding the maximum current expected in your system and specifying this in the script you can achieve the best possible current and power resolution. The library will calculate the best gain to achieve the highest resolution based on the maximum expected current.

In this mode if the current exceeds the maximum specified, the gain will be automatically increased, so a valid reading will still result, but at a lower resolution.

As above when the maximum gain is reached, an exception is thrown to avoid invalid readings being taken.

#!/usr/bin/env python
from ina219 import INA219
from ina219 import DeviceRangeError

SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2


def read():
    ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS)
    ina.configure(ina.RANGE_16V)

    print("Bus Voltage: %.3f V" % ina.voltage())
    try:
        print("Bus Current: %.3f mA" % ina.current())
        print("Power: %.3f mW" % ina.power())
        print("Shunt voltage: %.3f mV" % ina.shunt_voltage())
    except DeviceRangeError as e:
        # Current out of device range with specified shunt resistor
        print(e)


if __name__ == "__main__":
    read()

Advanced - Manual Gain, High Resolution

In this mode by understanding the maximum current expected in your system and specifying this and the gain in the script you can always achieve the best possible current and power resolution, at the price of missing current and power values if a current overflow occurs.

#!/usr/bin/env python
from ina219 import INA219
from ina219 import DeviceRangeError

SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.2


def read():
    ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS)
    ina.configure(ina.RANGE_16V, ina.GAIN_1_40MV)

    print("Bus Voltage: %.3f V" % ina.voltage())
    try:
        print("Bus Current: %.3f mA" % ina.current())
        print("Power: %.3f mW" % ina.power())
        print("Shunt voltage: %.3f mV" % ina.shunt_voltage())
    except DeviceRangeError as e:
        print("Current overflow")


if __name__ == "__main__":
    read()

Sensor Address

The sensor address may be altered as follows:

ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, address=0x41)

Low Power Mode

The sensor may be put in low power mode between reads as follows:

ina.configure(ina.RANGE_16V)
while True:
    print("Voltage : %.3f V" % ina.voltage())
    ina.sleep()
    time.sleep(60)
    ina.wake()

Note that if you do not wake the device after sleeping, the value returned from a read will be the previous value taken before sleeping.

Functions

Performance

On a Raspberry Pi 2 Model B running Raspbian Jesse and reading a 12-bit voltage in a loop, a read occurred approximately every 10 milliseconds.

On a Raspberry Pi 4 running Raspbian Buster a read occurred approximately every 570 microseconds.

Debugging

To understand the calibration calculation results and automatic gain increases, informational output can be enabled with:

    ina = INA219(SHUNT_OHMS, log_level=logging.INFO)

Detailed logging of device register operations can be enabled with:

    ina = INA219(SHUNT_OHMS, log_level=logging.DEBUG)

Testing

Install the library as described above, this will install all the dependencies required for the unit tests, as well as the library itself. Clone the library source from Github then execute the test suite from the top level directory with:

python3 -m unittest discover -s tests -p 'test_*.py'

A single unit test class may be run as follows:

python3 -m unittest tests.test_configuration.TestConfiguration

Code coverage metrics may be generated and viewed with:

coverage run --branch --source=ina219 -m unittest discover -s tests -p 'test_*.py'
coverage report -m

Coding Standard

This library adheres to the PEP8 standard and follows the idiomatic style described in the book Writing Idiomatic Python by Jeff Knupp.