Advertisement
silver2row

The ole Cape II

May 3rd, 2020
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from smbus2 import SMBus
  2. from time import sleep
  3.  
  4. # relevant registers
  5. MODE1       = 0x00
  6. MODE2       = 0x01
  7. LED         = 0x06
  8. ALL_LED     = 0xFA
  9. PRE_SCALE   = 0xFE
  10.  
  11. def pwm_reg( output ):
  12.     if output == 'all':
  13.         return ALL_LED
  14.     else:
  15.         assert output in range(0, 16)
  16.         return LED + 4 * output
  17.  
  18. class Pca9685:
  19.     def __init__(self, bus, addr):
  20.         self.addr = 0b10000000 | addr
  21.         self.bus = bus
  22.         self.write_reg(MODE1, 1 << 5)  # initialize MODE1 register
  23.         sleep(500e-6)  # wait 500us to allow oscillator to power up
  24.  
  25.     def read_reg(self, reg):
  26.         assert reg in range(0, 256)
  27.         return self.bus.read_byte_data(self.addr, reg)
  28.  
  29.     def write_reg(self, reg, value):
  30.         assert reg in range(0, 256)
  31.         return self.bus.write_byte_data(self.addr, reg, value)
  32.  
  33.     def read_regs(self, reg, count):
  34.         assert reg in range(0, 256)
  35.         assert count in range(1, 257-reg)
  36.         return self.bus.read_i2c_block_data(self.addr, reg, count)
  37.  
  38.     def write_regs(self, reg, values):
  39.         assert reg in range(0, 256)
  40.         return self.bus.write_i2c_block_data(self.addr, reg, values)
  41.  
  42.     def get_pwm(self, output):
  43.         [on_l, on_h, off_l, off_h] = self.read_regs(pwm_reg(output), 4)
  44.         on = on_l | on_h << 8
  45.         off = off_l | off_h << 8
  46.         return (off, on)
  47.  
  48.     def set_pwm(self, output, off, on=0):
  49.         assert on in range(0, 4097)
  50.         assert off in range(0, 4097)
  51.         assert on <= off
  52.         on_l = on & 0xff
  53.         on_h = on >> 8
  54.         off_l = off & 0xff
  55.         off_h = off >> 8
  56.         self.write_regs(pwm_reg(output), [on_l, on_h, off_l, off_h])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement