So I wrote in some debugging code, and it was then that it settled into my brain that I was definitely overrunning my led array, and I was surprised at how well the little thing seemed to be taking it. (I'm a lazy web programmer, so I'm used to this after all.) I decided that we should avoid this, and a simple if statement later, everything appears to be working. Feel free to suggest better code style, or whatever. But it appears to be working.
/*
* LED Snake!
*
*/
int ledPins[] = {2,3,4,5,6,7,8,9,10,11};
int length = 4;
int head = 0;
void setup() {
Serial.begin(9600);
for(int i = 0; i < 10; i++){
pinMode(ledPins[i],OUTPUT);
}
}
void loop() {
snake();
}
void snake() {
int tail = (head-length > 0) ? head-length : 0;
Serial.println(head);
Serial.println(tail);
Serial.println("---");
for (int i = 0; i < tail; i++) {
digitalWrite(ledPins[i], LOW);
}
Serial.print("Turning on: ");
for (int i = tail; i < head; i++) {
Serial.print(i);
Serial.print(",");
if (i < 10) {
digitalWrite(ledPins[i], HIGH);
}
}
Serial.println();
if (tail > 9) {
head = 0;
} else {
head++;
}
delay(500);
}
One full series in the serial log:
0
0
---
Turning on:
1
0
---
Turning on: 0,
2
0
---
Turning on: 0,1,
3
0
---
Turning on: 0,1,2,
4
0
---
Turning on: 0,1,2,3,
5
1
---
Turning on: 1,2,3,4,
6
2
---
Turning on: 2,3,4,5,
7
3
---
Turning on: 3,4,5,6,
8
4
---
Turning on: 4,5,6,7,
9
5
---
Turning on: 5,6,7,8,
10
6
---
Turning on: 6,7,8,9,
11
7
---
Turning on: 7,8,9,10,
12
8
---
Turning on: 8,9,10,11,
13
9
---
Turning on: 9,10,11,12,
14
10
---
Turning on: 10,11,12,13,