BTNATmega328P01INTF001Istackpresses016 MHz1void setup() {2 Serial.begin(9600);3 pinMode(2, INPUT_PULLUP);4 attachInterrupt(5 digitalPinToInterrupt(2),6 onPress, FALLING);7}1volatile byte presses = 0;2void onPress() { // ISR3 presses++;4}5void loop() {6 Serial.println(presses);7 delay(1000);8}5 V HIGH0 V LOWPCret+1
Back: the board (button, pin 2 trace, ATmega328P with its flag, I bit and memory, clock)Front: the sketch on two cards, setup() and the ISR with loop()Tokens: the PC, the falling edge, the return address, +1 and clock ticksAn Arduino Uno R3 with a button from pin 2 to ground. setup() calls attachInterrupt(digitalPinToInterrupt(2), onPress, FALLING). A press pulls pin 2 from 5 V to 0 V, a falling edge that sets the INTF0 flag; the CPU saves its place on the stack, clears the I bit and runs onPress(), which adds 1 to presses, then RETI returns to delay() exactly where it stopped. The hardware part takes 7 cycles (0.4375 µs) at 16 MHz; the Arduino wrapper makes it about 3 µs to your first line.

Why and where

  1. Our Uno spends almost all its time inside delay(1000). If loop() read the button once per pass, a quick press during the wait would be missed. An interrupt makes the hardware call a function the moment pin 2 changes.

Setting it up

One interrupt

Latency

What happens

;; step 1/10 · busy
loop()    Serial.println(presses); delay(1000);
polling   read the pin once per pass: a short press can fall between reads
interrupt the pin itself asks the CPU to run a function, at once

// Arduino Uno R3: a push button from pin 2 to GND
volatile byte presses = 0;
void onPress() {  // ISR
  presses++;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(
   digitalPinToInterrupt(2),
   onPress, FALLING);
}

void loop() {
  Serial.println(presses);
  delay(1000);
}

The two cards are one sketch: the global presses and onPress() come first, then setup() and loop(). Arduino code runs init() before setup(), and init() turns interrupts on, so the I bit is already 1 when setup() starts. The 0.44 µs is the datasheet minimum (4 + 3 cycles at 16 MHz); a multi-cycle instruction in progress adds its remaining cycles, and waking from sleep adds 4 more cycles plus the sleep mode's start-up time. The wrapper figures (82 cycles, 2.9375 µs before and 2.1875 µs after) were counted by N. Gammon from the compiled code; another compiler version can differ a little.