[Reference] Useful timed structures with millis()

Questions about the Waspmote board and its modules
Post Reply
libelium-dev
Posts: 27967
Joined: Mon Sep 28, 2009 1:06 pm

[Reference] Useful timed structures with millis()

Post by libelium-dev » Wed Jul 09, 2014 5:25 pm

There is a useful function called millis(), which returns the program execution time in milliseconds. This timer increases its value internally without any action, therefore it can be used for timed structures inside your code.

For example, you can use millis() in combination with a while loop to limit the amount of time inside the loop, avoiding infinite loops.
// Set timer 1 to 5 seconds
unsigned long TIMEOUT = 5000;
// Aux variables
unsigned long previous = 0;

void setup()
{
}

void loop()
{
  // Added a timeout to avoid stopping the code.
  previous = millis();
  while(((millis() - previous) < TIMEOUT) )
  {
    // Wait inside this loop during TIMEOUT
    // Do your stuff here.
    USB.println("waiting for timeout");
    delay(1000);

    // Condition to avoid an overflow (DO NOT REMOVE)
    if( millis() < previous ) previous=millis();
  }

  // If here, timeout has elapsed.
  USB.println("TIMEOUT!");
}
Another example is to trigger an action only if a certain time (TIMEOUT) has elapsed.
// set timer to 1 second
unsigned long TIMEOUT = 1000;
// aux variable
unsigned long previous = 0;

void setup()
{
  // initialize timer
  previous = millis();
}

void loop()
{
  if((millis() - previous) > TIMEOUT)
  {
    // If here, timeout!
   
    USB.println("timeout!");

    // Reset timer.
    previous = millis();

    // Condition to avoid an overflow (DO NOT REMOVE)
    if( millis() < previous ) previous=millis();
  }
}

Finally, next example uses millis() to implement a structure with two timers. When the first timer has elapsed, the second starts with a different time period. Once timer 2 has elapsed, bot are reset. Millis value is printed every second.
// Set timer 1 to 10 seconds
unsigned long TIMEOUT = 10000;
// Set timer 2 to 4 seconds
unsigned long TIMEOUT2 = 4000;
// Aux variables
unsigned long previous = 0;
unsigned long previous2 = 0;
uint8_t startTimer2 = 0;

void setup()
{
  // Initialize timer 1
  previous = millis();
}

void loop()
{
  // Print millis()
  USB.println(millis());
  delay(1000);

  if((millis() - previous) > TIMEOUT)
  {
    // If here, timer 1!
    USB.println("Timer 1");
    
    // Initialize timer 2 only first time.
    if (startTimer2 == 0)
    {
      previous2 = millis();
      startTimer2 = 1;
    }

    if((millis() - previous2) > TIMEOUT2)
    {
      // If here, timer 2!
      USB.println("Timer 2");
      USB.println(F("Reset timers"));
      previous = millis();
      startTimer2 = 0;
    }
  }
}
Hope these code structures are useful in your applications.

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest