Avoid Looping through all LEDs (and other inefficient disasters). - eviltoast

<!-- SC_OFF --><div class=“md”><p>I made a simple wrapper class for my project. Looking at the functions, I feel like there must be a better way to do a lot of this.</p> <p>For example, my decayAll() function looks super weird to me; there must be a better way.</p> <p>For another example, I feel like fastLED would have a native setRandomAll() function and I may be reinventing the wheel.</p> <p><strong>Is there a way to apply some math to all LEDs within a CRGB[]?</strong></p> <p>cpp template&lt;byte pin, int sz&gt; class LedStrip {</p> <p>protected:</p> <pre><code>int cache; CRGB matrix[sz]; void ledConfig() { cache = 0; FastLED.addLeds&lt;WS2812B, pin, GRB&gt;(matrix, sz); } void ledPop() { FastLED.show(); } </code></pre> <p>public:</p> <pre><code>LedStrip() { pinMode(pin, OUTPUT); ledConfig(); } CRGB getPix(int i) { if (i &lt; sz) { return matrix[i]; } else { return matrix[0]; } } void setPix(int i, byte r, byte g, byte b) { // For a personal project like this, I&#39;m happy to deal with the silent error. if (!(i &lt; 0 || i &gt;= sz)) { matrix[i].setRGB(r,g ,b); } ledPop(); } void drawTo(CRGB externalMatrix[]) { for (int i = 0; i &lt; sz; i++) { matrix[i] += externalMatrix[i]; } ledPop(); } void setRandomAll() { for (int i = 0; i &lt; sz; i++) { byte r = random(1,10); byte g = random(1,10); byte b = random(1,10); matrix[i].setRGB(r,g ,b); } ledPop(); } void meterTo(int k, byte r, byte g, byte b) { for (int i = 0; i &lt; k; i++) { float m = min(((float)(i + 1) / (float)sz) + 0.01, 1.0); setPix(i, r * m, g * m, b * m); } for (int i = k; i &lt; sz; i++) { matrix[i].setRGB(0,0,0); } ledPop(); } void sweepTo(int k, byte r, byte g, byte b) { for (int i = 0; i &lt; sz; i++) { if (i == cache) { matrix[i].setRGB(r,g,b); } else { matrix[i].setRGB(0,0,0); } } ledPop(); cache = (cache + 1) % min(k, sz); } void decayAll(float m) { for (int i = 0; i &lt; sz; i++) { CRGB px = getPix(i); byte r = (byte)floor(px.r * m); byte g = (byte)floor(px.g * m); byte b = (byte)floor(px.b * m); setPix(i, r, g, b); } ledPop(); } void clearAll() { for (int i = 0; i &lt; sz; i++) { matrix[i].setRGB(0,0,0); } ledPop(); } </code></pre> <p>}; </p> </div><!-- SC_ON --> submitted by <a href=“https://old.reddit.com/user/Jonny9744”> /u/Jonny9744 </a> <br/> <span><a href=“https://old.reddit.com/r/FastLED/comments/157vy93/avoid_looping_through_all_leds_and_other/”>[link]</a></span> <span><a href=“https://old.reddit.com/r/FastLED/comments/157vy93/avoid_looping_through_all_leds_and_other/”>[comments]</a></span>