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
00001 #include "INA219.h" 00002 00003 INA219::INA219(PinName sda, PinName scl, unsigned char adr) : 00004 _i2c(sda, scl) 00005 { 00006 _i2c.frequency(100000); 00007 _adr = adr; 00008 } 00009 00010 bool INA219::detect(void) 00011 { 00012 _i2c.start(); 00013 bool det = (1 == _i2c.write(_adr|1/*write address for reading*/)); 00014 _i2c.stop(); 00015 return det; 00016 } 00017 00018 double INA219::getCurrent(void) 00019 { 00020 double d = 0.0; 00021 char r = 0x01; 00022 if (0 == _i2c.write(_adr, &r, sizeof(r), true)) 00023 { 00024 char v[2] = {0}; 00025 if (0 == _i2c.read(_adr, v, sizeof(v))) 00026 { 00027 int u = (int)((((short)v[0]) << 8) + (unsigned char)v[1]) * 10; // uV 00028 int i = u * 2/*0.5ohm*/; 00029 d = 1e-6 * i; 00030 } 00031 } 00032 else 00033 { 00034 _i2c.stop(); 00035 } 00036 return d; 00037 } 00038 00039 double INA219::getVoltage(void) 00040 { 00041 double d = 0.0; 00042 char r = 0x02; 00043 if (0 == _i2c.write(_adr, &r, sizeof(r), true)) 00044 { 00045 char v[2] = {0}; 00046 if (0 == _i2c.read(_adr, v, sizeof(v))) 00047 { 00048 int u = (int)(((((short)v[0]) << 8) + (unsigned char)v[1]) >> 3) * 4; // mV 00049 d = 1e-3 * u; 00050 } 00051 } 00052 else 00053 _i2c.stop(); 00054 return d; 00055 }
Generated on Sun Jul 24 2022 22:49:42 by 1.7.2