Hello,
I have written a code to control a set of RGB LEDs and I am looking for a way to clean up my code to be easier to read.
As you can see below, I have programmed my RGB strip to pulse along the entire strip, and when it goes along the previous led will be dimmer (until I get to -4 LED). This gives the effect of organic flow but can this be reduced into a string for ease if I want to expand the LEDs in flow.
I hope you can help guys. I will answer any questions
void Pulse(){
ledsUPPER[ledPos].setRGB(255, 0, 0); //set LED on and colour for Pos, this sets the main colour in both directions
if (dir == 0) { //If the LED is equal to Zero
if (ledPos > 0) ledsUPPER[ledPos-1].setRGB(150, 0, 0); //if forward LEDs are above 0, set 2nd one this colour
if (ledPos-1 > 0) ledsUPPER[ledPos-2].setRGB(75,0,0); //if forward LEDs-1 are above 0, set 3rd one this colour
if (ledPos-2 > 0) ledsUPPER[ledPos-3].setRGB(50, 0, 0); //if forward LEDs-2 are above 0, set 4th one this colour
if (ledPos-3 > 0) ledsUPPER[ledPos-4].setRGB(10,0,0); //if forward LEDs-3 are above 0, set 5th one this colour
}
I'm really looking for a way of reducing the lines of code, which seem unnecessary.
Look at the lines of code. Do you see any patterns? Like the if statement compares ledPos - i, where i is 0 to 4. Like the index is ledPos - i - 1, where i is 0 to 4.
If the values to assign to the LED at some position were in an array, you'd need one statement and a for loop.
No. You need an array for the red values to use in the call to Pulse(). You need an array for the green values. And, you need an array for the blue values.
I'm trying to understand the -1 and how it works, also why -i?
Create a table. List the values of i down the page. Across the page, have the headings ledPos - n, ledsUPPER[n], reds[n], blus[n], and grns[n]. For each cell, calculate the value of n based on the value of i. Then, write the value of the appropriate array in the cell.
For instance, when i is 0, ledPos - 0 is ledPos. When i is 1, the value being tested is ledPos - 1.
The ledsUPPER index values will be ledPos -1 and ledPos - 2.
The index values for reds, grns, and blus will be 0 and 1.
Compare the index values and/or array values at the index position to the code that you supplied.