Commit e9a26791 authored by Jim Mussared's avatar Jim Mussared Committed by Damien George

drivers/neopixel: Reduce code size of driver.

Saves 71 bytes of bytecode.
Signed-off-by: default avatarJim Mussared <jim.mussared@gmail.com>
parent d63b287c
# NeoPixel driver for MicroPython # NeoPixel driver for MicroPython
# MIT license; Copyright (c) 2016 Damien P. George, 2021 Jim Mussared # MIT license; Copyright (c) 2016 Damien P. George, 2021 Jim Mussared
from micropython import const
from machine import bitstream from machine import bitstream
_BITSTREAM_TYPE_HIGH_LOW = const(0)
_TIMING_WS2818_800 = (400, 850, 800, 450)
_TIMING_WS2818_400 = (800, 1700, 1600, 900)
class NeoPixel: class NeoPixel:
# G R B W
ORDER = (1, 0, 2, 3) ORDER = (1, 0, 2, 3)
def __init__(self, pin, n, bpp=3, timing=1): def __init__(self, pin, n, bpp=3, timing=1):
...@@ -18,8 +14,10 @@ class NeoPixel: ...@@ -18,8 +14,10 @@ class NeoPixel:
self.bpp = bpp self.bpp = bpp
self.buf = bytearray(n * bpp) self.buf = bytearray(n * bpp)
self.pin.init(pin.OUT) self.pin.init(pin.OUT)
# Timing arg can either be 1 for 800kHz or 0 for 400kHz,
# or a user-specified timing ns tuple (high_0, low_0, high_1, low_1).
self.timing = ( self.timing = (
(_TIMING_WS2818_800 if timing else _TIMING_WS2818_400) ((400, 850, 800, 450) if timing else (800, 1700, 1600, 900))
if isinstance(timing, int) if isinstance(timing, int)
else timing else timing
) )
...@@ -27,21 +25,22 @@ class NeoPixel: ...@@ -27,21 +25,22 @@ class NeoPixel:
def __len__(self): def __len__(self):
return self.n return self.n
def __setitem__(self, index, val): def __setitem__(self, i, v):
offset = index * self.bpp offset = i * self.bpp
for i in range(self.bpp): for i in range(self.bpp):
self.buf[offset + self.ORDER[i]] = val[i] self.buf[offset + self.ORDER[i]] = v[i]
def __getitem__(self, index): def __getitem__(self, i):
offset = index * self.bpp offset = i * self.bpp
return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp)) return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp))
def fill(self, color): def fill(self, v):
for i in range(self.bpp):
c = color[i]
b = self.buf b = self.buf
for i in range(self.bpp):
c = v[i]
for j in range(self.ORDER[i], len(self.buf), self.bpp): for j in range(self.ORDER[i], len(self.buf), self.bpp):
b[j] = c b[j] = c
def write(self): def write(self):
bitstream(self.pin, _BITSTREAM_TYPE_HIGH_LOW, self.timing, self.buf) # BITSTREAM_TYPE_HIGH_LOW = 0
bitstream(self.pin, 0, self.timing, self.buf)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment