Reference   Language (extended) | Libraries | Comparison

attachInterrupt(interrupt, function, mode)

Description

attchInterrupt enables interrupts 0 or 1, on digital pins 2 or 3 respectively. It also specifies the function to call when an external interrupt occurs.

Note: millis() and delay() won't work in your interrupt-handling function. Any serial data received while in your interrupt-handling function will be lost.

You also should declare as volatile any variables that you modify within your interrupt handling function (see the example).''

Parameters

interrupt:: the number of the interrupt (int), with a valid value of 0 or 1.

function:: the function to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine.

mode: defines when the interrupt should be triggered. Four contstants are predefined as valid values:

  • LOW to trigger the interrupt whenever the pin is low,
  • CHANGE to trigger the interrupt whenever the pin changes value
  • RISING to trigger when the pin goes from low to high,
  • FALLING for when the pin goes from high to low.

Returns

none

Using Interrupts

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. A good task for using an interrupt might be reading a rotary encoder, monitoring user input.

If you wanted to insure that a program always caught the pulses from a rotary encoder, never missing a pulse, it would make it very tricky to write a program to do anything else, because the program would need to constantly poll the sensor lines for the encoder, in order to catch pulses when they occurred. Other sensors have a similar interface dynamic too, such as trying to read a sound sensor that is trying to catch a click, or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In all of these situations, using an interrupt can free the microcontroller to get some other work done while not missing the doorbell.

Interrupts can be used with internal hardware too, such as timers, but as of Arduino 008, this requires AVR code and is not supported in the Arduino core.

Example

int pin = 13;
volatile int state = LOW;

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
}

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

void blink()
{
  state = !state;
}

See also

Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.