converting delay code to interrupt:Metronome

I have some code for a metronome that I wrote, currently set by variable. It calculates a delay value, and blinks an LED. Here it is:

int ledPin = 13;                 // LED connected to digital pin 13
int val = 0;                     // variable for reading the pin status
int del = 126;
int delval = 0;

int calc(int val)
  val = val / 60;        //Gets BEats per second
  val = 1000 / val;    //Gets Milliseconds for delay
  val = val - 71;        //value obtained by guess and check for LED time
  return val;

void setup()
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output

void loop()
  delval = calc(del);
  digitalWrite(ledPin, HIGH);  // sets the LED on
  delay(50);                   // waits for a second
  digitalWrite(ledPin, LOW);   // sets the LED off
  delay(delval);                  // waits for a second

I would like to turn this into a program that uses interrupts, so that it exandable. Ex. Potentiometer,LCD, piezo output

The only problem is that I can’t figure out how to apply timer interrupts. I have searched for a while, so I figured I’d ask the forum for help.

Do you REALLY want to use interrupts, or do you just want to avoid the use of “delay” so that you can do other things. If you DO use a real timer interrupt, you’ll conflict with the arduino environment’s (potential) use of those timers for PWM and such. That’s OK, but you might get by with using the existing timer interrupt indirectly, something like:

unsigned long nexttick;
unsigned char tickstate;

loop() {
   if (millis() >= nexttick) {      /* See if it's time for a "tick." */
       if (tickstate == LOW) {  /* reverse state of pin */
         digitalWrite(ledPin, HIGH);
         tickstate = HIGH;
       } else {
         digitalWrite(ledPin, LOW);
         tickstate = LOW;
       nexttick += calc(val);
    * no tick, or tick finished.  We can do other things as long
    * as they don't take too long.

The technique of computing a time in the future and comparing agains millis() is essentially how delay() works internally, by the way.

The easiest way to break into “real” interrupts would probably be to modify the arduino support code in …/lib/targets/arduino/wiring.c; you can attach your code to the same function that modifies timer0_overflow_count