Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
mcp48XX.py
Go to the documentation of this file.
1 # Copyright 2013 Dagda Ltd.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from webiopi.utils.types import toint
16 from webiopi.devices.spi import SPI
17 from webiopi.devices.analog import DAC
18 
19 class MCP48XX(SPI, DAC):
20  def __init__(self, chip, channelCount, resolution, name):
21  SPI.__init__(self, toint(chip), 0, 8, 10000000)
22  DAC.__init__(self, channelCount, resolution, 2.048)
23  self.name = name
24  self.buffered=False
25  self.gain=False
26  self.shutdown=True
27  self.values = [0 for i in range(channelCount)]
28 
29  def __str__(self):
30  return "%s(chip=%d)" % (self.name, self.chip)
31 
32  def int2bin(self,n,count):
33  return "".join([str((n >> y) & 1 ) for y in range(count-1,-1,-1)])
34 
35  def __analogRead__(self, channel, diff=False):
36  return self.values[channel]
37 
38  def __analogWriteShut__(self, channel):
39  self.shutdown = True
40  d = [0x00, 0x00]
41  d[0] |= (channel & 0x01) << 7 # bit 15 = channel
42  d[0] |= 0x00 << 6 # bit 14 = ignored
43  d[0] |= 0x00 << 5 # bit 13 = gain
44  d[0] |= (self.shutdown & 0x01) << 4 # bit 12 = shutdown
45  d[0] |= 0x00 # bits 8-11 = msb data
46  d[1] |= 0x00 # bits 0 - 7 = lsb data
47 
48  self.writeBytes(d)
49  self.values[channel] = 0
50 
51  def __analogWrite__(self, channel, value):
52  self.shutdown=False
53  d = [0x00, 0x00]
54  d[0] |= (channel & 0x01) << 7 # bit 15 = channel
55  d[0] |= (self.buffered & 0x01) << 6 # bit 14 = ignored
56  d[0] |= (not self.gain & 0x01) << 5 # bit 13 = gain
57  d[0] |= (not self.shutdown & 0x01) << 4 # bit 12 = shutdown
58  d[0] |= value >> (self._analogResolution - 4) # bits 8-11 = msb data
59  d[1] |= ((value << (12-self._analogResolution)) & 0xFF) # bits 4 - 7 = lsb data (4802) bits 2-7 (4812) bits 0-7 (4822) # bits 0 - 3 = ignored
60 
61  self.writeBytes(d)
62  self.values[channel] = value
63 
65  def __init__(self, chip=0):
66  MCP48XX.__init__(self, chip, 2, 8, "MCP4802")
67 
69  def __init__(self, chip=0):
70  MCP48XX.__init__(self, chip, 2, 10, "MCP4812")
71 
73  def __init__(self, chip=0):
74  MCP48XX.__init__(self, chip, 2, 12, "MCP4822")
75