Using Interrupts

Here is some code I made up. I also made it into a library :slight_smile:

//execute function g() every interval ms
void timer(unsigned long interval, void (*g)()){
  static unsigned long prev = 0;
  if (millis() - prev >= interval){
    g();
    prev = millis();
  }
}
//execute function g() every interval ms, times times only
void timer(unsigned long interval, void (*g)(), unsigned long times){
  static unsigned long prev = 0;
  static unsigned long counter = 0;
  if (millis() - prev >= interval && counter < times){
    g();
    prev = millis();
    counter++;
  }
}
//function to be run
void blinking(){
  static boolean state = 1;
  digitalWrite(13, state);
  state = !state;
}
void fading(){
  static byte brightness = 0;
  static int fadeAmount = 1;
  analogWrite(9, brightness);    
  brightness = brightness + fadeAmount; 
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ; 
  }      
}
void setup(){
  pinMode(13, OUTPUT);
}
void loop(){
  //blink the LED on pin 13 every 500 ms 5 times only
  timer(500, blinking, 5);
  //fade an LED on pin 9 forever...
  timer(30, fading);
}

This will not halt your program in any way. Just don't use delay if you use my code! This code demonstrates multitasking without delay. It uses millis().