// Let a led bounce from left to right.
// Let another led follow in its footsteps
const byte leds[] = { 2, 3, 4, 5, 6, 7, 8, 9};
unsigned long previousMillis;
const unsigned long interval = 150;
int index = 0;
int direction = 1; // +1 or -1
int previousIndex = 0;
void setup()
{
for( auto a:leds)
pinMode(a, OUTPUT);
}
void loop()
{
unsigned long currentMillis = millis();
if( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
// There are three indexes:
// The new index for the led that should turn on.
// the current index, for the follower led, do nothing with it.
// the previous index, that led should be turned off.
int newIndex = index + direction;
// Creating the bouncing at the right and the left with the index
if( newIndex < 0)
{
newIndex = 0;
direction = 1;
}
else if( newIndex >= (int) sizeof( leds))
{
newIndex = sizeof( leds) -1;
direction = -1;
}
// Turn on the new led
digitalWrite( leds[newIndex], HIGH);
// Turn off the previous led, but only if it is not used
if( previousIndex != newIndex and previousIndex != index)
{
digitalWrite( leds[previousIndex], LOW);
}
// Set the variables for the next time.
previousIndex = index;
index = newIndex;
}
}