LEDstrip

JavaScript simulation of WS2811/WS2812 LED strips commonly used with Arduino.

Download as .zip Download as .tar.gz View on GitHub

LEDstrip simulation

By Dougal Campbell


This is an example of my WS2812 RGB LED strip simulation in JavaScript. These LED strips are popular in Arduino projects because they only require one GPIO output pin to control, handle PWM output of the RGB state automatically, and offer a relatively easy way to address individual pixels in the strip. Strips can even be cut and reconnected serially to create a 2D matrix, if desired.

Usage example

    var container = $('.mylights')[0]; // Container DIV in the page
    var colors = [ // blue gradient
      [0,0,50],
      [0,0,100],
      [0,0,150],
      [0,0,200],
      [0,0,250]
    ];
    var size = colors.length;

    /**
     * Set colors, and send to strip using chaining.
     */
    var strip = LEDstrip(container, size) // Initialize
      .setcolors(colors)  // chain commands
      .send();
    
    /**
     * Manipulate the color buffer. Example of using seperate
     * function calls.
     */
    colors.forEach(function(val,idx){ // fiddle with colors
      colors[idx][0] = colors[4-idx][2];
      /** 
       * g = (r + b) / 2
       */
      colors[idx][1] = (colors[idx][0] + colors[idx][2]) >> 1;
    });
    
    strip.buffer = colors; // set the color buffer directly
    strip.send();

    /**
     * Animation loops. Manipulate the buffer, and send values.
     *
     * animate() is a function that manipulates strip.buffer[]...
     */
    var i = 0;
    var rAF_id = requestAnimationFrame(animate);
    
    // Think of this function like the loop() call in the Arduino IDE
    function animate() {
      rAF_id = requestAnimationFrame(animate);
      if (i == size) i = 0; // loop around the array

      /* generate random rgb values */
      var r = Math.floor(Math.random() * 255);
      var g = Math.floor(Math.random() * 255);
      var b = Math.floor(Math.random() * 255);

      strip.buffer[i++] = [r, g, b];
      strip.send();
    }

    /* When you want to end the animation: */
    // cancelAnimationFrame(rAF_id);

For more information: