Yet Another WebIOPi+
 All Classes Namespaces Files Functions Variables Macros Pages
pca9685.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 import time
16 from webiopi.utils.types import toint
17 from webiopi.devices.i2c import I2C
18 from webiopi.devices.analog import PWM
19 
20 class PCA9685(PWM, I2C):
21  MODE1 = 0x00
22  PWM_BASE = 0x06
23  PRESCALE = 0xFE
24 
25  M1_SLEEP = 1<<4
26  M1_AI = 1<<5
27  M1_RESTART = 1<<7
28 
29  def __init__(self, slave=0x40, frequency=50):
30  I2C.__init__(self, toint(slave))
31  PWM.__init__(self, 16, 12, toint(frequency))
32  self.VREF = 0
33 
34  self.prescale = int(25000000.0/((2**12)*self.frequency))
35  self.mode1 = self.M1_RESTART | self.M1_AI
36 
37  self.writeRegister(self.MODE1, self.M1_SLEEP)
38  self.writeRegister(self.PRESCALE, self.prescale)
39  time.sleep(0.01)
40 
41  self.writeRegister(self.MODE1, self.mode1)
42 
43  def __str__(self):
44  return "PCA9685(slave=0x%02X)" % self.slave
45 
46  def getChannelAddress(self, channel):
47  return int(channel * 4 + self.PWM_BASE)
48 
49  def __pwmRead__(self, channel):
50  addr = self.getChannelAddress(channel)
51  d = self.readRegisters(addr, 4)
52  start = d[1] << 8 | d[0]
53  end = d[3] << 8 | d[2]
54  return end-start
55 
56  def __pwmWrite__(self, channel, value):
57  addr = self.getChannelAddress(channel)
58  d = bytearray(4)
59  d[0] = 0
60  d[1] = 0
61  d[2] = (value & 0x0FF)
62  d[3] = (value & 0xF00) >> 8
63  self.writeRegisters(addr, d)