The Arduino IDE provides a function, attachInterrupt(), that can set-up external interrupts for you. The Arduino Mega 2560 has six available external interrupts, INT5:0. The ATmega2560 chip has eight external interrupts total, but the Arduino only connects six of those pins to headers. If you are going to be setting the interrupt registers yourself and choose not to use the provided function, be warned that the interrupt numbers don't necessarily correspond to the same pins listed below.
The External Interrupts are connected to the following Pins when using attachInterrupt():
Digital Pin
INT5 : 18
INT4 : 19
INT3 : 20
INT2 : 21
INT1 : 3
INT0 : 2
The attachInterrupt() function uses three parameters to customize the interrupt:
- Interrupt Number: Found in the left column in list above. Attach your sensor to the corresponding pin.
- Function Name: The function that will be called when the interrupt occurs. This would be your Interrupt Service Routine if you were using a different micro-controller.
- Trigger Mode: Determines when the interrupt will be triggered. Can be one of four values: RISING, FALLING, CHANGE, and LOW.
- RISING: Triggers the interrupt only when the pin changes from low to high; a rising clock edge
- FALLING: Triggers the interrupt only when the pin changes from high to low; a falling clock edge
- CHANGE: Triggers when the pin changes from either low to high or high to low; any clock edge
- LOW: Triggers when the pin is low
Let's apply an interrupt to the following sketch:
int button_state = 0; // variable for storing button's status
void setup() {
pinMode(53, OUTPUT); //Set LED on PIN53 to output
pinMode(52, INPUT); //Set button on PIN52 as input
}
void loop(){
button_state = digitalRead(52); //Read state of button
if (button_state == HIGH) { //If HIGH, the button has been pressed
digitalWrite(53, HIGH); //Turn LED on
}
else { //If LOW, button is open
digitalWrite(53, LOW); //Turn LED off:
}
}
The sketch controls the state of an LED by polling a tactile button. When the button is pressed, the LED toggles ON/OFF. You can make the program more efficient by replacing the need for polling with an external interrupt.
More SCIENCE!
The following code sets up an External Interrupt using the attachInterrupt() function:
void setup(){
pinMode(53, OUTPUT);
attachInterrupt(0, button, CHANGE);
}
void loop(){
}
void button(){
state = !state;
digitalWrite(53, state);
}
If you are using a switch(button) for your interrupt trigger, you need to make sure to debounce the input (which I haven't) or the Arduino may read a single button press as multiple presses. The Arduino website offers one solution for a software debounce here. Normally, you could get away with just using a delay after the button press, but the delay() function is disabled inside of interrupt routines.


