Arduino doesn't understand for (int x=4; x>-1; x--)?

Hi everybody.

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();
}
}

My leds run still from pin13 to pin9...

I don't see why that statement shouldn't do what you want (or work) - however, I did notice later on you use

for (int x=5; x>-1; x--) { // turn off all LED's

x=5 is an invalid array entry.

Likewise, when you do

if (currentLED == 5) {direction = -1;}

It needs to be 4, or you risk accessing item index 5 next time in, which doesn't exist (indexes run from 0-4 for 5 items).

You are right about the 4 but not 5.

But it really runs from pin13.

Your example has

for (int x=5; x>-1; x--) { // turn off all LED's

What are you expecting ">-" to do? Do you mean ">="?

What are you expecting “>-” to do?

Test to see if “x” is greater than minus one?
Just a guess.

But yes, some consistency (hint: define a constant and use it) in the indices of the array would be good.

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.