From e87156263cdf33d930efc5fc438208f99a557112 Mon Sep 17 00:00:00 2001 From: Cullen Jennings Date: Sun, 22 May 2016 09:33:55 -0600 Subject: [PATCH] fix bug with negative currents and add Power --- samples/ina219.go | 9 +++++++-- sensor/ina219/ina219.go | 27 +++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/samples/ina219.go b/samples/ina219.go index 43de691..c73d963 100644 --- a/samples/ina219.go +++ b/samples/ina219.go @@ -23,7 +23,7 @@ func main() { bus := embd.NewI2CBus(1) - ina := ina219.New(bus, 0x40, 0.1) + ina := ina219.New(bus, 0x40, 0.001) defer ina.Close() for { @@ -42,7 +42,12 @@ func main() { panic(err) } - fmt.Printf("Shunt Voltage=%v Voltage=%v Current=%v\n", sv, v, c) + p, err := ina.Power() + if err != nil { + panic(err) + } + + fmt.Printf("Shunt Voltage=%v Voltage=%v Current=%v Power=%v \n", sv, v, c, p) time.Sleep(500 * time.Millisecond) } diff --git a/sensor/ina219/ina219.go b/sensor/ina219/ina219.go index 5cc76c3..795bdba 100644 --- a/sensor/ina219/ina219.go +++ b/sensor/ina219/ina219.go @@ -3,6 +3,7 @@ // interfcace. // TODO - add options to config voltage range, sensitivity and averaging +// TODO - add documentation package ina219 @@ -54,7 +55,10 @@ func (d *INA219) setup() error { d.mu.Lock() defer d.mu.Unlock() - config := uint16(0x219F) // 12, bit no integration, 32v bus range , 40mV shunt range + //config := uint16(0x219F) // 12, bit no integration, 32v bus range , 40mV shunt range + //config := uint16(0x2777) // 12, bit 64x integration, 32v bus range , 40mV shunt range + config := uint16(0x2F77) // 12, bit 64x integration, 32v bus range , 80mV shunt range + err := d.Bus.WriteWordToReg(d.address, configReg, config) if err != nil { return err @@ -62,7 +66,7 @@ func (d *INA219) setup() error { calib := uint16(0.5 + 40.96/d.shuntResitance) - err = d.Bus.WriteWordToReg(d.address, calibReg, calib) // .1 ohm sense resitor + err = d.Bus.WriteWordToReg(d.address, calibReg, calib) if err != nil { return err } @@ -84,7 +88,7 @@ func (d *INA219) ShuntVoltage() (float64, error) { return math.NaN(), err } - voltage := float64(v) / 100000.0 + voltage := float64( int16(v) ) / 100000.0 return voltage, nil } @@ -114,7 +118,22 @@ func (d *INA219) Current() (float64, error) { return math.NaN(), err } - current := float64(v) / 1000.0 + current := float64( int16(v) ) / 1000.0 + + return current, nil +} + +func (d *INA219) Power() (float64, error) { + if err := d.setup(); err != nil { + return math.NaN(), err + } + + v, err := d.Bus.ReadWordFromReg(d.address, powerReg) + if err != nil { + return math.NaN(), err + } + + current := float64( int16(v) ) / 50.0 return current, nil }