Periodically Called Functions Made Easy With the Timers Library

DIGILENT-StdLogo-3000Hey, everyone! Are you getting your week started right by using our awesome MPIDE for your programming needs? Are you just getting started with MPIDE? One of the first major functions used when starting out in MPIDE is the delay() function, as it makes it easy to see an LED blink on and off. However, once things get more complicated and multiple operations become necessary (e.g., configuring multiple digits on a 7-segment to display well as processing the data to display). The Timers library provides a way to easily define functions that should be called periodically. For example, function foo() should be called every 10 milliseconds. Getting it set up is easy too, as the example below shows:

Timers t;
int LED_state = LOW;

void blinkLED()
{
  LED_state = !LED_state;
  digitalWrite(13,LED_state);
}

void setup()
{
  pinMode(13,OUTPUT);
  t.addTimer(1000,blinkLED);
}

void loop()
{
  t.update();
}

As you can see, the Timers library really is easy to use. Just place the block of code you want to run periodically inside a new function, and then use “addTimer” to add that function with its period (time between calls; the delay as it were).

There is more to this library than that, however. Whenever you add a new timer, it returns an ID to that timer. This, coupled with with the other functions, allows us to remove timers, enable or disable timers, or even change a timer’s period. One other neat thing is that we can set is the timer resolution, whether it uses milliseconds or microseconds for its period.

You can find more information and the current version on the github for Timers, and the tutorial that covers the design behind this library will be available on the Learn website at a future date.

I’ll end this post with a sketch that uses some of these functions so that you can see how it might be useful. This code enables and disables the blinking LED on pin 13 whenever it receives data from Serial, which it checks every tenth of a second.


Timers t;
int blinkID;

int pinLED = 13;
int state = LOW;

void blinkLED()
{
  state = !state;
  digitalWrite(pinLED,state);
}

void checkSerial()
{
  static bool en = true;
  if(Serial.available() > 0){
    // Clear out the Serial buffer
    while(Serial.read() >= 0){}
    en = !en;
    if(en){
      t.enableTimer(blinkID);
    }else{
      t.disableTimer(blinkID);
    }
  }
}

void setup()
{
  pinMode(pinLED, OUTPUT);
  blinkID = t.addTimer(1000, blinkLED);
  t.addTimer(100, checkSerial);
  Serial.begin(9600);
}

void loop()
{
  t.update();
}



Be the 1st to vote.

Leave a Reply

Your email address will not be published. Required fields are marked *