ENع
←Interrupts in firmware
Lesson 13 · Interrupts, timers and PWM

Interrupts in firmware: attachInterrupt, edges and latency

12 min10 steps5 questionsIntermediate
About this lesson

An interrupt lets a pin pause your main code, run a short function and hand control straight back. On an Arduino Uno R3 we wire a button to pin 2, call attachInterrupt(digitalPinToInterrupt(2), onPress, FALLING), and follow one press through the chip: the falling edge sets the INTF0 flag, the CPU saves its place on the stack, runs the ISR, and returns into delay() as if nothing happened. Then we measure the cost: 7 clock cycles (0.4375 µs) in hardware, about 3 µs with the Arduino wrapper. The Hardware lesson “Interrupts and I/O: how devices get the CPU's attention” explains why polling wastes time; here you write the firmware.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 13 · Interactive
01 / 10

Busy, but not blind

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.

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);
}
Loading figure…
or ← →
Read the lesson step by step
  1. Busy, but not blind

    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.

    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);
    }
  2. Only pins 2 and 3

    On the Uno, attachInterrupt only works on pins 2 and 3. Inside the ATmega328P they are named INT0 and INT1. digitalPinToInterrupt(2) turns pin 2 into interrupt number 0, so the same code works on other boards.

    pin 2   PD2   INT0   digitalPinToInterrupt(2) = 0
    pin 3   PD3   INT1   digitalPinToInterrupt(3) = 1
    other pins  NOT_AN_INTERRUPT
    other boards map other pins: always use digitalPinToInterrupt()
  3. attachInterrupt sets it up

    In setup(), attachInterrupt stores the address of onPress, our interrupt service routine (ISR): the function that runs when the interrupt fires. It sets EICRA's sense bits, which choose which edge counts, to FALLING, and switches INT0 on.

    attachInterrupt(digitalPinToInterrupt(2), onPress, FALLING)
      intFunc[0] = onPress            remember the function
      EICRA ISC01:ISC00 = 10       FALLING = 2: falling edge
      EIMSK INT0 = 1                  INT0 switched on
  4. A press is a falling edge

    INPUT_PULLUP turns on a resistor inside the chip (20 to 50 kΩ) that holds pin 2 at 5 V, HIGH. Pressing connects the pin to ground: 0 V, LOW. That drop is a falling edge. Other modes: RISING, CHANGE, or LOW.

    idle      pull-up 20-50 kOhm to 5 V  ->  pin 2 HIGH
    pressed   button to GND               ->  pin 2 LOW
    HIGH -> LOW   falling edge   FALLING
    LOW -> HIGH   rising edge    RISING
    either        CHANGE         while low: LOW
  5. The edge sets a flag

    The edge sets one bit, the INTF0 flag. The CPU is deep inside delay() and does not stop to look; the hardware checks the flag between instructions. Even a pulse just over one tick of the 16 MHz clock, 62.5 ns, is caught.

    falling edge on PD2  ->  EIFR.INTF0 = 1
    CPU       still in delay(1000)
    checked   between instructions, by hardware
    caught    any edge pulse longer than one clock period (62.5 ns)
  6. Save the place, jump

    The CPU finishes its instruction and parks the return address (where to come back to) on the stack, a reserved strip of RAM. It clears the I bit and INTF0, then jumps through the INT0 vector, a fixed slot in flash at 0x0002, to onPress.

    finish the current instruction
    push   return address (2 bytes) onto the stack
    I bit  1 -> 0     no other interrupt can start
    INTF0  1 -> 0     cleared by hardware
    jump   vector 0x0002 (INT0)  ->  ISR(INT0_vect)  ->  onPress()
  7. The ISR runs

    onPress() runs and presses goes from 0 to 1. Keep an ISR short: inside one, delay() does not work, millis() stops advancing and incoming serial data can be lost. presses is volatile: the compiler must reread it from memory every time.

    line 3    presses++;     0 -> 1
    inside an ISR:
      delay()    does not work
      millis()   does not advance
      Serial     incoming data may be lost
    volatile: the compiler must reread presses every time
  8. Back where it left off

    The ISR ends with RETI (return from interrupt). It pops the return address off the stack and sets the I bit again. delay() carries on exactly where it stopped, and the next pass prints 1. The main code never noticed.

    RETI   4 cycles
      pop the return address from the stack
      I bit 0 -> 1
    back in delay(1000), same place
    next pass: Serial.println(presses) prints 1
  9. Latency: edge to your code

    Latency: the time from the edge to your code. One tick is 62.5 ns. The hardware needs 4 ticks to save the place and 3 to jump: 0.44 µs. The Arduino wrapper then saves registers, the CPU's few working slots: about 3 µs in all.

    tick        1 / 16 MHz = 62.5 ns
    hardware    4 (push PC) + 3 (jump) = 7 cycles = 0.4375 µs
                plus the rest of a multi-cycle instruction
    wrapper     ISR(INT0_vect) saves registers, calls intFunc[0]
                about 2.9375 µs (47 cycles) before onPress starts
                2.1875 µs more after it returns
  10. When interrupts must wait

    Latency grows while interrupts are off: inside another ISR, or after noInterrupts(). The flag holds the press until the I bit is 1 again, then onPress runs. But a flag is one bit: two presses while waiting count as one.

    I bit 0     (another ISR, or noInterrupts())
    press 1     INTF0 = 1   remembered
    press 2     INTF0 = 1   already 1: lost
    I bit 1     onPress runs once
    presses     1 -> 2, not 3

Quiz Unlocks after the last step.