rpi-ws281x / rpi-ws281x-python

Python library wrapping for the rpi-ws281x library
BSD 2-Clause "Simplified" License
326 stars 103 forks source link

Add PixelSubStrip class to simplify working with multiple segments #63

Open lbt opened 3 years ago

lbt commented 3 years ago

The existing API is unchanged.

A PixelSubStrip handles a subset of the pixels in a PixelStrip and can be created like so: strip = PixelStrip(...) strip1 = strip.createPixelSubStrip(0, num=10) # controls first 10 pixels strip2 = strip.createPixelSubStrip(10, num=10) # controls next 10 pixels

Signed-off-by: David Greaves david@dgreaves.com

MaxThom commented 3 years ago

this is cool! I'm working on a project as well and I did the segment in a different way. But your way is pretty cool.

MaxThom commented 3 years ago

With A change like this, you should add an example or two.

lbt commented 3 years ago

More than happy to do that. I first wanted to see if the approach was something that was acceptable.

Gadgetoid commented 2 years ago

Sorry for the lack of response here, this library is pretty low on my looooong list of priorities.

This is an interesting change- reminiscent of the sort of things I was trying to accomplish with Plasma. I think it solves a real problem and it's worth exploring.

This library should probably trend toward being helpful. I wonder if we could tackle things like 2d matrices with a similar pattern?

Right now I tackle those downstream with a fairly blunt 2d list lookup- https://github.com/pimoroni/unicorn-hat/blob/657deffc385895d43a81828c30355e5051cce6c7/library/UnicornHat/unicornhat.py#L76-L85

shadoxxhd commented 2 months ago

numpy support could naturally accommodate this with views:

# strip is a numpy ndarray of the color values; assuming dtype=np.uint32 for now
substrip1 = stip[start:end]
substrip2 = strip[start2:end2:2] # only every 2nd LED in this area

# assign colors to whole substrips
substrip1[:] = col1
substrip2[:] = col2

matrix = strip.reshape((10,10)) # still assuming dtype=np.uint32; otherwise ".reshape((10,10,4))" to preserve WRGB color channels
# assign colors to 2D areas
matrix[2:5,3:7] = col1
matrix[0,0] = col2
matrix[:,5] = col3
# or even assign every 2nd LED in the 8th column (assuming x,y indexing)
matrix[8,::2] = col4
# switch between x,y and y,x indexing
matrix2 = matrix.T

# access color components
matrix_col = matrix.view(dtype=np.uint8) # might need [:,:,::-1] to reverse byte order, depending on underlying architecture
matrix_col[9,9,0] = w # set white channel of specific pixel

If the numpy array was created in C and passed to python on PixelStrip creation, assignments to the numpy array would directly modify the underlying C array, and could immediately be rendered without any manual data movement (eg. setPixelColor calls).