element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      • Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Arduino - multiple LEDs with different delays
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Suggested Answer
  • Replies 8 replies
  • Answers 5 answers
  • Subscribers 404 subscribers
  • Views 4266 views
  • Users 0 members are here
Related

Arduino - multiple LEDs with different delays

Former Member
Former Member over 12 years ago

Hi all

I'm trying to write code to get 3 LEDs flashing independently, each with a different ON and OFF period.

For example:

LED1: ON for 25 ms, OFF for 500 ms

LED2: ON for 50 ms, OFF for 800 ms

LED3: ON fo 100 ms, OFF for 300 ms

 

 

So far I have set up the hardware: 3 LEDs on digital pins 6, 7 and 8 using my Arduino UNO board and a breadboard.

 

 

Code-wise I understand that I can't use the "delay" function because it causes the whole system to delay i.e. causes 'blocking'. At the moment I'm using the millis() function. My problem is that at the moment my code causes LED1 to turn ON for 25 ms and off for 25 ms, LED2 turns ON for 50 ms and off for 50 ms etc. So I need to somehow alter the OFF period independently.

 

 

In summary: I need a new approach or an alteration to my code to be able to independently change the ON and OFF periods for each of my LEDs independently.

 

 

Here is my code so far:

[code]

 

 

// Which pins are connected to which LED

const byte LED1 = 6;

const byte LED2 = 7;

const byte LED3 = 8;

 

 

// Assigning delays.

const unsigned long LED1_interval = 25;

const unsigned long LED2_interval = 50;

const unsigned long LED3_interval = 100;

 

 

// Declaring the variables holding the timer values for each LED.

unsigned long LED1_timer;

unsigned long LED2_timer;

unsigned long LED3_timer;

 

 

// Setting 3 digital pins as output pins and resetting timer

void setup ()

  {

  pinMode (LED1, OUTPUT);

  pinMode (LED2, OUTPUT);

  pinMode (LED3, OUTPUT);

  LED1_timer = millis ();

  LED2_timer = millis ();

  LED3_timer = millis ();

  }  // end of setup

 

 

//LED1 loop that turns it ON if it is OFF and vice versa

void toggle_LED1 ()

  {

   if (digitalRead (LED1) == LOW)

      digitalWrite (LED1, HIGH);

   else

      digitalWrite (LED1, LOW);

 

 

  // remember when we toggled it

  LED1_timer = millis (); 

  }  // end of toggleLED_1

 

 

//LED2 loop

void toggle_LED2 ()

  {

   if (digitalRead (LED2) == LOW)

      digitalWrite (LED2, HIGH);

   else

      digitalWrite (LED2, LOW);

 

 

  // remember when we toggled it

  LED2_timer = millis (); 

  }  // end of toggle_LED2

 

  //LED 3 loop

void toggle_LED3 ()

  {

   if (digitalRead (LED3) == LOW)

      digitalWrite (LED3, HIGH);

   else

      digitalWrite (LED3, LOW);

 

 

  // remember when we toggled it

  LED3_timer = millis (); 

  }  // end of toggle_LED3

 

 

void loop ()

  {

 

 

  // Handling the blink of LED1.

  if ( (millis () - LED1_timer) >= LED1_interval)

     toggle_LED1 ();

 

 

  // Handling the blink of LED2.

  if ( (millis () - LED2_timer) >= LED2_interval)

    toggle_LED2 ();

   

// Handling the blink of LED3.

  if ( (millis () - LED3_timer) >= LED3_interval)

    toggle_LED3 ();

   

/* Other code that needs to execute goes here.

   It will be called many thousand times per second because the above code

   does not wait for the LED blink interval to finish. */

 

 

}  // end of loop

[/code]

 

 

Any help would be greatly appreciated because I'm [b]very[/b] new to this!

 

 

Thanks!

  • Sign in to reply
  • Cancel

