Go Down

Topic: How to light two leds with different blink rates at the same time? (Read 456 times) previous topic - next topic

westonkeyes

Hello,

   I would like to learn how to do this but don't know which direction to go in. I you could tell me which programming function to use I will read up on it. The code below works for lighting  leds sequentially but I want to have them both lit at the same time and running there own blink pattern continually.
Thanks in advance.

Wes Keyes

Code: [Select]
/*
 Blink
 Turns on an LED on for one second, then off for one second, repeatedly.

 This example code is in the public domain.
*/

void setup() {                
 // initialize the digital pin as an output.
 // Pin 13 has an LED connected on most Arduino boards:
 
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
void loop() {
 digitalWrite(13, HIGH);   // set the LED on
 delay(750);              // wait for a second
 digitalWrite(13, LOW);    // set the LED off
 delay(1000);              // wait for a second
 digitalWrite(13, HIGH);   // set the LED on
 delay(2000);              // wait for a second
 digitalWrite(13, LOW);    // set the LED off
 delay(750);              // wait for a second  
 digitalWrite(12, HIGH);   // set the LED on
 delay(750);              // wait for a second
 digitalWrite(12, LOW);    // set the LED off
 delay(750);              // wait for a second
 digitalWrite(12, HIGH);   // set the LED on
 delay(3000);              // wait for a second
 digitalWrite(12, LOW);    // set the LED off
 delay(750);              // wait for a second  
}


Moderator edit: CODE TAGS.

PaulS

Code: [Select]
  delay(750);              // wait for a second
This ensures that NOTHING else happens at the same time.

As we tell everyone else, look at the blink without delay example, without delay.

AlxDroidDev

#2
Mar 20, 2013, 02:31 pm Last Edit: Mar 20, 2013, 02:33 pm by AlxDroidDev Reason: 1
Use millis() instead of delay().

for each of the leds you want to blink, keep a global variable (it will be it's elapsed time variable) that will store the last time (millis()) the led was switched on/off. Then, at each iteraction of the loop() function, check to see if the amount of time required for that LED has elapsed, and if so, do whatever you want with that led and set it's time variable to the current millis().

This will be a non-blocking approach, and you'll be able to have as many leds you want, each with different rate.

EDIT:

Here is a tutorial for the several approaches, including the one I described above:
http://www.cmiyc.com/blog/2011/01/06/millis-tutorial/
Learn to live: Live to learn.
Showing off my work: http://arduino.cc/forum/index.php/topic,126197.0.html

Go Up