1
2
3
4
5
6
7 import time
8 import math
9 from Tools import Tools
10
12 _mode_adr = 0x00
13 _base_adr_low = 0x08
14 _base_adr_high = 0x09
15 _prescale_adr = 0xFE
16
17 - def __init__(self, bus, address = 0x40):
18 '''
19 Creates an instance of the PWM chip at given i2c address.
20 @param bus: the SMBus instance to access the i2c port (0 or 1).
21 @param address: the address of the i2c chip (default: 0x40)
22 '''
23 self.bus = bus
24 self.address = address
25 self._isAvailable = True
26 self._writeByte(self._mode_adr, 0x00)
27
29 '''
30 Sets the PWM frequency. The value is stored in the device.
31 @param freq: the frequency in Hz (approx. in range 16 - 1500 Hz)
32 '''
33 if not self._isAvailable:
34 return
35 prescaleValue = 25000000.0
36 prescaleValue /= 4096.0
37 prescaleValue /= float(freq)
38 prescaleValue -= 1.0
39 prescale = math.floor(prescaleValue + 0.5)
40 oldmode = self._readByte(self._mode_adr)
41 if oldmode == None:
42 return
43 newmode = (oldmode & 0x7F) | 0x10
44 self._writeByte(self._mode_adr, newmode)
45 self._writeByte(self._prescale_adr, int(math.floor(prescale)))
46 self._writeByte(self._mode_adr, oldmode)
47 time.sleep(0.005)
48 self._writeByte(self._mode_adr, oldmode | 0x80)
49
51 '''
52 Sets a single PWM channel. The value is stored in the device.
53 @param channel: one of the channels 0..15
54 @param duty: the duty cycle 0..4095 (included)
55 '''
56 if not self._isAvailable:
57 return
58 duty = int(duty)
59 duty = max(0, duty)
60 duty = min(4095, duty)
61 self._writeByte(self._base_adr_low + 4 * channel, duty & 0xFF)
62 self._writeByte(self._base_adr_high + 4 * channel, duty >> 8)
63
65 try:
66 self.bus.write_byte_data(self.address, reg, value)
67 except:
68 Tools.debug("Error while writing to I2C device at address: " + str(self.address))
69 self._isAvailable = False
70
72 try:
73 result = self.bus.read_byte_data(self.address, reg)
74 return result
75 except:
76 Tools.debug("Error while reading from I2C device at address: " + str(self.address))
77 return None
78