Random LED Millis

by Keebo07 in Circuits > Arduino

6846 Views, 5 Favorites, 0 Comments

Random LED Millis

MillisLab.jpg

The goal of this project is to create 4 LED that turn on randomly based on a random number generator and use an interval based on Millis. To create this project, you will need a push button, 4 led lights and the wires to hook them up.

Step 1

MillisLab.jpg

The first step is pretty simple. Connect 4 LEDs and and a push button to your Arduino. In our code, we will use the pushing of the button to start the LEDs.

An LED will light up after a two second interval as determined but Millis.

A random number generator will decided which led to turn on.

Code:

unsigned long wait = 2000;
unsigned long previousTime = 0; int buttonPin = 2; int buttonState = 0; int previousButton = 0; int pin1 = 13; int pin2 = 12; int pin3 = 11; int pin4 = 10; long randomNumber; boolean led1State = false; boolean led2State = false; boolean led3State = false; boolean led4State = false;
void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);
  pinMode(pin4, OUTPUT);
}
void loop()
{
  //read the button's state (on or off)
  buttonState = digitalRead(buttonPin);
  if(buttonState != previousButton)
  {
    if(buttonState == HIGH)//Button is pressed
    {
      unsigned long time = millis;
      randomNumber = random(0,3);
      if(time - previousTime >= wait)
      {
        switch(randomNumber)
        {
          case 0: 
            digitalWrite(pin1, HIGH);
            digitalWrite(pin2, LOW);
            digitalWrite(pin3, LOW);
            digitalWrite(pin4, LOW);
            previousTime = time;
          break;
          case 1: 
            digitalWrite(pin1, LOW);
            digitalWrite(pin2, HIGH);
            digitalWrite(pin3, LOW);
            digitalWrite(pin4, LOW);
            previousTime = time;
          break;
          case 2: 
            digitalWrite(pin1, LOW);
            digitalWrite(pin2, LOW);
            digitalWrite(pin3, HIGH);
            digitalWrite(pin4, LOW);
            previousTime = time;
          break;
          case 3: 
            digitalWrite(pin1, LOW);
            digitalWrite(pin2, LOW);
            digitalWrite(pin3, LOW);
            digitalWrite(pin4, HIGH);
            previousTime = time;
          break;
        }
      }
            
    }
  }                      
}