ATmega328P/Digital pins/21. Interrupts on D2 and D3
Digital pins · 21 of 33

Interrupts on D2 and D3

attachInterrupt makes the chip watch D2 or D3 itself and run a short function the instant the pin changes, even while loop() is stuck in delay(). Only those two pins have it on the ATmega328P. The function must be short, its variables volatile, and it must not print.

Your board

The chip can watch a pin for you

A sketch that polls a pin only sees it when loop() gets round to reading it. A delay(500) means half a second of not looking. An interrupt moves the watching into hardware: the chip notices the pin change, stops whatever the sketch is doing between two instructions, runs a function you gave it, and goes back to exactly where it was.

On the ATmega328P, and so on both boards, only two pins can do this directly. D2 is INT0 and D3 is INT1.

attachInterrupt(digitalPinToInterrupt(2), onFall, FALLING);

digitalPinToInterrupt(2) turns the pin number into the interrupt number, 0; writing the pin through it rather than the bare number keeps sketches portable to boards where the numbers differ. onFall is the function to run, the interrupt service routine or ISR. FALLING says when: on HIGH to LOW. The other choices are RISING, CHANGE (both edges) and LOW (repeatedly, for as long as the pin is held low).

What happens when the edge arrives

The ISR cuts into loop()
ISR: count++
What the ISR does
count
0
Printed
-
loop() paused for
-
Press Run it. loop() prints the count and sleeps in delay(500); D2 is held HIGH by its pull-up.

The edge arrives in the middle of delay(500). The ISR runs, adds one to the count, and returns; loop() carries on with its delay and prints the new count the next time it gets there. The chip catches an edge longer than one clock cycle, 62.5 ns at 16 MHz, so it sees bounces no polling loop could.

Three rules for the ISR

Keep it short. While an ISR runs, other interrupts wait, including the timer behind millis(). Arduino's reference says delay() does not work inside an ISR and millis() does not advance. Count, note a time, set a flag, return.

Make shared variables volatile. The ISR changes count behind loop()'s back. Without volatile, the compiler may assume nothing changed it and reuse an old copy. A counter wider than one byte has a second trap: loop() reads it in two halves, and an interrupt between them gives a value that was never stored. The sketch copies it with interrupts off for the two instructions that takes:

noInterrupts();
unsigned int n = count;
interrupts();

Do not print from it. Serial.print works by filling a 64-byte buffer that another interrupt empties. Inside an ISR, once that buffer is full, each character waits for the wire, about a millisecond at 9600 baud, with the whole sketch stopped. Print from loop().

The other pins

Every other pin has a weaker relative, the pin change interrupt, except the Nano's A6 and A7, which are analogue inputs only and have none. It fires on any change, rising or falling, and pins share one per group of up to eight, so the ISR has to work out which pin changed. attachInterrupt does not set these up; libraries such as PinChangeInterrupt do. For one or two signals, D2 and D3 are the simple answer.

The code

Count_With_Interrupt.ino

Counts every falling edge on D2 in an interrupt routine and prints the count twice a second from loop(). Upload it, put one end of a jumper wire in the 2 hole and tap the other into a GND hole.

// Count_With_Interrupt.ino — counts falling edges on D2 in an ISR
// Tools > Board: Arduino Uno, or Arduino Nano with
//   Processor ATmega328P (Old Bootloader if the upload says
//   "not in sync")
// Tools > Port: the CH340 port
// Wiring: one jumper wire from the 2 hole, touched to a GND hole.
// D2 is INPUT_PULLUP, so the wire is safe. D2 is INT0.

const byte PIN = 2;

volatile unsigned int count = 0;   // changed by the ISR

void onFall() {    // the ISR: short, no Serial, no delay()
  count++;
}

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

void loop() {
  noInterrupts();           // copy all bytes at once
  unsigned int n = count;
  interrupts();

  Serial.println(n);        // printing is loop()'s job
  delay(500);               // the ISR still counts in here
}

loop() spends almost all its time in delay(500) and still misses nothing. The count includes the bounces, often more of them than the polling sketch saw, because the hardware catches edges far shorter than one pass of loop().

When it does not work

attachInterrupt compiles but nothing is ever counted

Check the pin is 2 or 3 and that the call goes through digitalPinToInterrupt(pin). On the UNO and the Nano, digitalPinToInterrupt returns NOT_AN_INTERRUPT for every other pin, and the call then silently does nothing.

The count is printed wrong, or jumps

The counter must be volatile, or the compiler may keep a copy in a register that loop() never refreshes. It is also two bytes on an 8-bit chip, so copy it with interrupts off, as the sketch does, or the ISR can change it between the two halves.

millis() runs slow, or the sketch freezes, after adding a print to the ISR

Interrupts are off while an ISR runs. A long ISR holds back the timer interrupt behind millis(), and once Serial's 64-byte buffer is full each character waits about a millisecond at 9600 baud. Count or set a flag in the ISR, and print from loop().

One tap counts several times

That is contact bounce, and an interrupt sees all of it. Debounce in loop() with the millis() lockout from the previous article, or record millis() in the ISR and ignore edges that come too soon after the last one.

Where this goes next

From HIGH and LOW to a number from 0 to 1023, and what one step is worth in volts.

analogRead: 1024 steps →

Edit this page — content/books/atmega328p/interrupts-on-d2-and-d3.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Modules and blocks on the forum →