Try Embedded

Power meter (INA219)

Measure the voltage, current and power of a load with an INA219, and add up the energy it uses.

Sensors · Intermediate

In a real product: Solar charge controller (Energy): Measures power in and out and adds up the energy harvested.

How long will a battery last? How much does a motor draw when it stalls? An INA219 sits in the supply line of a load and measures both the voltage and the current, so you can see power and energy.

What you'll learn

  • High-side current sensing with a shunt resistor
  • Reading voltage, current and power over I²C
  • Integrating power over time into energy (mWh)

How it works

The load's current flows through a 0.1 Ω shunt between VIN+ and VIN−. The INA219 measures the small voltage across it (25 mV at 250 mA) and the voltage at VIN−, the bus voltage. The library writes a calibration value so that the chip's own current and power registers come out in convenient units.

Here a 12 V supply feeds VIN+; the load itself is not drawn, so the current comes from the INA219's current setting. Energy is power times time: each second the sketch adds power × 1 s to a running total.

Try this

  • Click the INA219 while it runs and change the current: power and the energy rate follow.
  • Set the supply to 24 V: the bus voltage reads 24 V.
  • Estimate how long a 2000 mAh battery would last at the measured current.

sketch.ino

// An INA219 at 0x40 in a 12 V supply line: voltage, current, power and the energy used so far.
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;
float energy_mWh = 0;
unsigned long last = 0;

void setup() {
  Serial.begin(9600);
  if (!ina219.begin()) {
    Serial.println("No INA219 at 0x40");
    while (true) {}
  }
  last = millis();
}

void loop() {
  float volts = ina219.getBusVoltage_V();
  float mA = ina219.getCurrent_mA();
  float mW = ina219.getPower_mW();
  unsigned long now = millis();
  energy_mWh += mW * (now - last) / 3600000.0;
  last = now;
  Serial.print(volts, 2);
  Serial.print(" V  ");
  Serial.print(mA, 1);
  Serial.print(" mA  ");
  Serial.print(mW, 0);
  Serial.print(" mW  total ");
  Serial.print(energy_mWh, 3);
  Serial.println(" mWh");
  delay(1000);
}

Lessons behind it