From 9c1817a8194a05d9db64b4fd24fe04b23d7da40d Mon Sep 17 00:00:00 2001 From: analogic Date: Sat, 27 May 2017 14:57:32 +0200 Subject: [PATCH] Adding MCP3208 convertor Copy of mcp3008 with necessary changes derived from https://github.com/kidoman/embd/pull/47 to make MCP3208 work. Creating new driver instead of changing API of different model (like pull 47) seems to be better choice. --- convertors/mcp3208/mcp3208.go | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 convertors/mcp3208/mcp3208.go diff --git a/convertors/mcp3208/mcp3208.go b/convertors/mcp3208/mcp3208.go new file mode 100644 index 0000000..3347392 --- /dev/null +++ b/convertors/mcp3208/mcp3208.go @@ -0,0 +1,45 @@ +// Package mcp3208 allows interfacing with the mcp3208 8-channel, 12-bit ADC through SPI protocol. +package mcp3208 + +import ( + "github.com/golang/glog" + "github.com/kidoman/embd" +) + +// MCP3208 represents a mcp3208 8bit DAC. +type MCP3208 struct { + Mode byte + Bus embd.SPIBus +} + +const ( + // SingleMode represents the single-ended mode for the mcp3208. + SingleMode = 1 + + // DifferenceMode represents the diffenrential mode for the mcp3208. + DifferenceMode = 0 +) + +// New creates a representation of the mcp3208 convertor +func New(mode byte, bus embd.SPIBus) *MCP3208 { + return &MCP3208{mode, bus} +} + +const ( + startBit = 1 +) + +// AnalogValueAt returns the analog value at the given channel of the convertor. +func (m *MCP3208) AnalogValueAt(chanNum int) (int, error) { + var data [3]uint8 + data[0] = (uint8(startBit) << 2) + (uint8(m.Mode) << 1) + (uint8(chanNum) >> 2) + data[1] = uint8(chanNum) << 6 + data[2] = 0 + + glog.V(2).Infof("mcp3208: sendingdata buffer %v", data) + if err := m.Bus.TransferAndReceiveData(data[:]); err != nil { + return 0, err + } + + return int(uint16(data[1] & 0x0f) << 8 | uint16(data[2])), nil +}