I have 8 LEDs lined up on a breadboard, and I am trying to make them run from one end to the other and back, sorta like the lights on KITT (from night rider – hope that clarifies). the LEDs are all set up and correct and work.
I have set up my code like so:
int ledPins[]={2,3,4,5,6,7,8,9};
void setup()
{
for (int i =0; i <8; i++)
{
pinMode(ledPins[i],OUTPUT);
}
}
void loop()
{
for(int i =0; i<8; i++)
{
digitalWrite(ledPins[i],HIGH);
delay(100);
digitalWrite(ledPins[i],LOW);
}
for(int i =7; i<1; i--)
{
digitalWrite(ledPins[i],HIGH);
delay(100);
digitalWrite(ledPins[i],LOW);
}
}
but it doesn't cycle the LEDs from right to left and then back like I was aiming for.
EDIT: What it does do – is light the LEDs from right to left, but doesn't light them the opposite way (left to right). It just keeps going from right to left, right to left
I am using an Arduino UNO, and basing my circuit off the experimentation kit for Arudino CIRC-02
EDIT #2: So I have changed the for-loops to while loops:
int ledPins[]={2,3,4,5,6,7,8,9};
void setup()
{
for (int i =0; i <8; i++)
{
pinMode(ledPins[i],OUTPUT);
}
}
void loop()
{
int i = 0;
while (i<7)
{
{
digitalWrite(ledPins[i],HIGH);
delay(100);
digitalWrite(ledPins[i],LOW);
i++;
}
}
i = 7;
while (i >0)
{
digitalWrite(ledPins[i],HIGH);
delay(100);
digitalWrite(ledPins[i],LOW);
i--;
}
}
and it works as intended!
However, I am still interested in where my for-loop went wrong, if anybody has any ideas
Best Answer
In the second 'for' loop, i is immediately not <1, so the loop never executes.
should say