ina219 provides support for a popular power sensor from Texas Instruments:
The driver as the following functionality:
Use cmd/ina219 to retrieve measurement from the device.
Purpose: gather current, bus voltage and power.
This example uses either a INA219 connected via I²C.
package main
import (
"fmt"
"log"
"periph.io/x/conn/v3/i2c/i2creg"
"periph.io/x/devices/v3/ina219"
"periph.io/x/host/v3"
)
func main() {
// Make sure periph is initialized.
if _, err := host.Init(); err != nil {
log.Fatal(err)
}
// Open default I²C bus.
bus, err := i2creg.Open("")
if err != nil {
log.Fatalf("failed to open I²C: %v", err)
}
defer bus.Close()
// Create a new power sensor.
sensor, err := ina219.New(bus, &ina219.DefaultOpts)
if err != nil {
log.Fatalln(err)
}
// Read values from sensor.
measurement, err := sensor.Sense()
if err != nil {
log.Fatalln(err)
}
fmt.Println(measurement)
}
The default options are for a 100mΩ sense resistor. To calibrate measure the actual value of the sense resistor and use that value in the ina219 options like so:
sensorOpts := ina219.Opts{
Address :0x40,
SenseResistor :50 * physics.MilliOhm,
MaxCurrent :3200 * physics.MilliAmpere,
}
//...
sensor, err := ina219.New(bus, &sensorOpts)
if err != nil {
log.Fatal(err)
}
//...
The maximum current for the ina219 is determined by the value of the sense resistor. There can’t be more than 320mV drop across the sense resistor. With a 100mΩ sense resistor the maximum current is 3.2Amps. Using V=IR, you can determine what the maximum current is for your sense resistor:
I = V/R
I = 0.320V / 0.1Ω
I = 3.2A
If the actual load current is bellow the maximum current for your sense resistor setting MaxCurrent to some amount above the maximum load current will give more resolution to the current and power readings. Example: Load of 500mA with 100mΩ.
sensorOpts := ina219.Opts{
Address :0x40,
SenseResistor :100 * physics.MilliOhm,
MaxCurrent :1000 * physics.MilliAmpere,
}
//...
sensor, err := ina219.New(bus, &sensorOpts)
if err != nil {
log.Fatal(err)
}
//...
These links are for the INA219:
ina219 products from Adafruit use the high accuracy B version of ina219, and good quality sense resistors. Other vendors my vary in quality of sense resistors and version of the ina219.
The periph authors do not endorse any specific seller. These are only provided for your convenience.