Skip to content
Michael Miller edited this page Jul 28, 2017 · 6 revisions

How do I store a reference to the NeoPixelBus in another class?

Since the NeoPixelBus is a template class; you can't just store a reference to it using older models. But there are two ways to accomplish this.

My first recommendation is to make the containing class a template also. The following sketch demonstrates this all in one file. The actual template class can be in another file or library.

#include <NeoPixelBus.h>

typedef  NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>  NeoPixelBusType;

NeoPixelBusType strip(4, 2);

// example template class using a reference
template<typename T_PIXEL_METHOD> class PixelRef {
  public:
  PixelRef(T_PIXEL_METHOD& pixelStrip) :
    _strip(pixelStrip) {
    }

  void Draw() {
    _strip.Show();
  }
  
  private:
  T_PIXEL_METHOD& _strip;
};

PixelRef<NeoPixelBusType> myPixelRef(strip);

void setup() {
    strip.Begin();
    strip.Show();
}

void loop() {
    myPixelRef.Draw();
}

The second method to accomplish this uses a normal class definition; but has the limitation that class must be fully implemented in a header file due to the NeoPixelBus type is defined in the sketch.

#include <NeoPixelBus.h>

typedef  NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>  NeoPixelBusType;

NeoPixelBusType strip(4, 2);

// example class using a reference; requires all code to be in the include
class PixelRef {
  public:
  PixelRef(NeoPixelBusType& pixelStrip) :
    _strip(pixelStrip) { 
    }

  void Draw() {
    _strip.Show();
  }
  
  private:
  NeoPixelBusType& _strip;
};

PixelRef myPixelRef(strip);

void setup() {
    strip.Begin();
    strip.Show();
}

void loop() {
    myPixelRef.Draw();
}
Clone this wiki locally