How do I blink multiple LEDs in a sequence using millis?

@paolo_gie, I hope you don't mind that we get a little carried away. The best way is what you understand and suits you best.

I wanted to see for myself if it would be possible to have one led bouncing to left and right and another led following. The "follower" would be the second led.

This is how it turned out:

// 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;
  }
}

You can see it in Wokwi:

Wokwi is a online simulation for Arduino, and so is Tinkercad. I have compared them here: Virtual Online Arduino and ESP32 Simulator - Wokwi Arduino Simulator features - #3 by Koepel

The state in [state*2] and [state*2+1] is to solve a mathematical problem. It calculates the index for the first and the second led. You can put that calculation on a separate line with a extra variable to better understand it. Maybe you want the led pattern to be slightly different, then you need other code to calculate the index of the leds.

1 Like