Some of the frequent contributors thought this might be a good example - for when the tutorial "Blink without Delay" example is not enough
/* Multiple independent delay - Two blinking LEDs
Working code example that blinks two LEDs, each with its own independent period.
This extends the BlinkWithoutDelay example of a single LED, showing how to
implement multiple independent timing paths in the main loop.
Written by several forum members. In public domain. Oct 2011.
Note: works even when millis () wraps around to zero after approximately 50 days.
*/
// Which pins are connected to which LED
const byte greenLED = 8 ;
const byte redLED = 10 ;
// Time periods of blinks in milliseconds (1000 milliseconds to a second).
// Time variable and constants are always unsigned long
const unsigned long greenLEDinterval = 555UL ;
const unsigned long redLEDinterval = 1234UL ;
// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer = 0 ;
unsigned long redLEDtimer = 0 ;
// Variable to know what the current LED state is
int greenLEDState = LOW ;
int redLEDState = LOW ;
void setup() {
pinMode (greenLED,OUTPUT) ;
pinMode (redLED,OUTPUT) ;
greenLEDtimer = millis () ;
redLEDtimer = millis () ;
}
void loop() {
// Handling the blink of one LED.
// First, check if it is time to change state
if ( (millis () - greenLEDtimer) >= greenLEDinterval ) {
// It is time to change state. Calculate next state.
if (greenLEDState == LOW)
greenLEDState = HIGH ;
else
greenLEDState = LOW ;
// Write new state
digitalWrite (greenLED, greenLEDState ) ;
// Reset timer
greenLEDtimer = millis () ;
}
// The other LED is controlled the same way. Repeat for more LEDs
if ( (millis () - redLEDtimer) >= redLEDinterval ) {
if (redLEDState == LOW)
redLEDState = HIGH ;
else
redLEDState = LOW ;
digitalWrite (redLED, redLEDState ) ;
redLEDtimer = millis () ;
}
/* Other code that needs to execute goes here.
It will be called many thousands of times per second because the above code
does not wait for the LED blink interval to finish. */
}