adafruit / Adafruit_INA219

INA219 Current Sensor
Other
206 stars 145 forks source link

Small negative currents returned as large positive ones #2

Closed kravlost closed 11 years ago

kravlost commented 11 years ago

The library returns strange readings when the current is flickering around zero, and it appears to be due to a minor bug in the Adafruit library. In the function:

uint16_t Adafruit_INA219::getCurrent_raw() {
  uint16_t value;
  wireReadRegister(INA219_REG_CURRENT, &value);
  return value;
}

it is treating the value in the current register as an unsigned int, but in fact it is a signed value. This means that small negative currents are being treated as large positive ones.

By changing the function to return a signed int:

int16_t Adafruit_INA219::getCurrent_raw() {
  uint16_t value;
  wireReadRegister(INA219_REG_CURRENT, &value);
  return (int16_t)value;
}

it can return positive and negative currents correctly.

The function getShuntVoltage_raw() looks like it suffers from the same problem, but that has not been tested.

microbuilder commented 11 years ago

Good eye .. thanks, and fixed.