Giter Site home page Giter Site logo

chrisb2 / pi_ina219 Goto Github PK

View Code? Open in Web Editor NEW
112.0 15.0 34.0 56 KB

This Python library supports the INA219 voltage, current and power monitor from Texas Instruments with a Raspberry Pi using the I2C bus. The intent of the library is to make it easy to use the quite complex functionality of this sensor.

License: MIT License

Python 100.00%
python raspberry-pi python-library ina-219 beaglebone-black lopy4

pi_ina219's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pi_ina219's Issues

Problem with this on a Pi Pico

I tried this on a Pi Pico and this is what came up:

%Run -c $EDITOR_CONTENT
Traceback (most recent call last):
File "", line 1, in
File "/lib/ina219.py", line 5, in
ImportError: no module named 'logging'

addressing i2c bus numbers > 1

Hi Chris,

I've been attempting to use your library with an Intel UpSquared and ran into an issue with the Intel's bus numbering system - their GPIO bus is 5 rather than the RPi default (assuming 1)

I made the following changes to ina219.py get it working on my project

def __init__(self, shunt_ohms, max_expected_amps=None, busnum=None, address=__ADDRESS, log_level=logging.ERROR):
self._i2c = I2C.get_i2c_device(address=address, busnum=busnum)

Cheers,
Steve

Citation

I used your library in my dissertation, I'd like your confirmation on the citation:
C. Borrill, T. Timmons, T. van Staveren, T. Kluyver, and S. Bauer, โ€œpi_ina219โ€ 2019. [Online]. Available: https://github.com/chrisb2/pi_ina219. [Accessed: 24-Jul-2019].

Guide until get data of voltage and current ina219 using raspberrypi

okay this LED in DIM condition (10% of brightness)
-voltage - below 1 V
Led in full brightness (100% of brightness)
-voltage - above 5V

I measure using multimeter.

can u guide me until I get this value using ina219.
I follow all video and this instruction . but get some error.

that error say the python cant find that lib.

thank you

not working on raspberrypiOS 32 bit

New RaspberryPI os,

installed python3
installed library

sudo pip3 install pi-ina219

that is installed successfuly but if i wil run the code

python ina219.py Traceback (most recent call last): File "/home/pi/ina219.py", line 3, in <module> from ina219 import INA219 File "/home/pi/ina219.py", line 3, in <module> from ina219 import INA219 ImportError: cannot import name 'INA219' from partially initialized module 'ina219' (most likely due to a circular import) (/home/pi/ina219.py)

Using the powerdown() function results in invalid readings

Using the powerdown() function as described in the readme (see below) often results in the previous reading being returned from ina.voltage(), not a new reading.

`while True:
    ina.configure(ina.RANGE_16V, ina.GAIN_1_40MV)
    print "Voltage : %.3f V" % ina.voltage()
    ina.powerdown()
    time.sleep(300)

`

Reading current samples from python while INA219 is connected to Arduino board

Hi Chris,

I would like to use the library of the ina219 on python and I have some questions please.,
Basically, I'm running Pyfirmata (StandardFirmata) on my Arduino nano and I'm controlling some motor via Python.
I want to connect the INA219 to my Arduino and read the current samples from Python to display it on my App.
Do I have to use Raspberrypi board ? Because I am more familiar with Arduino.
It is possible to use this library to do so?

Thanks in advance, eliran

Library is not compatible with Python 3

These errors occur:

Traceback (most recent call last):
  File "example.py", line 4, in <module>
    from ina219 import INA219
  File "/home/pi/pi_ina219/ina219.py", line 7, in <module>
    import Adafruit_GPIO.I2C as I2C
ImportError: No module named 'Adafruit_GPIO'

and:

  File "example.py", line 14
    print "Bus Voltage    : %.3f V" % ina.voltage()

ina219.DeviceRangeError: Current out of range I have got exactly the same problem when trying to install Raspberry PI i52 UPS Plus HAT. Device is called EP-0136

I have got exactly the same problem when trying to install Raspberry PI i52 UPS Plus HAT. Device is called EP-0136
https://wiki.52pi.com/index.php/UPS_Plus_SKU:_EP-0136

