|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +import time |
| 4 | +import math |
| 5 | +from Adafruit_I2C import Adafruit_I2C |
| 6 | + |
| 7 | +# ============================================================================ |
| 8 | +# Adafruit PCA9685 16-Channel PWM Servo Driver |
| 9 | +# ============================================================================ |
| 10 | + |
| 11 | +class PWM : |
| 12 | + i2c = None |
| 13 | + |
| 14 | + # Registers/etc. |
| 15 | + __SUBADR1 = 0x02 |
| 16 | + __SUBADR2 = 0x03 |
| 17 | + __SUBADR3 = 0x04 |
| 18 | + __MODE1 = 0x00 |
| 19 | + __PRESCALE = 0xFE |
| 20 | + __LED0_ON_L = 0x06 |
| 21 | + __LED0_ON_H = 0x07 |
| 22 | + __LED0_OFF_L = 0x08 |
| 23 | + __LED0_OFF_H = 0x09 |
| 24 | + __ALLLED_ON_L = 0xFA |
| 25 | + __ALLLED_ON_H = 0xFB |
| 26 | + __ALLLED_OFF_L = 0xFC |
| 27 | + __ALLLED_OFF_H = 0xFD |
| 28 | + |
| 29 | + def __init__(self, address=0x40, debug=False): |
| 30 | + self.i2c = Adafruit_I2C(address) |
| 31 | + self.address = address |
| 32 | + self.debug = debug |
| 33 | + if (self.debug): |
| 34 | + print "Reseting PCA9685" |
| 35 | + self.i2c.write8(self.__MODE1, 0x00) |
| 36 | + |
| 37 | + def setPWMFreq(self, freq): |
| 38 | + "Sets the PWM frequency" |
| 39 | + prescaleval = 25000000.0 # 25MHz |
| 40 | + prescaleval /= 4096.0 # 12-bit |
| 41 | + prescaleval /= float(freq) |
| 42 | + prescaleval -= 1.0 |
| 43 | + if (self.debug): |
| 44 | + print "Setting PWM frequency to %d Hz" % freq |
| 45 | + print "Estimated pre-scale: %d" % prescaleval |
| 46 | + prescale = math.floor(prescaleval + 0.5) |
| 47 | + if (self.debug): |
| 48 | + print "Final pre-scale: %d" % prescale |
| 49 | + |
| 50 | + oldmode = self.i2c.readU8(self.__MODE1); |
| 51 | + newmode = (oldmode & 0x7F) | 0x10 # sleep |
| 52 | + self.i2c.write8(self.__MODE1, newmode) # go to sleep |
| 53 | + self.i2c.write8(self.__PRESCALE, int(math.floor(prescale))) |
| 54 | + self.i2c.write8(self.__MODE1, oldmode) |
| 55 | + time.sleep(0.005) |
| 56 | + self.i2c.write8(self.__MODE1, oldmode | 0x80) |
| 57 | + |
| 58 | + def setPWM(self, channel, on, off): |
| 59 | + "Sets a single PWM channel" |
| 60 | + self.i2c.write8(self.__LED0_ON_L+4*channel, on & 0xFF) |
| 61 | + self.i2c.write8(self.__LED0_ON_H+4*channel, on >> 8) |
| 62 | + self.i2c.write8(self.__LED0_OFF_L+4*channel, off & 0xFF) |
| 63 | + self.i2c.write8(self.__LED0_OFF_H+4*channel, off >> 8) |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments