silver2row

The ole Cape

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