The INA219 is a high-side current shunt and power monitor with an I2C interface. The INA219 monitors both shunt drop and supply voltage, with programmable conversion times and filtering. A programmable calibration value, combined with an internal multiplier, enables direct readouts in amperes. An additional multiplying register calculates power in watts. The I2C interface features 16 programmable addresses.

INA219.cpp

Committer:
mazgch
Date:
2013-11-22
Revision:
2:a123ae7c1e4b
Parent:
1:2816fc874abc

File content as of revision 2:a123ae7c1e4b:

#include "INA219.h"

INA219::INA219(PinName sda, PinName scl, unsigned char adr) :
    _i2c(sda, scl)
{
    _i2c.frequency(100000);
    _adr = adr;
}

bool INA219::detect(void)
{
    _i2c.start();
    bool det = (1 == _i2c.write(_adr|1/*write address for reading*/));
    _i2c.stop();
    return det;
}

double INA219::getCurrent(void)
{
    double d = 0.0;
    char r = 0x01;
    if (0 == _i2c.write(_adr, &r, sizeof(r), true))
    {
        char v[2] = {0};
        if (0 == _i2c.read(_adr, v, sizeof(v)))
        {
            int u = (int)((((short)v[0]) << 8) + (unsigned char)v[1]) * 10; // uV
            int i = u * 2/*0.5ohm*/;
            d = 1e-6 * i;
        }
    }
    else 
    {
        _i2c.stop();
    }
    return d;
}

double INA219::getVoltage(void)
{
    double d = 0.0;
    char r = 0x02;
    if (0 == _i2c.write(_adr, &r, sizeof(r), true))
    {
        char v[2] = {0};
        if (0 == _i2c.read(_adr, v, sizeof(v)))
        {
            int u = (int)(((((short)v[0]) << 8) + (unsigned char)v[1]) >> 3) * 4; // mV
            d = 1e-3 * u;
        }
    }
    else 
        _i2c.stop();
    return d;
}