# Creating a loop to have multiple random LEDs turn on.

I have eight LED’s hooked up to D0 thru D7. I have the following code to randomly turn one on at a time, but my goal is to have more than one light randomly turn on. How can I do this?

``````int LED[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
int DELAY = 2000; // delay between each LED
int RANDOM;
int num_pins = 8; // number of pins
int i;

void setup()
{

for (i = 0; i < num_pins; i++)
pinMode(LED[i], OUTPUT);

}

void loop()
{
RANDOM = random(0, 9);

digitalWrite(LED[RANDOM], HIGH);
delay(DELAY);

digitalWrite(LED[RANDOM], LOW);
delay(DELAY);

}
``````

You turn on an LED then plug your ears and sit there waiting for 2 seconds. The Arduino can't do anything else during that 2 seconds.

Your specification needs a little more work. Does an "on" LED only stay on for exactly 2 seconds? Do you care if all the LEDs are all on at the same time or do you want it to "look" random without actually being random?

I would modify this to randomly turn on individual LEDs several times per second. Then randomly turn off LEDs several times per second too. An individual LED might stay on for many seconds before it gets hit by an "off". Or it might get hit by the "off" on the next cycle. Or it may be hit twice in a row by "on" - this won't make any change to the visible display.

Lots of ways. Maybe instead of picking the LED randomly, always loop through all the LEDs and set the HIGH/LOW randomly. shrug

How about something like this

``````const byte ledPins[] = {10, 11, 12, 13};
const byte NUMBER_OF_LEDS = sizeof(ledPins) / sizeof(ledPins[0]);
unsigned long startTimes[NUMBER_OF_LEDS];
unsigned long periods[NUMBER_OF_LEDS];

void setup()
{
for (int led = 0; led < NUMBER_OF_LEDS; led++)
{
pinMode(ledPins[led], OUTPUT);
}
}

void loop()
{
unsigned long currentTime = millis();
for (int led = 0; led < NUMBER_OF_LEDS; led++)
{
if (currentTime - startTimes[led] >= periods[led])
{