I want to confirm a thing: Arduino doesn't understand for (int x=4; x>-1; x--)? For this code:
byte ledPin[] = {13,12,11,10,9}; // Create array for LED pins
int ledDelay(65); // delay between changes
int direction = 1;
int currentLED = 0;
unsigned long changeTime;
void setup() {
for (int x=4; x>-1; x--) { // set all pins to output
pinMode(ledPin[x], OUTPUT); }
changeTime = millis();
}
void changeLED() {
for (int x=5; x>-1; x--) { // turn off all LED's
digitalWrite(ledPin[x], LOW);
}
digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
currentLED += direction; // increment by the direction value
// change direction if we reach the end
if (currentLED == 5) {direction = -1;}
if (currentLED == 0) {direction = 1;}
}
void loop() {
if ((millis() - changeTime) > ledDelay) { // if it has been ledDelay ms since
//last change
changeLED();
changeTime = millis();
}
}
elisawuliang:
You are right about the 4 but not 5.
But it really runs from pin13.
I'm not sure what you mean, but the code can be tested easily enough:
for (int x=5; x>-1; x--) { // turn off all LED's
digitalWrite(ledPin[x], LOW);
}
Will set x to 5,4,3,2,1,0 as it loops - but you only have five items: ledPin[0], ledPin[1], ledPin[2], ledPin[3], ledPin[4]
The result is you will try to access an invalid item.
Likewise later on:
if (currentLED == 5) {direction = -1;}
By allowing currentLED to reach 5, the next time you go into the function you'll do a digitalWrite with ledPin[5], which doesn't exist:
digitalWrite(ledPin[currentLED], HIGH); // turn on the current LED
In any case, these are coding issues, but may not be the problem you're experiencing - perhaps if you describe exactly how the program fails, someone could offer some specific advice.