RobTillaart / INA228

Arduino library for INA228 current and power sensor
MIT License
1 stars 2 forks source link

Update INA228.cpp #8

Closed markliquid1 closed 2 weeks ago

markliquid1 commented 2 weeks ago

updated getShuntVoltage() to allow reading of negative currents

RobTillaart commented 2 weeks ago

Please have a look at PR #7, there is similar work in progress

RobTillaart commented 2 weeks ago

If I understand correctly this should allow the small negative range over the bus (and thus negative current for shunt)?

Datasheet 7.3.1 The supported common-mode voltage range at the input pins is –0.3 V to +85 V, which makes the device well suited for both high-side and low-side current measurements.

Next weekend I hope to have time to get hands on with hardware.

RobTillaart commented 2 weeks ago

Have checked the data sheet and your code is an improvement however with minor points see above.

float INA228::getShuntVoltage() 
{
  //  datasheet P25
  float LSB = 312.5e-9;  //  312.5 nV
  uint16_t config = _readRegister(INA228_CONFIG, 2);
  if (config & 0x0010)   //  ADCRANGE
  {
    LSB = 78.125e-9;     //  78.125 nV
  }

  //  remove reserved bits.
  int32_t value = _readRegister(INA228_SHUNT_VOLTAGE, 3) >> 4;
  if (value & 0x00800000) 
  {
    value |= 0xFF000000;
  }
  return value * LSB;
}

Please give it a try, thanks.

RobTillaart commented 2 weeks ago

@markliquid1 better use this

float INA228::getShuntVoltage() 
{
  //  datasheet P25
  float LSB = 312.5e-9;  //  312.5 nV
  if (getADCRange() == 1) 
  {
    LSB = 78.125e-9;     //  78.125 nV
  }

  //  remove reserved bits.
  int32_t value = _readRegister(INA228_SHUNT_VOLTAGE, 3) >> 4;
  //  handle negative values
  if (value & 0x00800000) 
  {
    value |= 0xFF000000;
  }
  return value * LSB;
}
markliquid1 commented 2 weeks ago

Thanks, I'll give it a try today. I'm new to programming, so mainly submitted this request as a way to point out the issue with negative current measurement. The code I proposed was inspired by the Adafruit library for the INA228, and did seem to work, but certainly was not the cleanest way to do it, and not consistent with the rest of your library.

RobTillaart commented 2 weeks ago

Then I will include it in my current develop branch which I'm working on. There is still work todo before the library is functional complete.

Thanks for the clarification

Will close this as a PR. If you have more remarks, please open an issue per topic.

markliquid1 commented 2 weeks ago

Ok, I wasn't yet aware of the "Issue" functionality of github, so I will use that in the future. Thanks for all your open source work on Arduino libraries. I have benefited greatly as I learn, including this INA228. I look forward to your updates.

RobTillaart commented 2 weeks ago

Included getShuntVoltage() into my develop branch,

Thanks again for pointing out the negative values!