-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpwm.py
66 lines (45 loc) · 1.92 KB
/
pwm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/python
import sys
import time
import math
from Adafruit_GPIO.I2C import Device as Adafruit_I2C
sys.path.append('./aeac_controls_2022/')
from constants import MODE1, CLK, COUNT_SIZE, PRESCALE
from utils import getCounterValues
# ============================================================================
# Adafruit PCA9685 16-Channel PWM Servo Driver
# ============================================================================
class PWM :
i2c = None
# need busnum, i2c_interface
def __init__(self, address=0x40, busnum=0, debug=False):
self.i2c = Adafruit_I2C(address, busnum)
self.address = address
self.debug = debug
if self.debug:
print("Reseting PCA9685")
self.i2c.write8(MODE1, 0x00)
def setPWMFreq(self, freq):
""" Sets the PWM frequency """
prescaleval = ((CLK/COUNT_SIZE)/float(freq)) - 1.0 # 25MHz
if self.debug:
print("Setting PWM frequency to %d Hz" % freq)
print("Estimated pre-scale: %d" % prescaleval)
prescale = math.floor(prescaleval + 0.5)
if self.debug:
print("Final pre-scale: %d" % prescale)
oldmode = self.i2c.readU8(MODE1);
newmode = (oldmode & 0x7F) | 0x10 # sleep
self.i2c.write8(MODE1, newmode) # go to sleep
self.i2c.write8(PRESCALE, int(math.floor(prescale)))
self.i2c.write8(MODE1, oldmode)
time.sleep(0.005)
self.i2c.write8(MODE1, oldmode | 0x80)
def setPWMCounters(self, reg, bus, on, off):
"""Sets a single PWM channel"""
if self.debug:
print("Setting PWM at reg {} bus {}".format(reg, bus))
self.i2c.write8(reg[0] + 4*bus, on & 0xFF)
self.i2c.write8(reg[1] + 4*bus, on >> 8)
self.i2c.write8(reg[2] + 4*bus, off & 0xFF)
self.i2c.write8(reg[3] + 4*bus, off >> 8)