ina3221/ina3221.go

106 lines
1.7 KiB
Go
Raw Normal View History

2023-08-20 05:57:49 +00:00
package ina3221
import (
"encoding/binary"
"log"
"periph.io/x/conn/v3/i2c"
"periph.io/x/conn/v3/i2c/i2creg"
"periph.io/x/conn/v3/mmr"
"periph.io/x/host/v3"
)
type Channel uint8
const (
Channel_1 Channel = 1
Channel_2 Channel = 3
Channel_3 Channel = 5
current_factor float64 = 40e-6
voltage_factor float64 = 8e-3
)
var (
logger log.Logger = *log.Default()
mem_dev mmr.Dev8
bus i2c.BusCloser
i2c_dev i2c.Dev
)
func start(slave_addr uint16) error {
logger.SetPrefix("ina3112: ")
logger.Println("Starting")
var err error
_, err = host.Init()
if err != nil {
logger.Println(err)
}
bus, err = i2creg.Open("")
if err != nil {
logger.Println(err)
}
i2c_dev = i2c.Dev{
Bus: bus,
Addr: slave_addr,
}
mem_dev = mmr.Dev8{
Conn: &i2c_dev,
Order: binary.BigEndian,
}
return err
}
func stop() error {
return bus.Close()
}
func read_register(address uint8) (uint16, error) {
return mem_dev.ReadUint16(address)
}
func shunt_voltage(channel Channel) (float64, error) {
res, err := read_register(uint8(channel))
if err != nil {
logger.Println(err)
return 0.0, err
}
res >>= 3
return float64(res), err
}
func bus_voltage(channel Channel) (float64, error) {
res, err := read_register(uint8(channel) + 1)
if err != nil {
logger.Println(err)
return 0.0, err
}
res >>= 3
return float64(res), err
}
func Current(channel Channel) (float64, error) {
res, err := shunt_voltage(channel)
if err != nil {
logger.Println(err)
return 0.0, err
}
return res * current_factor, err
}
func Voltage(channel Channel) (float64, error) {
res, err := bus_voltage(channel)
if err != nil {
logger.Println(err)
return 0.0, err
}
return res * voltage_factor, err
}
func ManufacturerID() (uint16, error) {
return read_register(0xfe)
}