Playground.arduino.cc will be read-only starting December 31st, 2018. For more info please look at this Forum Post

MsTimer2 is a small and very easy to use library to interface Timer2 with humans. It's called MsTimer2 because it "hardcodes" a resolution of 1 millisecond on timer2.

Updated again:

UPDATED:

  • works on ATmega1280 (thanks to Manuel Negri).
  • works on ATmega328 (thanks Jerome Despatis).
  • works on ATmega48/88/168 and ATmega128/8.

Methods

MsTimer2::set(unsigned long ms, void (*f)())
this function sets a time on ms for the overflow. Each overflow, "f" will be called. "f" has to be declared void with no parameters.
MsTimer2::start()
enables the interrupt.
MsTimer2::stop()
disables the interrupt.

Source code

License: LGPL

MsTimer2.zip

Install it on {arduino-path}/libraries/

Example

// Toggle LED on pin 13 each second
#include <MsTimer2.h>

void flash() {
  static boolean output = HIGH;

  digitalWrite(13, output);
  output = !output;
}

void setup() {
  pinMode(13, OUTPUT);

  MsTimer2::set(500, flash); // 500ms period
  MsTimer2::start();
}

void loop() {
}

Further examples on the Web

Bugs

send any bug to javiervalencia80 [at] gmail.com