Top Replies

  • billabott
    billabott over 12 years ago +1 suggested
    Most Arduino boards have two external interrupts: numbers 0 (on digital pin 2) and 1 (on digital pin 3). Official Arduino.cc Example int pin = 13 ; volatile int state = LOW ; void setup ( ) { pinMode …
Parents
  • mixx
    0 mixx over 5 years ago

    Wait a second... Nobody realized that you're trying to read an output? I'm almost 100% sure that's a no-no. You have to store the state in another variable. I'd suggest using arrays and just making it into one function. You can make a boolean array to store the states more easily, and advance the index using an increment in the loop. Either way, just store the state in a variable. I also just noticed the OP is from 2013, but I feel other people might check this forum for solutions so, here. This should work, I tested it on my uno. I also worked on a variation of this myself and i'll post it after I give it to my professor so it doesn't show up in an originality report haha. Here:

     

    // Which pins are connected to which LED
    
    const byte LED1 = 6;
    const byte LED2 = 7;
    const byte LED3 = 8;
    
    // Assigning delays.
    
    const unsigned long LED1_interval = 25;
    const unsigned long LED2_interval = 50;
    const unsigned long LED3_interval = 100;
    
    // Declaring the variables holding the timer values for each LED.
    
    unsigned long LED1_timer;
    unsigned long LED2_timer;
    unsigned long LED3_timer;
    
    //Saving states of led's in an array + index
    
    bool states[4] = {0, 0, 0, 0};
    int index = 0;
    
    // Setting 3 digital pins as output pins and resetting timer
    void setup ()
      {
      pinMode (LED1, OUTPUT);
      pinMode (LED2, OUTPUT);
      pinMode (LED3, OUTPUT);
      LED1_timer = millis ();
      LED2_timer = millis ();
      LED3_timer = millis ();
      } 
    // end of setup
    
    //LED1 loop that turns it ON if it is OFF and vice versa
    
    void toggle_LED1 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED1, HIGH);
          states[index] = HIGH;
       }
    
       else{
          digitalWrite (LED1, LOW);
          states[index] = LOW;
       }
    
      // remember when we toggled it
    
      LED1_timer = millis (); 
      } 
    // end of toggleLED_1
    
    //LED2 loop
    
    void toggle_LED2 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED2, HIGH);
          states[index] = HIGH;
       }
    
       else{
          digitalWrite (LED2, LOW);
          states[index] = LOW;
       }
    
      // remember when we toggled it
    
      LED2_timer = millis (); 
      }
    // end of toggle_LED2
    
      //LED 3 loop
    
    void toggle_LED3 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED3, HIGH);
          states[index] = HIGH;
       }
       else{
          digitalWrite (LED3, LOW);
          states[index] = LOW;
       }
      // remember when we toggled it
    
      LED3_timer = millis (); 
      } 
    // end of toggle_LED3
    
    void loop ()
      {
      // Handling the blink of LED1.
    
      if ( (millis () - LED1_timer) >= LED1_interval)
         toggle_LED1 ();
    
     index++;          // Increment Index
    
      // Handling the blink of LED2.
    
      if ( (millis () - LED2_timer) >= LED2_interval)
        toggle_LED2 ();
    
    index++;           // Increment Index
    
    // Handling the blink of LED3.
    
      if ( (millis () - LED3_timer) >= LED3_interval)
         toggle_LED3 ();
    
    index = 0;          // Reset index to 0 for next run
    
    /* Other code that needs to execute goes here.
       It will be called many thousand times per second because the above code
       does not wait for the LED blink interval to finish. */
    }  // end of loop

     

    Edit: Ahh yes, forgot I said I'd post my own code that tackles this problem. Here it is, I seem to have some weird issues when initializing the states at low, and I also seemed to have another weird issue when running this that required adding a delay to setup. This solves it for some reason. I haven't looked into it all that much. If anyone knows what might be causing these issues please message me/reply to my post.

     

    // Variable Inits
    int led[4] = {4, 5, 6, 7}, count = 0, cot = 0; // Create array with led pins and int 'count'
    
    
    bool states[4] = {1, 1, 1, 1);  // Create a boolean array to store led states
    
    
    unsigned long prevTime[5], currTime;  // Create an array to store the previous time an led is checked, and
                                              // a variable to store the current time when checked for each loop
                                              
    long off[4] = {100, 600, 2100, 3600}; // Create an array to store how long led's should be off
    long on[4] = {400, 400, 400, 400};  // Create an array to store how long led's should be on
    
    
    #define ledcount (sizeof(led)/sizeof(led[0])) // Use define to return the size of the array of led pins when calling 'ledcount'
                                                  // 'sizeof()' returns the size in bytes of a variable. For an array,
                                                  // you can take the total size of the array, and divide by the size
                                                  // of a single element to get the amount of values in the array
    void setup() {
      delay(1);
      for(int i = 0; i <= ledcount; i++){   // Initialize led pins as outputs
        pinMode(led[i], OUTPUT);
      }
        //Serial.begin(115200);
    }
    
    
    void loop() {
    
    
      currTime = millis();  // Save the current time in milliseconds since the program started running
      
      for(int i = 0; i <= ledcount; i++){   // Loop through each led and turn it on, off, or leave it alone
        changeLED(i, currTime);
      }
    }
    
    
    void changeLED(int place, unsigned long Time){
      if((states[place] == 1) && ((Time - prevTime[place]) >= on[place])){  // If the led has been on for the desired
                                                                            // amount of time, turn it off
        //Serial.println("Buoy " + String(place+1) + ": Off, Time Since last check: " + String(Time - prevTime[place]));
        prevTime[place] = Time;     // Save time that led was changed
        states[place] = 0;      // Save state of led
      }
      else if((states[place] == 0) && ((Time - prevTime[place]) >= off[place])){  // If the led has been off for the
                                                                                  // desired amount of time, turn it on
        if(place != 0){     // If we're not changing the first led, just turn it on and save the time/state
          //Serial.println("Buoy " + String(place+1) + ": On, Time Since last check: " + String(Time - prevTime[place]));
          prevTime[place] = Time;
          states[place] = 1;
        }
        else{     // Since the first led has an extra delayed blink, it gets special treatment
          if((count == 1) || (count == 6) || count == 18){        // If count is 1, 4, or 18 turn on the led. multiply count by 100
                                                                  // and you'll get the time in milliseconds. count increments every
            states[place] = 1;                                    // 100 milliseconds when the LED hasn't been turned off.
            //Serial.println("Buoy " + String(place+1) + ": On, Time Since last check: " + String(Time - prevTime[place]));
          }
          if(count == 48){    // if 6 seconds have passed since pattern started, reset the count for next sequence
            count = 0;
          }
          count++;  // Increment count and save time
          prevTime[place] = Time;
        }
      }
      digitalWrite(led[place], states[place]);
    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
Reply
  • mixx
    0 mixx over 5 years ago

    Wait a second... Nobody realized that you're trying to read an output? I'm almost 100% sure that's a no-no. You have to store the state in another variable. I'd suggest using arrays and just making it into one function. You can make a boolean array to store the states more easily, and advance the index using an increment in the loop. Either way, just store the state in a variable. I also just noticed the OP is from 2013, but I feel other people might check this forum for solutions so, here. This should work, I tested it on my uno. I also worked on a variation of this myself and i'll post it after I give it to my professor so it doesn't show up in an originality report haha. Here:

     

    // Which pins are connected to which LED
    
    const byte LED1 = 6;
    const byte LED2 = 7;
    const byte LED3 = 8;
    
    // Assigning delays.
    
    const unsigned long LED1_interval = 25;
    const unsigned long LED2_interval = 50;
    const unsigned long LED3_interval = 100;
    
    // Declaring the variables holding the timer values for each LED.
    
    unsigned long LED1_timer;
    unsigned long LED2_timer;
    unsigned long LED3_timer;
    
    //Saving states of led's in an array + index
    
    bool states[4] = {0, 0, 0, 0};
    int index = 0;
    
    // Setting 3 digital pins as output pins and resetting timer
    void setup ()
      {
      pinMode (LED1, OUTPUT);
      pinMode (LED2, OUTPUT);
      pinMode (LED3, OUTPUT);
      LED1_timer = millis ();
      LED2_timer = millis ();
      LED3_timer = millis ();
      } 
    // end of setup
    
    //LED1 loop that turns it ON if it is OFF and vice versa
    
    void toggle_LED1 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED1, HIGH);
          states[index] = HIGH;
       }
    
       else{
          digitalWrite (LED1, LOW);
          states[index] = LOW;
       }
    
      // remember when we toggled it
    
      LED1_timer = millis (); 
      } 
    // end of toggleLED_1
    
    //LED2 loop
    
    void toggle_LED2 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED2, HIGH);
          states[index] = HIGH;
       }
    
       else{
          digitalWrite (LED2, LOW);
          states[index] = LOW;
       }
    
      // remember when we toggled it
    
      LED2_timer = millis (); 
      }
    // end of toggle_LED2
    
      //LED 3 loop
    
    void toggle_LED3 ()
      {
       if (states[index] == LOW){
          digitalWrite (LED3, HIGH);
          states[index] = HIGH;
       }
       else{
          digitalWrite (LED3, LOW);
          states[index] = LOW;
       }
      // remember when we toggled it
    
      LED3_timer = millis (); 
      } 
    // end of toggle_LED3
    
    void loop ()
      {
      // Handling the blink of LED1.
    
      if ( (millis () - LED1_timer) >= LED1_interval)
         toggle_LED1 ();
    
     index++;          // Increment Index
    
      // Handling the blink of LED2.
    
      if ( (millis () - LED2_timer) >= LED2_interval)
        toggle_LED2 ();
    
    index++;           // Increment Index
    
    // Handling the blink of LED3.
    
      if ( (millis () - LED3_timer) >= LED3_interval)
         toggle_LED3 ();
    
    index = 0;          // Reset index to 0 for next run
    
    /* Other code that needs to execute goes here.
       It will be called many thousand times per second because the above code
       does not wait for the LED blink interval to finish. */
    }  // end of loop

     

    Edit: Ahh yes, forgot I said I'd post my own code that tackles this problem. Here it is, I seem to have some weird issues when initializing the states at low, and I also seemed to have another weird issue when running this that required adding a delay to setup. This solves it for some reason. I haven't looked into it all that much. If anyone knows what might be causing these issues please message me/reply to my post.

     

    // Variable Inits
    int led[4] = {4, 5, 6, 7}, count = 0, cot = 0; // Create array with led pins and int 'count'
    
    
    bool states[4] = {1, 1, 1, 1);  // Create a boolean array to store led states
    
    
    unsigned long prevTime[5], currTime;  // Create an array to store the previous time an led is checked, and
                                              // a variable to store the current time when checked for each loop
                                              
    long off[4] = {100, 600, 2100, 3600}; // Create an array to store how long led's should be off
    long on[4] = {400, 400, 400, 400};  // Create an array to store how long led's should be on
    
    
    #define ledcount (sizeof(led)/sizeof(led[0])) // Use define to return the size of the array of led pins when calling 'ledcount'
                                                  // 'sizeof()' returns the size in bytes of a variable. For an array,
                                                  // you can take the total size of the array, and divide by the size
                                                  // of a single element to get the amount of values in the array
    void setup() {
      delay(1);
      for(int i = 0; i <= ledcount; i++){   // Initialize led pins as outputs
        pinMode(led[i], OUTPUT);
      }
        //Serial.begin(115200);
    }
    
    
    void loop() {
    
    
      currTime = millis();  // Save the current time in milliseconds since the program started running
      
      for(int i = 0; i <= ledcount; i++){   // Loop through each led and turn it on, off, or leave it alone
        changeLED(i, currTime);
      }
    }
    
    
    void changeLED(int place, unsigned long Time){
      if((states[place] == 1) && ((Time - prevTime[place]) >= on[place])){  // If the led has been on for the desired
                                                                            // amount of time, turn it off
        //Serial.println("Buoy " + String(place+1) + ": Off, Time Since last check: " + String(Time - prevTime[place]));
        prevTime[place] = Time;     // Save time that led was changed
        states[place] = 0;      // Save state of led
      }
      else if((states[place] == 0) && ((Time - prevTime[place]) >= off[place])){  // If the led has been off for the
                                                                                  // desired amount of time, turn it on
        if(place != 0){     // If we're not changing the first led, just turn it on and save the time/state
          //Serial.println("Buoy " + String(place+1) + ": On, Time Since last check: " + String(Time - prevTime[place]));
          prevTime[place] = Time;
          states[place] = 1;
        }
        else{     // Since the first led has an extra delayed blink, it gets special treatment
          if((count == 1) || (count == 6) || count == 18){        // If count is 1, 4, or 18 turn on the led. multiply count by 100
                                                                  // and you'll get the time in milliseconds. count increments every
            states[place] = 1;                                    // 100 milliseconds when the LED hasn't been turned off.
            //Serial.println("Buoy " + String(place+1) + ": On, Time Since last check: " + String(Time - prevTime[place]));
          }
          if(count == 48){    // if 6 seconds have passed since pattern started, reset the count for next sequence
            count = 0;
          }
          count++;  // Increment count and save time
          prevTime[place] = Time;
        }
      }
      digitalWrite(led[place], states[place]);
    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Reject Answer
    • Cancel
Children
No Data
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube