Module PCA9685
[hide private]
[frames] | no frames]

Source Code for Module PCA9685

 1  # PCA9685.py 
 2  # ============================================================================ 
 3  # Most code from Adafruit PCA9685 16-Channel PWM Servo Driver 
 4  # with thanks to the author 
 5  # ============================================================================ 
 6   
 7  import time 
 8  import math 
 9  from Tools import Tools 
10   
11 -class PWM:
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
28 - def setFreq(self, freq):
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 # 25MHz 36 prescaleValue /= 4096.0 # 12-bit 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 # sleep 44 self._writeByte(self._mode_adr, newmode) # goto sleep 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
50 - def setDuty(self, channel, duty):
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
64 - def _writeByte(self, reg, value):
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
71 - def _readByte(self, reg):
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