I am getting following error:


------Current information of the detected Raspberry Pi------

Raspberry Pi Supply Voltage: 4.956 V
Raspberry Pi Current Current Consumption: 1180.656 mA
Raspberry Pi Current Power Consumption: 5843.566 mW

Traceback (most recent call last):
File "/home/pi/bin/upsPlus.py", line 40, in
batt_current = ina_batt.current()
File "/home/pi/.local/lib/python3.9/site-packages/ina219.py", line 196, in current
self._handle_current_overflow()
File "/home/pi/.local/lib/python3.9/site-packages/ina219.py", line 246, in _handle_current_overflow
self._increase_gain()
File "/home/pi/.local/lib/python3.9/site-packages/ina219.py", line 271, in _increase_gain
raise DeviceRangeError(self.__GAIN_VOLTS[gain], True)
ina219.DeviceRangeError: Current out of range (overflow), for gain 0.32V, device limit reached
UPS Plus Installation is Incomplete! ... failed!
Please visit wiki for more information:.
-----------------------------------------------------.
https://wiki.52pi.com/index.php/UPS_Plus_SKU:_EP-0136.
-----------------------------------------------------.

Originally posted by @wojciechczyz in #15 (comment)

Force library to use specified logging level

I have a logging configuration file which is:

[loggers]
keys=root

[handlers]
keys=consoleHandler

[logger_root]
level=NOTSET
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
...

My code:

import logging
from ina219 import INA219, DeviceRangeError
logging.getLogger('ina219').setLevel(logging.ERROR)

class CurrentReader():
    SHUNT_OHMS = 0.1
    MAX_EXPECTED_AMPS = 3.0

    def init(self):
        self.ina = INA219(self.SHUNT_OHMS, self.MAX_EXPECTED_AMPS, busnum=1, log_level=logging.ERROR)

No matter what I do, the module is always in debug level.
How can I force Ina219 to use the specified logging level instead of the one in the logging file?

Allow gain to auto-scale if a current overflow occurs

The idea is to make it even easier to use this library by automatically increasing the gain if a current overflow is detected at the current gain. Current overflow would only occur when the gain reaches the maximum value support by the INA219.

Auto-scaling of gain would be the default configuration, so to measure voltage upto 26V and current upto 3.2A (with std 0.1 Ohm shunt) only code similar to the following would required:

SHUNT_OHMS = 0.1
ina = INA219(SHUNT_OHMS)
ina.configure()

try:
    print "Bus Voltage: %.3f V" % ina.voltage()
    print "Bus Current: %.3f mA" % ina.current()
except CurrentOverflowException"
    print "Current greater than device capability"

Unable to get ADC_16SAMP (or any of the others to work)

I didn't have any issues with the first two sample programs. So, I thought I'd try changing the sampling options. So I changed the following :-

ina.configure(ina.RANGE_16V, ina.ADC_16SAMP)

