how to add timer

instead of using "delay", i would like to use "timer". how do i declare and program for timer? Currently i m using arduino version 1.0.4 . Do i need to update in order to use this "timer" function?

reply ASAP
thank u :slight_smile:

how should i declare "timer" in arduino ? because i don't want to use delay function .

pandalay:
how should i declare “timer” in arduino ? because i don’t want to use delay function .

Gammon Forum : Electronics : Microprocessors : How to do multiple things at once ... like cook bacon and eggs !

Hi..

// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup () 
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();  
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();  
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval) 
    toggleRedLED ();

/* 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

In this code what is the use of millis() and what is the difference between greenLEDtimer and millis() ?

if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

ADI89:
In this code what is the use of millis() and what is the difference between greenLEDtimer and millis() ?

What is the use of a clock?

I'm not sure I understand you. You use millis() to find out how much time has elapsed.

greenLEDtimer is set to millis() so we know when we toggled the LED. As the comment above that line says.