2014-05-03 18:05:09 +02:00
|
|
|
package mcp3008
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/golang/glog"
|
|
|
|
"github.com/kidoman/embd"
|
|
|
|
)
|
|
|
|
|
2014-05-21 22:49:01 +02:00
|
|
|
// MCP3008 represents a mcp3008 8bit DAC
|
|
|
|
type MCP3008 struct {
|
2014-05-08 19:39:31 +02:00
|
|
|
mode byte
|
2014-05-03 18:05:09 +02:00
|
|
|
|
|
|
|
bus embd.SPIBus
|
|
|
|
}
|
|
|
|
|
2014-05-08 19:39:31 +02:00
|
|
|
var SingleMode byte = 1
|
|
|
|
var DifferenceMode byte = 0
|
2014-05-03 18:05:09 +02:00
|
|
|
|
2014-05-21 22:49:01 +02:00
|
|
|
func New(mode byte, bus embd.SPIBus) *MCP3008 {
|
|
|
|
return &MCP3008{mode, bus}
|
2014-05-03 18:05:09 +02:00
|
|
|
}
|
|
|
|
|
2014-05-21 22:49:01 +02:00
|
|
|
const (
|
|
|
|
startBit = 1
|
|
|
|
)
|
|
|
|
|
|
|
|
func (m *MCP3008) AnalogValueAt(chanNum int) (int, error) {
|
|
|
|
var data [3]uint8
|
|
|
|
data[0] = startBit
|
2014-05-03 18:05:09 +02:00
|
|
|
data[1] = uint8(m.mode)<<7 | uint8(chanNum)<<4
|
|
|
|
data[2] = 0
|
|
|
|
|
2014-05-08 19:58:29 +02:00
|
|
|
glog.V(2).Infof("mcp3008: sendingdata buffer %v", data)
|
2014-05-21 22:49:01 +02:00
|
|
|
if err := m.bus.TransferAndRecieveData(data[:]); err != nil {
|
2014-05-03 18:05:09 +02:00
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return int(uint16(data[1]&0x03)<<8 | uint16(data[2])), nil
|
|
|
|
}
|