This seemed correct (although I'm sure you'll tell me I'm doing it wrong). Howeever, python gives me an error when doing this :-

$ python3 ina219_2.py

Traceback (most recent call last):
File "ina219_2.py", line 29, in <module>
read()
File "ina219_2.py", line 13, in read
ina.configure(ina.RANGE_16V, ina.ADC_16SAMP)
File "/usr/local/lib/python3.7/dist-packages/ina219.py", line 164, in configure
self.logger.info('gain set to %.2fV' % self.__GAIN_VOLTS[self._gain])
IndexError: list index out of range

Oddly, if I also add :-

ina.configure(ina.RANGE_16V, ina.ADC_12BIT, ina.ADC_16SAMP)

It then 'works'. I put works in quotes, as it then starts giving me overflow errors :-

Bus Voltage: 8.440 V
Current out of range (overflow), for gain 0.32V

If I take out both out and just leave the line as :-

ina.configure(ina.RANGE_16V)

then it works fine :-

pi@pizero-i2c:~ $ python3 ina219_2.py

Bus Voltage: 8.360 V
Bus Current: 1204.098 mA
Power: 10294.634 mW
Shunt voltage: 121.250 mV

Bus Voltage: 8.520 V
Bus Current: 1305.171 mA
Power: 12634.146 mW
Shunt voltage: 166.960 mV

Bus Voltage: 8.356 V
Bus Current: 1352.000 mA
Power: 11112.195 mW
Shunt voltage: 119.970 mV

Bus Voltage: 8.476 V
Bus Current: 1294.829 mA
Power: 11791.220 mW
Shunt voltage: 142.850 mV

ImportError: cannot import name INA219

Hi, I am using this code with your library and get the error: ImportError: cannot import name INA219

#!/usr/bin/env python


import socket, time, math, csv, datetime, subprocess, sys, os

op_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
sys.path.append(op_folder+'/classes')
#from ads1115 import Ads1115
#from conf_analog import Conf_analog
from ina219 import INA219
from ina219 import DeviceRangeError

SHUNT_OHMS = 0.01

conf_analog=Conf_analog()
home = conf_analog.home

if len(sys.argv)>1:
	if sys.argv[1]=='settings':
		print home+'/.openplotter/openplotter_analog.conf'
		subprocess.Popen(['leafpad',home+'/.openplotter/openplotter_analog.conf'])
	exit
else:

	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

	poll_interval = 1
	rate_analog = 1

	tick_analog=time.time()
	ina = INA219(SHUNT_OHMS,1.0,0x41)
	ina.configure()

	try:
		inaV = ina.voltage()
		inaA = ina.current()/1000
		inaW = inaV*inaA
	except DeviceRangeError as e:
		print e
	
	while True:
		tick2=time.time()
		time.sleep(poll_interval*1.0/1000.0)
		#GENERATE	

		if tick2-tick_analog > rate_analog:
			tick_analog=time.time()

			list_signalk_path1=[]
			list_signalk1=[]

			try:
				inaV = inaV*0.8 +ina.voltage()*0.2
				inaA = inaA*0.8 +ina.current()/1000*0.2
				inaW = inaV*inaA
			except DeviceRangeError as e:
				print e

			SignalK = '{"updates": [{"$source": "OPsensors.I2C.ina219","values":[ '
			Erg=''
			Erg += '{"path": "electrical.batteries.rpi.current","value":'+str(inaA)+'},'
			Erg += '{"path": "electrical.batteries.rpi.voltage","value":'+str(inaV)+'},'
			Erg += '{"path": "electrical.batteries.rpi.power","value":'+str(inaW)+'},'			
			SignalK +=Erg[0:-1]+']}]}\n'
			sock.sendto(SignalK, ('127.0.0.1', 55557))

The following code is working perfectly, so I know it is not a hardware problem:

#!/usr/bin/env python

import logging
from ina219 import INA219

SHUNT_OHMS = 0.01
MAX_EXPECTED_AMPS = 6


def read():
    ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS, log_level=logging.INFO)
    ina.configure(ina.RANGE_16V, ina.GAIN_AUTO)

    print("Bus Voltage    : %.3f V" % ina.voltage())
    print("Bus Current    : %.3f mA" % ina.current())
    print("Supply Voltage : %.3f V" % ina.supply_voltage())
    print("Shunt voltage  : %.3f mV" % ina.shunt_voltage())
    print("Power          : %.3f mW" % ina.power())


if __name__ == "__main__":
    read()

Hope you can help! Been trying for days, with no luck to get the first script running.
I am running it with python ina219.py and not python3 ina219.py

Regards,

Jamos

Calculation of "current" for negative "shunt_voltage"

when the shunt voltage is positive all is as expected (voltage range=12-14V, shunt 16mV, current 160mA)
when the shunt voltage is negative (or the Vin- and Vin+) are swapped (same voltage range, shunt -16mV) then the current is given as about -1100mA. Is this expected behaviour for the library (v1.2.0). I'm puzzled as I thought the INA219 could handle positive and negative shunt voltages. The application is measuring charge and discharge of a 12 volt battery at minute intervals with the INA219 in series with the battery positive terminal. All aspects of the INA219 are standard except I set the voltage range to 16 Volts and the Max current to 2,0 Amps.

