Skip to content

Instantly share code, notes, and snippets.

@boochow
Last active October 8, 2018 10:33
Show Gist options
  • Save boochow/a47784ff8862fdb1ee187a6ca4e2eee4 to your computer and use it in GitHub Desktop.
Save boochow/a47784ff8862fdb1ee187a6ca4e2eee4 to your computer and use it in GitHub Desktop.
# Hardware PWM
MS_DISABLE = const(0)
MS_ENABLE = const(1)
MODE_PWM = const(0)
MODE_SERIALIZER = const(1)
DEFAULT_RANGE = const(960)
class PWM:
def __init__(self, id, pin=-1, active=1, ms=MS_ENABLE, mode=MODE_PWM, polarity=0, silence=0, use_fifo=0, fifo_repeat=0):
self._active = active
self._flags = ms <<7 | use_fifo <<5 | polarity <<4 | silence <<3 |\
fifo_repeat <<2 | mode <<1
if pin > 0:
id_enabled = select_PWM_pin(pin)
if id != id_enabled:
raise ValueError
else:
self.id = id_enabled
elif id == 0 or id == 1:
self.id = id
else:
raise ValueError
self.set_PWM_CTL(self.id, self._flags | active)
# default settings: 1KHz output (19.2MHz / 960) / 20
PWM_clock_config(CLK_OSC, 20)
self.range(960)
def PWM_CTL(self):
return mem32[0x2020c000]
def set_PWM_CTL(self, id, reg):
mask = ~(0xff << id * 8)
mem32[0x2020c000] = (mem32[0x2020c000] & mask) | reg << id * 8
def range(self, rng=-1):
if rng == -1:
return mem32[0x2020c010 + 0x10 * self.id]
else:
save = self._active
self.active(0)
mem32[0x2020c010 + 0x10 * self.id] = rng
self.active(save)
def data(self, data=-1):
if data == -1:
return mem32[0x2020c014 + 0x10 * self.id]
else:
mem32[0x2020c014 + 0x10 * self.id] = data
def active(self, bool=-1):
if bool == -1:
return (self.PWM_CTL() & 1 << 8 * self.id) > 0
elif bool == 0 or bool == 1:
self._active = bool
self.set_PWM_CTL(self.id, self._flags | bool)
else:
raise ValueError
def duty(self, duty=-1):
self.range(DEFAULT_RANGE)
if duty == -1:
return self.data(-1)
self.data(duty)
def freq(self, freq=-1):
divi = (19200000 // DEFAULT_RANGE) // freq
divf = round((((19200000 // DEFAULT_RANGE) / freq) - divi) * 4096)
PWM_clock_config(CLK_OSC, divi, divf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment