Jun 052012
 

An Arduino program comprises two functions. Setup is executed once, whenever the Arduino is powered on or the reset button is pressed. Loop is then executed repeatedly until the power supply is removed.

There are occasions when you want the loop function to perform some action at regular intervals, or you want to perform some action then perform another action sometime afterwards. There are generally two ways of achieving this:

If you want to perform two tasks with a fixed period between them, say 2 seconds, you can perform the first task, then call delay, then call the second task. The loop function might look like:

loop()
{
  function1();
  delay(2000);
  function2();
}

This will work, and if that’s all your program needs to do, it’s a good way to code the solution.

If your program has to do other tasks however, using delay is not a good move. Delay is a blocking function – It’s called by loop but it doesn’t return until the period has expired. For example if your program needs to read a temperature sensor every 5 minutes but wants to flash an LED every 10 seconds, the following would not achieve the effect you want:

loop()
{
  delay(5 * 60 * 1000);
  getTemperature();
  delay(10000);
  flashLED();
}

It will wait 5 minutes, then it will get the temperature, then it will wait 10 more seconds then it will flash the LED. Then it will wait 5 minutes etc.

An alternative approach is to structure loop so it keeps track of the time and it performs different tasks depending how much time has passed. The code for the same problem would look like:

int LEDtimer = 0;
loop ()
{
  int secs = millis / 1000;
  if (secs % 300 == 0) { // i.e if it's fully divisible by 300
    getTemperature();
  }
  else if (secs % 10 == 0) { // i.e if seconds is wholly divisible by 10
    flashLED();
  }
  else {
    // Do other things
  }
}

There are other ways to keep track of the number of seconds elapsed, and you have to remember that millis will wraparound back to zero after around 50 days, but hopefully this is an adequate illustration.

I’m not saying that one approach is better, you have to choose based on the problem you’re trying to solve

 Posted by at 5:31 pm  Tagged with: