Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
pcf8574.py
Go to the documentation of this file.
1 # Copyright 2012-2013 Eric Ptak - trouch.com
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.i2c import I2C
17 from webiopi.devices.digital import GPIOPort
18 
20  FUNCTIONS = [GPIOPort.IN for i in range(8)]
21 
22  def __init__(self, slave=0x20):
23  slave = toint(slave)
24  if slave in range(0x20, 0x28):
25  self.name = "PCF8574"
26  elif slave in range(0x38, 0x40):
27  self.name = "PCF8574A"
28  else:
29  raise ValueError("Bad slave address for PCF8574(A) : 0x%02X not in range [0x20..0x27, 0x38..0x3F]" % slave)
30 
31  I2C.__init__(self, slave)
32  GPIOPort.__init__(self, 8)
33  self.portWrite(0xFF)
34  self.portRead()
35 
36  def __str__(self):
37  return "%s(slave=0x%02X)" % (self.name, self.slave)
38 
39  def __getFunction__(self, channel):
40  return self.FUNCTIONS[channel]
41 
42  def __setFunction__(self, channel, value):
43  if not value in [self.IN, self.OUT]:
44  raise ValueError("Requested function not supported")
45  self.FUNCTIONS[channel] = value
46 
47  def __digitalRead__(self, channel):
48  mask = 1 << channel
49  d = self.readByte()
50  return (d & mask) == mask
51 
52  def __portRead__(self):
53  return self.readByte()
54 
55  def __digitalWrite__(self, channel, value):
56  mask = 1 << channel
57  b = self.readByte()
58  if value:
59  b |= mask
60  else:
61  b &= ~mask
62  self.writeByte(b)
63 
64  def __portWrite__(self, value):
65  self.writeByte(value)
66 
68  def __init__(self, slave=0x38):
69  PCF8574.__init__(self, slave)
70