Skip to content
Michael Miller edited this page Oct 10, 2023 · 6 revisions

I wish to dynamically set the number pixels, but I don't see a way to do this and other libraries expose a method to change the number of pixels like updateLength() or setPixelCount().

There are two solutions that will allow you to support this.

Always define it with the max possible

With this solution you define the strip with maximum but always consider it having less. The number of physical pixels doesn't matter.

const uint16_t MaxPixelCount = 144;
uint16_t PixelCount = 32; // default number of pixels
NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod> strip(MaxPixelCount, 2); 

void setup() {
}

void loop() {
    // some arbitrary code, use PixelCount and not strip.PixelCount()
    for (uint16_t pixel = 0; pixel < PixelCount; pixel++) {
        strip.SetPixelColor(pixel, red);
    }
}

void PixelCountChanged(uint16_t newCount) {
    PixelCount  = newCount;
}

Dynamically create one

The key word here is dynamic. The best practice when dealing with key feature change is to dynamically create the object and recreate it when things change. It will often lead to smaller program code size even though you may have to type more. See the following snippet of code as an example of how to do this.
The caveat to this solution is that if it happens often, memory will become fragmented slowing down your sketch. This is best used when it happens rarely.

// declare your object as dynamic, a pointer to it, the *
// a good practice is to set it NULL
NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>* strip = NULL;

void setup() {
...
// inside setup, allocate your default, or maybe you don't do this and just wait for outside influence
    PixelCountChanged(1); 
...
}

bool PixelCountChanged(uint16_t newCount) {
    if (strip != NULL) {  
       delete strip; // delete the previous dynamically created strip
    }
    strip = new NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>(newCount, Pin); // and recreate with new count
    if (strip == NULL) {
        Serial.println("OUT OF MEMORY");
        return false;
    }
    strip->Begin();
    return true;
}

void loop() {
// other parts of your code, you set the colors, and show
    if (strip != NULL) { 
        // some arbitrary code
        for (uint16_t pixel = 0; pixel < strip->PixelCount(); pixel++) {
            strip->SetPixelColor(pixel, red);
        }
        strip->Show();
    }
}

Clone this wiki locally