I'm working on an arduino project with 8 LEDs that will cycle through a set of 4 colors. I've created an array of colors and am trying to figure out if there's a programmatic way to calculate which element from the array is next
LED | Loop 0 | loop 1 | loop 2 | loop 3 |
---|---|---|---|---|
0 | 0 | 1 | 2 | 3 |
1 | 1 | 2 | 3 | 0 |
2 | 2 | 3 | 0 | 1 |
3 | 3 | 0 | 1 | 2 |
4 | 0 | 1 | 2 | 3 |
5 | 1 | 2 | 3 | 0 |
6 | 2 | 3 | 0 | 1 |
7 | 3 | 0 | 1 | 2 |
The first loop (loop 0) works using modulus the formula loop + pixel % 4
(i.e. 0 + 0 % 4
, 0 + (1 % 4)
, etc.). But with subsequent loops, the numbers don't repeat correctly. For instance
LED | Desired | Formula | Result |
---|---|---|---|
0 | 1 | 1 + (0 % 4) | 1 |
1 | 2 | 1 + (1 % 4) | 2 |
2 | 3 | 1 + (2 % 4) | 3 |
3 | 0 | 1 + (3 % 4) | 4 |
4 | 1 | 1 + (4 % 4) | 1 |
5 | 2 | 1 + (5 % 4) | 2 |
6 | 3 | 1 + (6 % 4) | 3 |
7 | 0 | 1 + (7 % 4) | 4 |
It all works until we get to led 3, where the desired result is 0 but I get 4. The next loop (loop 2) results in 2, 3, 4, 5, 2, 3, 4, 5, when I want 2, 3, 0, 1, 2, 3, 0, 1.
I haven't been able to find anything on the Internet because I'm not sure what to ask. I've tried looking for repeating sequences but keep getting the results not related to this question.
Is there an elegant mathematical solution?
Yes it is. I think this fulfills the expression (loop+pixel)%4