1
0
mirror of https://github.com/kidoman/embd synced 2024-12-22 21:00:05 +01:00
embd/controller/mcp4725/mcp4725.go

101 lines
1.9 KiB
Go
Raw Normal View History

2014-01-06 02:26:45 +05:30
// Package mcp4725 allows interfacing with the MCP4725 DAC.
package mcp4725
import (
"sync"
"github.com/golang/glog"
2014-03-03 00:51:23 +05:30
"github.com/kidoman/embd"
2014-01-06 02:26:45 +05:30
)
const (
dacReg = 0x40
programReg = 0x60
powerDown = 0x46
genReset = 0x06
powerUp = 0x09
)
// MCP4725 represents a MCP4725 DAC.
type MCP4725 struct {
// Bus to communicate over.
2014-03-03 00:51:23 +05:30
Bus embd.I2CBus
2014-01-06 02:26:45 +05:30
// Addr of the sensor.
Addr byte
initialized bool
mu sync.RWMutex
}
// New creates a new MCP4725 sensor.
2014-03-03 00:51:23 +05:30
func New(bus embd.I2CBus, addr byte) *MCP4725 {
2014-01-06 02:26:45 +05:30
return &MCP4725{
Bus: bus,
Addr: addr,
}
}
func (d *MCP4725) setup() error {
2014-01-06 02:26:45 +05:30
d.mu.RLock()
if d.initialized {
d.mu.RUnlock()
return nil
2014-01-06 02:26:45 +05:30
}
d.mu.RUnlock()
d.mu.Lock()
defer d.mu.Unlock()
glog.V(1).Infof("mcp4725: general call reset")
if err := d.Bus.WriteByteToReg(d.Addr, 0x00, powerUp); err != nil {
return err
2014-01-06 02:26:45 +05:30
}
if err := d.Bus.WriteByteToReg(d.Addr, 0x00, genReset); err != nil {
return err
2014-01-06 02:26:45 +05:30
}
d.initialized = true
return nil
2014-01-06 02:26:45 +05:30
}
func (d *MCP4725) setVoltage(voltage int, reg byte) error {
if err := d.setup(); err != nil {
return err
2014-01-06 02:26:45 +05:30
}
if voltage > 4095 {
voltage = 4095
}
if voltage < 0 {
voltage = 0
}
glog.V(2).Infof("mcp4725: setting voltage to %04d", voltage)
if err := d.Bus.WriteWordToReg(d.Addr, reg, uint16(voltage<<4)); err != nil {
return err
2014-01-06 02:26:45 +05:30
}
return nil
2014-01-06 02:26:45 +05:30
}
// SetVoltage sets the output voltage.
func (d *MCP4725) SetVoltage(voltage int) error {
2014-01-06 02:26:45 +05:30
return d.setVoltage(voltage, dacReg)
}
// SetPersistedVoltage sets the voltage and programs the EEPROM so
// that the voltage is restored on reboot.
func (d *MCP4725) SetPersistedVoltage(voltage int) error {
2014-01-06 02:26:45 +05:30
return d.setVoltage(voltage, programReg)
}
// Close puts the DAC into power down mode.
func (d *MCP4725) Close() error {
glog.V(1).Infof("mcp4725: powering down")
if err := d.Bus.WriteWordToReg(d.Addr, powerDown, 0); err != nil {
return err
2014-01-06 02:26:45 +05:30
}
return nil
2014-01-06 02:26:45 +05:30
}