Arduino Programming Language: AttachInterrupt

Name

attachInterrupt()

Description

 This command specifies a named Interrupt Service Routine (ISR) to call when an interrupt occurs.   

Most Arduino boards have two external interrupts: int. 0 (on digital pin 2) and int.1 (on digital pin 3). 
There are some Arduino board that have others interrupt. 
For example in Arduino Mega 2560 have others four interrupts: int.2 (pin 21), int.3 (pin 20), int.4 (pin 19), int.5 (pin18). 
While in Arduino Leonardo have int.0(pin 3),int.1(pin2),int.2 (pin 0), int.3 (pin 1), int.4 (pin 7).

Board int.0 int.1 int.2 int.3 int.4 int.5
Uno, Ethernet 2 3        
Mega2560 2 3 21 20 19 18
Leonardo 3 2 0 1 7  
Due (see below)

The Arduino Due board allows to attach an interrupt function on all available pins. 
Instead the Arduino M0, M0 Pro and Zero Pro boards can use as interrupt pins all pins except D2.

Board int.0 int.1 int.2 int.3 int.4 int.5 int.6 int.7 int.8 int.9 int.10 int.11 int.12 int.13
M0/M0 Pro 0 1 5 6 7 10  11 12 13 

Note:
In the new Arduino Primo, you can use all pins except the 0 and 1 pins as interrupt pins. But keep in mind that you can't use more than 8 interrupt pins at the same time.

Syntax

attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);
attachInterrupt(interrupt,function, mode)
attachInterrupt(pin,ISR, mode) (Arduino Due only)

Parameters

  • interrupt: the number of the external interrupt to enable
  • pin: the pin number of the interrupt to enable
  • ISR: the name of the function to be called whenever the interrupt event happens. This function must take no parameters and return nothing.
  • mode: there are four valid mode:
    • LOW: sets to trigger the interrupt when the pin is low.
    • CHANGE: sets to trigger the interrupt when the pin changes value.
    • RISING: sets to trigger the interrupt when the pin goes from low to high.
    • FALLING: sets to trigger the interrupt when the pin goes from high to low.
    • HIGH (Arduino Due Only):sets to trigger the interrupt when the pin is high.

Returns

none 

Usage

Application

Note

Inside the attached function, delay() won't work. 
Serial data received while in the function may be lost. 
You should declare as volatile any variables that you modify within the attached function.

Examples

int pinLed = 4;
volatile int state = LOW;
void setup()
{
pinMode(pinLed, OUTPUT);
attachInterrupt(1, interrupt1, CHANGE);
Serial.begin(9600);
}

void loop()
{
digitalWrite(pinLed, state);
}

void interrupt1()
{
state = !state;
Serial.println("Interrupt");
}

Related Functions


Based on the reference originally written by Arduino Community,  wiring.org.co and  arduino.cc