cannot import name INA219

pi@raspberrypi:~/shabi/python$ python ina219.py
Traceback (most recent call last):
  File "ina219.py", line 4, in <module>
    from ina219 import INA219
  File "/home/pi/shabi/python/ina219.py", line 4, in <module>
    from ina219 import INA219
ImportError: cannot import name INA219

and I tried to pip3 install it but same error occurred. How can I fix it?

improbable values returned?

Hi Chris,

first, thanks for the hard work on this library. second, I'm trying to use it with an ina219, which I think I have wired correctly but the results I'm seeing are a bit strange.

Here's my test code:

`#!/usr/bin/python3
from ina219 import INA219

ina = INA219(shunt_ohms=0.1,
max_expected_amps = 3.0,
address=0x40)

ina.configure(voltage_range=ina.RANGE_32V,
gain=ina.GAIN_AUTO,
bus_adc=ina.ADC_128SAMP,
shunt_adc=ina.ADC_128SAMP)
v = ina.voltage()
i = ina.current()
p = ina.power()

print('{0:0.1f}V {1:0.1f}mA'.format(v, i))
print('{0:0.1f} Watts'.format(p/1000))`

with no load on it I'm seeing the following:

19.4V 0.0mA
0.0 Watts

Under load (which should be 20ish volts at 3amps I'm seeing:
0.0V -66.8mA
0.0 Watts

I have it wired as follows:

Red: reference ground to 20v DC ground
Orange: 3.3v -> ina219 VCC pin
Brown: ground to ina219 ground pin
Blue: SDA -> ina219 SDA pin
Yellow: SLC -> ina219 SLC pin

on the ina219 the brown wire is connected to VCC+ which is connected to the 20v DC+ from the power supply, the red wire on VCC- is connected to the load.

Attached are photos of the layout (maybe that will help?) Anyways, any ideas you have would be helpful. Thanks!
IMG_20200830_122152
IMG_20200830_122148

Convert from Adafruit_GPIO library (which is archived) to smbus2 library

The Adafruit_GPIO library is now archived and so does not correctly support later versions of Raspberry Pi and OS. The plan is to replace this with smbus2.

This stacktrace occurred on a Raspberry Pi 4 with 'Bullseye' Raspberry Pi OS:

File "/usr/local/lib/python3.9/dist-packages/ina219.py", line 116, in __init__
    self._i2c = I2C.get_i2c_device(address=address, busnum=busnum)
  File "/usr/local/lib/python3.9/dist-packages/Adafruit_GPIO/I2C.py", line 63, in get_i2c_device
    busnum = get_default_bus()
  File "/usr/local/lib/python3.9/dist-packages/Adafruit_GPIO/I2C.py", line 55, in get_default_bus
    raise RuntimeError('Could not determine default I2C bus for platform.')
RuntimeError: Could not determine default I2C bus for platform.

A work-around for this is described in the readme.

Use named logger instead of root

Would it be possible to update ina219.py to use a named logger rather than the root logger? Being that this library is usually imported, logger.basicConfig() has likely been called by the main module already, so the basicConfig() call in __init__() has no effect (IOW the log level will not be changed at that time if it is different from the main module)

Use something like:
logger = logging.getLogger(__name__)
then change log calls to use logger.info() instead of logging.info() for example.

I can fix it and do a PR if you prefer. Thanks.

issue with code

Hi, i have been trying to use this code to read the adafruit ina 219 sensor, however when I run the code i get error reading ImportError: cannot import name 'INA219'. How can I resolve this. It may be something basic or me just being stupid, i havn't used python very much before
thanks

Library depends on obsolete dependency

Hi, is there any way to convert dependency to current library? Like Blinka or so?
Adafruit_GPIO can't detect Raspberry Pis later than 2 and it requires tinkering
to make it work.

Current overflow false positive

I'm testing the INA219 with a raspberry pi 3B with a voltage source and cannot read above 0,32 A, despite it being possible to get up to 3,2 A, or 0,32 V on the shunt. I consistently get current overflow errors when reaching 0,32 A / 0,032 V on the shunt (tested with a high precision multimeter). Tested with both auto-gain and manual, and both voltage ranges. I find it odd that the amp value raising the overflow is the voltage value that would produce max current on the shunt.

Invalid current readings when maximum value of calibration register is exceeded

As per the specification of the INA219 the maximum value of the calibration register is 0xFFFE (65534) (see P31). When the library calculates the calibration value is does not check that the chosen current LSB will cause this to be exceeded, resulting in invalid current and power readings.

With the Adafruit INA219 breakout with 0,1 Ohms shunt resistor and a max expected current of 100mA specified and INFO logging enabled the logged calibration value will be greater that 65534, see last line:

2017-02-21 19:09:11,039 - INFO - INA219 gain automatically set to 0.04V
2017-02-21 19:09:11,043 - INFO - INA219 max possible current: 0.400A
2017-02-21 19:09:11,046 - INFO - INA219 max expected current: 0.100A
2017-02-21 19:09:11,050 - INFO - INA219 min current LSB: 3.052e-06 A/bit
2017-02-21 19:09:11,053 - INFO - INA219 max current LSB: 2.441e-05 A/bit
2017-02-21 19:09:11,056 - INFO - INA219 chosen current LSB: 4.000e-06 A/bit
2017-02-21 19:09:11,059 - INFO - INA219 power LSB: 8.000e-05 W/bit
2017-02-21 19:09:11,062 - INFO - INA219 max current before overflow: 0.131A
2017-02-21 19:09:11,065 - INFO - INA219 max shunt voltage before overflow: 0.013V
2017-02-21 19:09:11,068 - INFO - INA219 calibration: 102400

Until this is fixed, this can be worked around by increasing the value of max_expected_current. In my case setting it to 200mA fixed the issue.

getting [Errno 121] Remote I/O error?

Hello m
I don't know if this is the place to ask - but I couln't find answer anywhere.

I have done everything is said in the guide : (except the LCD part)
https://www.rototron.info/raspberry-pi-ina219-tutorial/

download and try to run the code (without the LCD)
but I'm gettting the
[Errno 121] Remote I/O error
what could be the reason for it

when I run the scanner - I can see the INA219

sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --

this is the code I'm using
`from ina219 import INA219, DeviceRangeError
from time import sleep

SHUNT_OHMS = 0.1
MAX_EXPECTED_AMPS = 0.6
ina = INA219(SHUNT_OHMS, MAX_EXPECTED_AMPS)
ina.configure()

def read_ina219():
try:
print ('Bus Voltage: {0:0.2f}V'.format(ina.voltage()))
print ('Bus Current: {0:0.2f}mA'.format(ina.current()))
print ('Power: {0:0.2f}mW'.format(ina.power()))
print ('Shunt Voltage: {0:0.2f}mV\n'.format(ina.shunt_voltage()))
except DeviceRangeError as e:
# Current out of device range with specified shunt resister
print(e)

while 1:
read_ina219()
sleep(1)`

and this is the all error I'm getting

python Documents/TestINA219_a.py Traceback (most recent call last): File "Documents/TestINA219_a.py", line 7, in <module> ina.configure() File "/usr/local/lib/python2.7/dist-packages/ina219.py", line 165, in configure self._max_expected_amps) File "/usr/local/lib/python2.7/dist-packages/ina219.py", line 283, in _calibrate self._calibration_register(calibration) File "/usr/local/lib/python2.7/dist-packages/ina219.py", line 329, in _calibration_register self.__write_register(self.__REG_CALIBRATION, register_value) File "/usr/local/lib/python2.7/dist-packages/ina219.py", line 361, in __write_register self._i2c.writeList(register, register_bytes) File "/usr/local/lib/python2.7/dist-packages/Adafruit_GPIO/I2C.py", line 127, in writeList self._bus.write_i2c_block_data(self._address, register, data) File "/usr/local/lib/python2.7/dist-packages/Adafruit_PureIO/smbus.py", line 294, in write_i2c_block_data self._device.write(data) IOError: [Errno 121] Remote I/O error

is there any way you can assit or find the problem ?
Thanks ,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.