attachInterrupt vs. ISR(INT1_vect)


This study was carried out to find the total overhead of the attachInterrupt function.

To switch between both versions, just modify the #define statement accordingly.
You do not need any external hardware to run this program as the pin in question is triggered by software in the loop function.

You can enter more code into the int1 function matching your requirements.

/*
  Measure the overhead of "attachInterrupt"
  Measure the time between triggering
  the interrupt and entering the ISR.
  Results: 4 - 12 microseconds respectively Timer1 - Ticks:
  digitalWrite: 111
  sbi 11.3:      51
  PORT:          52
  Using ISR(INT1_vect) only 21 / 25 Ticks.
*/

// modify this to change behaviour accordingly
#define ATTACH

void setup() {
  Serial.begin(9600);
  Serial.println(__FILE__);
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  print("old TCCR1A: ", TCCR1A, " PWM");
  print("old TCCR1B: ", TCCR1B, " prescale: /64");
  TCCR1A = 0; // Timer/Counter Mode of Operation: NORMAL
  TCCR1B = 1; // = /1, fast
  print("new TCCR1A: ", TCCR1A, " NORMAL");
  print("new TCCR1B: ", TCCR1B, " prescale: /1");
  // INT1 is assigned to Pin-3
#ifdef ATTACH
  int x = RISING; // does not matter
  attachInterrupt(1, int1, x);
#else
  EICRA = B00001100; // configure INT1 for rising
  EIMSK = B00000010; // interrupt mask for INT1
#endif
}

volatile byte t1; // no overflow of TCNT1L expected
volatile boolean f;

void loop() {
  f = true;
  // reset Timer-1:
  TCNT1 = 0;
  // TCNT1 address: 0x84/0x85
  // trigger INT1 (three methodes):
  //digitalWrite(3, HIGH);
  //asm("sbi 11,3"); // PORT D, bit 3
  PORTD = B00001000;
  // wait until ISR is finished:
  while (f);
  byte t2 = TCNT1L - t1;
  // print results:
  print("time to enter: ", t1, " ticks");
  print("time to leave: ", t2, " ticks");
  digitalWrite(3, LOW);
  delay(100);
}

void print(String s, byte t, String u) {
  Serial.print(s);
  Serial.print(t);
  Serial.println(u);
}

#ifdef ATTACH
void int1()
#else
ISR(INT1_vect)
#endif
{
  t1 = TCNT1L;
  f = false;
}

/*
  ISR(INT1_vect)
  000006dc <__vector_2>:
  6dc: 1f 92         push  r1
  6de: 0f 92         push  r0
  6e0: 0f b6         in  r0, 0x3f  ; 63
  6e2: 0f 92         push  r0
  6e4: 11 24         eor r1, r1
  6e6: 8f 93         push  r24
  6e8: 80 91 84 00   lds r24, 0x0084 ; 0x800084 <TCNT1L>
  6ec: 80 93 e8 01   sts 0x01E8, r24 ; 0x8001e8 <t1>
  6f0: 10 92 e9 01   sts 0x01E9, r1  ; 0x8001e9 <f>
  6f4: 8f 91         pop r24
  6f6: 0f 90         pop r0
  6f8: 0f be         out 0x3f, r0  ; 63
  6fa: 0f 90         pop r0
  6fc: 1f 90         pop r1
  6fe: 18 95         reti
*/



contact: nji(at)gmx.de