Example 3

Back to Arduino Interrupts

#if !defined (__AVR_ATmega328P__) 
#error "This sketch is designed for an Arduino Uno or Duemilenova.  You are using a different processor.  Check INT0 pin"

const byte LED = 13, SW = 2; // must be INT0 pin

void handleSW() { // ISR
    digitalWrite(LED, digitalRead(SW));

void handleOtherStuff() {

void setup() {
    pinMode(LED, OUTPUT);
    pinMode(SW, INPUT_PULLUP);
    attachInterrupt(INT0, handleSW, CHANGE);

void loop() {
    // handleSW();

Here, we have commented out the call to handleSW() within loop() and instead, in setup(), we registered handleSW as an interrupt service routine (ISR) for the external interrupt 0 interrupt.  Now, the Arduino hardware will monitor pin 2 and whenever the value changes, the code will be paused, the state of certain registers in the machine will be saved, handleSW will be called, the registers will be restored and the code will continue where it got interrupted. The result is once again “instantaneous” response to the user input even if the main code is in the middle of the delay(250);

I will note that this code is designed for an ATmega328P chip, which is the one on an Arduino Uno and on a Duemilenova.  If your Arduino has a different processor, the pin associated with external interrupt may be different.  You will have to look up the pinout of your processor and see which pin is associated with INT0.

Leave a Reply

Your email address will not be published. Required fields are marked *

Triangle Embedded Interest Group