Mitek ... / INA219

Dependents:   INA219TEST

Fork of INA219 by Michael Ammann

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers INA219.cpp Source File

INA219.cpp

00001 #include "INA219.h"
00002 
00003 INA219::INA219(PinName sda, PinName scl, unsigned char adr, int hz) :
00004     _i2c(sda, scl)
00005 {
00006     _i2c.frequency(hz);
00007     Address = adr;
00008 }
00009 
00010 I2C INA219::getI2C(void)
00011 {
00012     return _i2c;
00013 }
00014 
00015 bool INA219::detect(void)
00016 {
00017     _i2c.start();
00018     bool det = (0 == _i2c.write(Address | 1 /*write address for reading*/));
00019     _i2c.stop();
00020     return det;
00021 }
00022 
00023 bool INA219::getRegister(unsigned char reg, unsigned short *data)
00024 {
00025     unsigned char v[2];
00026     v[0] = reg;
00027     if (0 == _i2c.write(Address, (char *)&v, 1, true))
00028     {
00029         if (0 == _i2c.read(Address, (char *)&v, 2))
00030         {
00031             *data = (v[0] << 8) | v[1];
00032             return true;
00033         }
00034     }
00035     else
00036     {
00037         _i2c.stop();
00038     }
00039     return false;
00040 }
00041 
00042 unsigned short INA219::getRegister(unsigned char reg)
00043 {
00044     unsigned short data = 0;
00045     getRegister(0x00, &data);
00046     return data;
00047 }
00048 
00049 double INA219::getCurrent(void)
00050 {
00051     double d = 0.0;
00052     unsigned short data;
00053     if (getRegister(0x01, &data))
00054     {
00055         d = 1e-6 * ((int)data * 100); // uV * 0.1 ohm = A
00056     }
00057     return d;
00058 }
00059 
00060 double INA219::getVoltage(void)
00061 {
00062     double d = 0.0;
00063     unsigned short data;
00064     if (getRegister(0x02, &data))
00065     {
00066         d = 1e-3 * (int)(data >> 1); // V
00067     }
00068     return d;
00069 }