Interrupts in firmware: attachInterrupt, edges and latency
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.
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);
}Read the lesson step by step
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); }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()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 onA 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: LOWThe 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)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()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 timeBack 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 1Latency: 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 returnsWhen 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
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01On an Arduino Uno R3, which pins can you use with attachInterrupt?
On the Uno (ATmega328P) attachInterrupt works on pins 2 and 3, which are INT0 and INT1 inside the chip. digitalPinToInterrupt(2) returns 0 and digitalPinToInterrupt(3) returns 1.
02A button connects pin 2 to ground, and pin 2 uses INPUT_PULLUP. Which mode fires once when the button is pressed down?
The pull-up holds the pin HIGH (5 V). Pressing pulls it to ground, LOW: a change from HIGH to LOW is a falling edge. LOW would keep firing for as long as the button is held, and HIGH is not available on the Uno.
03What does the CPU do first when the INT0 interrupt is served?
The ATmega328P finishes the instruction in progress, pushes the program counter onto the stack and clears the global interrupt enable (I) bit, then jumps through the INT0 vector. RETI later pops the address and sets the I bit again.
04At 16 MHz, how long do the datasheet's minimum 4 response cycles plus the 3-cycle jump take?
One cycle is 1 / 16 MHz = 62.5 ns, and 7 × 62.5 ns = 437.5 ns = 0.4375 µs. The Arduino wrapper adds register saving and a call through a pointer, making it about 3 µs before your first line runs.
05Interrupts are switched off with noInterrupts() while the button is pressed twice. What happens when interrupts are switched back on?
The flag is set by the first edge and stays set; the second edge cannot set it any further. When the I bit returns to 1, the pending interrupt runs once. Long stretches with interrupts off can therefore lose events.
Glossary
- Interrupt
- A hardware event that makes the CPU pause the main program between two instructions, run a short function, then resume.
- ISR (interrupt service routine)
- The function that runs when an interrupt fires, such as onPress(). It should be as short and fast as possible.
- attachInterrupt()
- The Arduino function that connects an ISR to an interrupt pin and chooses the mode: LOW, CHANGE, RISING or FALLING.
- Falling edge
- The moment a signal drops from HIGH to LOW. A rising edge is the change from LOW to HIGH.
- Pull-up resistor
- A resistor that holds an input HIGH when nothing drives it. INPUT_PULLUP turns on one inside the ATmega328P (20 to 50 kΩ).
- Interrupt flag
- A bit the hardware sets when the event happens (INTF0 for INT0). It remembers the request until the ISR runs.
- I bit (global interrupt enable)
- A bit in the status register. When it is 0, no interrupt can start; the hardware clears it on entry to an ISR and RETI sets it again.
- Register
- One of the CPU's few small working slots, each holding a byte it is working on right now. An ISR must save the ones it uses and put them back before returning.
- Stack
- A reserved strip of RAM where the CPU parks values to come back to, last in, first out. On an interrupt it pushes the return address there; RETI pops it off.
- Interrupt vector
- A fixed slot in flash, one per interrupt, holding a jump to its handler. On the ATmega328P the INT0 vector is at address 0x0002.
- RETI (return from interrupt)
- The instruction that ends an ISR: it pops the return address off the stack and sets the I bit again, in 4 clock cycles.
- volatile
- A C/C++ keyword that tells the compiler a variable can change behind its back (for example in an ISR), so it must reread it from memory every time instead of keeping a stale copy.
- Latency
- The time from the event to the first line of your ISR: a few hardware cycles plus any code the compiler adds.
Notes and sources
- 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.
- presses is a byte on purpose: the 8-bit AVR reads one byte in a single instruction, so loop() can never see half an update. A bigger counter needs the care shown in the lesson "volatile and sharing data with an ISR".
- A real button bounces: its contacts can open and close several times in a few milliseconds, and each bounce is another falling edge. Debounce it, as in the lesson "Debouncing a button", before trusting the count.
- 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.
- The AVR clears the I bit when it enters an ISR, so ISRs do not interrupt each other unless you turn the bit back on yourself. Pending interrupts then run in priority order: on the ATmega328P, INT0 comes first, right after RESET.
- Every ATmega328P I/O pin also has a pin change interrupt (PCINT), which fires on any change and is shared by a group of pins. attachInterrupt does not use those: on the Uno it only offers INT0 and INT1, pins 2 and 3.
- Arduino language reference: attachInterrupt()
- Arduino language reference: attachInterrupt() (source)
- Arduino AVR core: WInterrupts.c (how attachInterrupt sets EICRA and EIMSK, and ISR(INT0_vect))
- Arduino AVR core: pins_arduino.h for the Uno (digitalPinToInterrupt)
- Arduino AVR core: Arduino.h (FALLING, RISING, CHANGE, INPUT_PULLUP)
- Arduino AVR core: wiring.c (init() enables interrupts before setup())
- Microchip ATmega328P datasheet (DS40002061B): §7.7 Reset and Interrupt Handling, §13 External Interrupts
- N. Gammon, Interrupts (cycle count of the attachInterrupt wrapper)
- J. W. Valvano, Embedded Systems: Shape the World, ch. 12: Interrupts (UT Austin)
Quiz Unlocks after the last step.