Skip to content

Instantly share code, notes, and snippets.

@igrr
Created December 2, 2021 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igrr/3455b2b4fa190845948d2240717ea2f2 to your computer and use it in GitHub Desktop.
Save igrr/3455b2b4fa190845948d2240717ea2f2 to your computer and use it in GitHub Desktop.
MicroPython module for the TLC5947 (untested)
# SPDX-FileCopyrightText: 2017 Tony DiCola for Adafruit Industries
#
# SPDX-License-Identifier: MIT
#
# MicroPython module for the TLC5947 12-bit 24 channel LED PWM driver.
# Based on CircuitPython version of the same by Tony DiCola, Walter Haschka.
#
from machine import Pin, SPI
_CHANNELS = 24
_STOREBYTES = _CHANNELS + _CHANNELS // 2
class TLC5947:
"""TLC5947 12-bit 24 channel LED PWM driver. Create an instance of this by
passing in at least the following parameters:
:param spi: The machine.SPI bus instance, connected to the chip (only the SCK and MOSI lines are
used, there is no MISO/input).
:param latch: A machine.Pin instance connected to the chip's latch line.
Optionally you can specify:
:param auto_write: This is a boolean that defaults to True and will automatically
write out all the channel values to the chip as soon as a
single one is updated. If you set to False to disable then
you MUST call write after every channel update or when you
deem necessary to update the chip state.
:param num_drivers: This is an integer that defaults to 1. It stands for the
number of chained LED driver boards (DOUT of one board has
to be connected to DIN of the next). For each board added,
36 bytes of RAM memory will be taken. The channel numbers
on the driver directly connected to the controller are 0 to
23, and for each driver add 24 to the port number printed.
The more drivers are chained, the more viable it is to set
auto_write=False, and call write explicitly after updating
all the channels.
"""
def __init__(self, spi, latch, *, auto_write=True, num_drivers=1):
if num_drivers < 1:
raise ValueError(
"Need at least one driver; {0} is not supported.".format(num_drivers)
)
self._spi = spi
self._latch = latch
self._latch.init(Pin.OUT, None, value=0)
# This device is just a big 36*n byte long shift register. There's no
# fancy protocol or other commands to send, just write out all 288*n
# bits every time the state is updated.
self._n = num_drivers
self._shift_reg = bytearray(_STOREBYTES * self._n)
# Save auto_write state (i.e. push out shift register values on
# any channel value change).
self.auto_write = auto_write
def write(self):
"""Write out the current channel PWM values to the chip. This is only
necessary to call if you disabled auto_write in the initializer,
otherwise write is automatically called on any channel update.
"""
# Write out the current state to the shift register.
# First ensure latch is low.
self._latch.off()
# Write out the bits.
self._spi.write(self._shift_reg[0:_STOREBYTES * self._n + 1])
# Then toggle latch high and low to set the value.
self._latch.on()
self._latch.off()
def _get_gs_value(self, channel):
# pylint: disable=no-else-return
# Disable should be removed when refactor can be tested
if channel < 0 or channel >= _CHANNELS * self._n:
raise ValueError(
"Channel {0} not available with {1} board(s).".format(channel, self._n)
)
# Invert channel position as the last channel needs to be written first.
# I.e. is in the first position of the shift registr.
channel = _CHANNELS * self._n - 1 - channel
# Calculate exact bit position within the shift register.
bit_offset = channel * 12
# Now calculate the byte that this position falls within and any offset
# from the left inside that byte.
byte_start = bit_offset // 8
start_offset = bit_offset % 8
# Grab the high and low bytes.
high_byte = self._shift_reg[byte_start]
low_byte = self._shift_reg[byte_start + 1]
if start_offset == 4:
# Value starts in the lower 4 bits of the high bit so you can
# just concat high with low byte and return the 12-bit value.
return ((high_byte << 8) | low_byte) & 0xFFF
elif start_offset == 0:
# Value starts in the entire high byte and spills into upper
# 4 bits of low byte. Shift low byte and concat values.
return ((high_byte << 4) | (low_byte >> 4)) & 0xFFF
else:
raise RuntimeError("Unsupported bit offset!")
def _set_gs_value(self, channel, val):
if channel < 0 or channel >= _CHANNELS * self._n:
raise ValueError(
"Channel {0} not available with {1} board(s).".format(channel, self._n)
)
if val < 0 or val > 4095:
raise ValueError(
"PWM intensity {0} outside supported range [0;4095]".format(val)
)
# Invert channel position as the last channel needs to be written first.
# I.e. is in the first position of the shift registr.
channel = _CHANNELS * self._n - 1 - channel
# Calculate exact bit position within the shift register.
bit_offset = channel * 12
# Now calculate the byte that this position falls within and any offset
# from the left inside that byte.
byte_start = bit_offset // 8
start_offset = bit_offset % 8
# Grab the high and low bytes.
high_byte = self._shift_reg[byte_start]
low_byte = self._shift_reg[byte_start + 1]
if start_offset == 4:
# Value starts in the lower 4 bits of the high bit.
high_byte &= 0b11110000
high_byte |= val >> 8
low_byte = val & 0xFF
elif start_offset == 0:
# Value starts in the entire high byte and spills into upper
# 4 bits of low byte.
high_byte = (val >> 4) & 0xFF
low_byte &= 0b00001111
low_byte |= (val << 4) & 0xFF
else:
raise RuntimeError("Unsupported bit offset!")
self._shift_reg[byte_start] = high_byte
self._shift_reg[byte_start + 1] = low_byte
# Write the updated shift register values if required.
if self.auto_write:
self.write()
# Define index and length properties to set and get each channel's raw
# 12-bit value (useful for changing channels without quantization error
# like when using the PWMOut mock class).
def __len__(self):
"""Retrieve the total number of PWM channels available."""
return _CHANNELS * self._n # number channels times number chips.
def __getitem__(self, key):
"""Retrieve the 12-bit PWM value for the specified channel (0-max).
max depends on the number of boards.
"""
if key < 0: # allow reverse adressing with negative index
key = key + _CHANNELS * self._n
return self._get_gs_value(key) # does parameter checking
def __setitem__(self, key, val):
"""Set the 12-bit PWM value (0-4095) for the specified channel (0-max).
max depends on the number of boards.
If auto_write is enabled (the default) then the chip PWM state will
immediately be updated too, otherwise you must call write to update
the chip with the new PWM state.
"""
if key < 0: # allow reverse adressing with negative index
key = key + _CHANNELS * self._n
self._set_gs_value(key, val) # does parameter checking
def main():
spi_bus = SPI(1, 1000000, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
latch = Pin(15)
tlc = TLC5947(spi_bus, latch, auto_write=True)
# set channel 0 to 2048 (mid range)
tlc[0] = 2048
# send the channel values to the chip
# note: this is optional since if auto_write=True is passed to the constructor
tlc.write()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment