INTERRUPT-ARDUINO

Photo of author

By Jackson Taylor

Home » Electronics Topics » Arduino » INTERRUPT-ARDUINO

As an Amazon Associate we earn from qualifying purchases.

An interrupt lets an Arduino react to an event right away, without checking for it again and again inside loop(). When the event happens, the processor pauses what it is doing, runs a short function, and then carries on where it left off. This guide explains how that works and walks through two examples: counting pulses with an external interrupt and reacting to serial data.

What is an interrupt in Arduino?

Normally your sketch runs top to bottom, then repeats. If you want to detect a button press or a pulse from a sensor, you can poll the pin in loop(). That works until the sketch spends time in delay() or other slow code, and a short pulse slips by unnoticed.

An interrupt solves this. You register a function called an interrupt service routine (ISR). When the chosen event occurs, the Arduino stops the main code, runs the ISR, and then resumes.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

Which pins support external interrupts?

It depends on the board. On Uno-class boards (Uno, Nano) the external interrupts are on pin 2 and pin 3. Other boards, such as the Mega, offer more. Check the documentation for your board before wiring anything.

The older style of attachInterrupt(0, ...) uses an interrupt number, where 0 is pin 2 on an Uno. A clearer approach is digitalPinToInterrupt(pin), which converts a pin number into the right interrupt number for your board.

Interrupt trigger modes

The third argument of attachInterrupt() sets when the ISR fires:

  • RISING: the pin goes from LOW to HIGH.
  • FALLING: the pin goes from HIGH to LOW.
  • CHANGE: the pin changes in either direction.
  • LOW: the pin is LOW (the ISR keeps firing while it stays LOW).

Pulse counting using an external interrupt

This sketch counts falling edges on interrupt 0 (pin 2 on an Uno) and prints how many arrived each second. It is a typical way to measure the speed of a wheel, a flow sensor or any pulse output.

int c=0;
void setup()
{
  attachInterrupt(0, blink, FALLING);
  Serial.begin(9600);
}
void loop()
{
delay(1000);
Serial.println(c);
c=0;
}
void blink()
{
  c=c+1;
}

How it works

  1. attachInterrupt(0, blink, FALLING) tells the Arduino to call blink() each time the pin falls from HIGH to LOW.
  2. While loop() waits in delay(1000), interrupts still fire, so pulses are counted during the wait.
  3. After one second the sketch prints the count and resets it to zero.
See also
To turn on the white led......!!!

A safer version of the same sketch

The sketch above works for a simple demo, but two details are worth fixing. A variable shared between an ISR and the main code should be declared volatile, so the compiler does not cache an old value. Also, on a board with an 8-bit processor, reading a 2-byte int can be interrupted halfway, so briefly disable interrupts while you copy and reset it.

volatile int c = 0;

void setup()
{
  pinMode(2, INPUT_PULLUP);  // only if your signal source needs a pull-up
  attachInterrupt(digitalPinToInterrupt(2), blink, FALLING);
  Serial.begin(9600);
}

void loop()
{
  delay(1000);
  noInterrupts();
  int count = c;
  c = 0;
  interrupts();
  Serial.println(count);
}

void blink()
{
  c = c + 1;
}

Mechanical switches “bounce” and can produce several pulses for one press, so a raw button on this pin will over-count. For that case, see our Arduino button interrupt guide.

UART interrupt: reacting to serial data

The second example stops an LED from blinking as soon as something arrives over the serial port. It uses serialEvent(), a function the Arduino core calls when serial data is waiting.

//led blinking will off when interrupt occur
int a=0;
void setup() {
  Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop()
{
  if(a==0)
  {
 digitalWrite(13,HIGH);
 delay(500);
 digitalWrite(13,LOW);
 delay(500);
  }
  else
  digitalWrite(13,LOW);
}
void serialEvent()
{
 // while (Serial.available()) {
 // Serial.write(Serial.read() );
 a=1;
   //}
 }

What to know about serialEvent()

  • The LED blinks on pin 13 while a is 0. When serial data arrives, serialEvent() sets a to 1 and the LED stays off.
  • The commented-out lines show how you would read and echo the incoming bytes instead.
  • serialEvent() is not a true hardware interrupt. The core checks for data between runs of loop(), so the reaction waits until the current pass, including both delay(500) calls, finishes.
  • It is not available on every board, so confirm support for yours.

If you need an immediate response, use a pin-based interrupt instead, or avoid long delays and check Serial.available() often.

Rules for writing a good ISR

  • Keep it short. Set a flag or update a counter, then handle the work in loop().
  • Do not use delay() inside an ISR. It relies on timer interrupts that are blocked while the ISR runs.
  • Avoid Serial.print() in an ISR. It can stall or misbehave. Print from loop().
  • Remember that millis() does not advance while the ISR runs.
  • Use volatile for any variable shared with the main code.
  • Take no arguments and return nothing. An ISR is declared as void name().

Where interrupts are useful

Interrupts suit anything where timing matters or events are brief: rotary encoders, flow meters, tachometers and wake-up signals. Even sensors with pulse outputs, such as the echo pin of an HC-SR04 ultrasonic sensor, can be timed this way, though the common library approach for that sensor does not need it.

See also
HIGH VOLTAGE BUCK CONVERTER USING ARDUINO (275V DC TO 165V DC)

Interrupts on other platforms

The idea is the same on other microcontrollers, but the setup differs. If you are curious how interrupts on ARM microcontrollers are handled, or how to set up an external interrupt on an MSP430, those posts cover it.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

FAQ

How many interrupt pins does an Arduino Uno have?

The Uno has two external interrupt pins: pin 2 and pin 3. Other pins can use pin change interrupts, which need extra code or a library.

Why should I declare the variable as volatile?

It tells the compiler the value can change at any moment outside the normal program flow. Without it, the main code may keep using an old copy of the variable.

Can I use delay() inside an interrupt?

No. delay() depends on timer interrupts, which are paused while an ISR runs, so it will not work as expected. Keep the ISR to a few quick lines.

Is serialEvent() the same as a hardware interrupt?

No. It is called by the Arduino core between passes of loop(), so it is delayed by whatever your loop is doing. A pin interrupt reacts almost immediately.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works