1

I am trying to turn on a specific LED using the NeoPixel module. How it works is really easy: Parse it a 2D array of RGB colors. Here's an example:

require("neopixel").write(NodeMCU.B2, [[255, 0, 0], [0, 255, 0], [0, 0, 255]]);

That will turn on the first three LEDs with red, green, and blue. I want to have a function, where I can do something like:

function single(number, color) {
    require("neopixel").write(NodeMCU.B2, number, color);
}

single(0, [255, 0, 0]);
single(1, [0, 255, 0]);
single(2, [0, 0, 255]);

Which would do the exact same as above. Now you might ask: Why would you want that? Well:

  1. I want it to remember the last "configuration" of LEDs, so I can update it over time
  2. If I want to turn off all my 100+ LEDs and just turn on the last few (or the ones in the middle), I wouldn't have to parse the write() function 100+ LEDs, where most of them are black

Is something like that possible, or would I have to do some magic in order to remember the last LED configuration?

MortenMoulder
  • 6,138
  • 11
  • 60
  • 116

1 Answers1

1

Yes, totally - it's worth looking at the neopixel docs at http://www.espruino.com/WS2811 as they suggest you use an array to store the current state.

Once you have that array - called arr here - you can use the .set method to set the 3 elements at the right position (3x the number, because RGB), and then can resend the whole array.

var arr = new Uint8ClampedArray(NUM_OF_LEDS*3);

function single(number, color) {
  arr.set(color, number*3);
  require("neopixel").write(NodeMCU.B2, arr);
}
Gordon Williams
  • 1,856
  • 1
  • 17
  • 31
  • Sick! So the new `arr` will have the new LED updated, if I do `arr.set()`? Basically doing exactly what I want. – MortenMoulder Dec 04 '17 at 12:03
  • Also, do you happen to know, if it's possible to simply turn all of them off simply, or if I have to set all 100+ to [0,0,0]? – MortenMoulder Dec 04 '17 at 14:01
  • Yes, that's right. `.set()` is a standard JavaScript Typed Array method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set). There's also `.fill` which sets every element of the array to the same thing, so to turn them all off just do `arr.fill(0)` and then the `neopixel` line to send all the data back out. – Gordon Williams Dec 04 '17 at 15:20