I am attempting to have multiple types of LED runs that are selectable using numbers in the serial monitor (eventually will be DMX controlled, but this is the first step. LOL).
Case 1 is a 50 light run starting at 1 and going to 50. Case 2 reverses that, going from 50 to 1. The first time I call a case (either 1 or 2), it works properly. Every time after that, regardless of which case I call, the LEDs all turn on at once, rather than in a sequence. Both sets of code work properly when run outside of the switch-break format. What am I missing?`
Off the top of my head, may bear no relationship to reality, no fitness for purpose is expressed or implied, your mileage may vary:
Using one or two character upper case names for variables is something best avoided.
0..48
50..2
...seems a bit odd.
As does
But ignoring all of that... once you've gone through either of your cases, your brightness level is set to 0.
So the next time through your loop, setting each LED to a particular colour and doing a show is going to display... anything? Isn't brightness still set to 0?
So the first time you're going to see something is when you send FastLED.setBrightness(255); and all the LEDs suddenly get scaled up to full brightness from full off?
In other words: when you receive a character, first thing, set all LEDs to CRGB(0,0,0), setBrightness(255), then do your cases stuff.
I know the numbers are all wonky- this is a tester program and I've been going through different iterations, so bits and pieces are not getting changed as they should.
Thank you! The brightness was definitely the piece I was missing.
for (int ii = 0: ii < 50; ii++) {
int thePixel = 49 - ii; // algebra! 49 .. 0
// use thePixel, not ii
}
A loop is easiest to understand when you can see it do 50 times something as the loop index goes from 0 to 49.
If every loop you write does that.
If you need something that goes backwards, or from a here to a there that isn't 0 .. N - 1, or skips by three or whatever, write a simple expression to calculate the index you want.
Nice too when one loop is making things go forward and backward and double fast at once.
In my opinion for loops should be kept as simple as possible and a backwards loop is quite simple. Why introduce extra complications by doing maths in the loop to derive the value that you really want when it could be directly available ?
As for
This looks more like deliberate obfuscation than a reasonable solution
One man's deliberate obfuscation is another man's elegant abstraction. Plus, it's the standard technique used to traverse all C++ container classes, not just simple C-style arrays. Thus, it maintains consistent syntax regardless of the container type.
In a subtraction loop, MAX is a counting number (does not include zero), so it needs off-by-one math to address the right device, as the MAX value is actually MAX - 1, which is a whole number (includes zero).