Arduino Tutorial

By LiterallyTheOne

6: Interrupt

bg right:33% w:400


Introduction

  • Previous tutorial: Analog
  • This tutorial: Interrupt

bg right:33% w:400


External Interrupt

  • Special Signal
  • Pause the current action
  • Run a code in a function
  • Interrupt Service Routine Function (ISR Function)

External Interrupt in Arduino Uno

  • 2 External Interrupts
  • pin 2, 3

Setup LEDs

setup leds height:450


Write a Routine

#include <Arduino.h>

int led_pins[8] = {6, 7, 8, 9, 10, 11, 12, 13};

int current_led = 0;

void setup()
{
  for (int i = 0; i < 8; i++)
  {
    pinMode(led_pins[i], OUTPUT);
  }
}

void loop()
{
  digitalWrite(led_pins[current_led], HIGH);
  delay(200);
  digitalWrite(led_pins[current_led], LOW);

  current_led++;
  current_led %= 8;
}

Output of LED setup

LED stup gif height:450


Connect an Interrupt

  • Button is Normally Closed
  • Default: 5V
  • Change: 0V

LED pause bg right:50% height:410


Define Interrupt in Arduino

  • attachInterrupt
    • pin
    • ISR function
    • mode

Define Interrupt pin

  • digitalPinToInterrupt
attachInterrupt(digitalPinToInterrupt(2), ... ,...);

Define ISR function

void isr_pause()
{
}
attachInterrupt(digitalPinToInterrupt(2), isr_pause ,...);

Modes

ModeDescriptionfigure
LOWtrigger the interrupt whenever the pin is low.interrupt-stage-low
CHANGEtrigger the interrupt whenever the pin changes value.interrupt-stage-change
RISINGtrigger when the pin goes from low to high.interrupt-stage-rise
FALLINGtrigger when the pin goes from high to low.interrupt-stage-fall

Add mode

attachInterrupt(digitalPinToInterrupt(2), isr_pause, RISING);

Fill the isr function

#include <Arduino.h>

int led_pins[8] = {6, 7, 8, 9, 10, 11, 12, 13};

int current_led = 0;
int x = 1;

void isr_pause()
{
  x = 1 - x;
}

void setup()
{
  for (int i = 0; i < 8; i++)
  {
    pinMode(led_pins[i], OUTPUT);
  }

  attachInterrupt(digitalPinToInterrupt(2), isr_pause, RISING);
}

void loop()
{
  digitalWrite(led_pins[current_led], HIGH);
  delay(200);
  digitalWrite(led_pins[current_led], LOW);

  current_led += x;
  current_led %= 8;
}

Output of pause interrupt

pause interrupt h:450


Volatile in Cpp

  • Stops Compiler optimazation for a variable
volatile int v;

Reset with Interrupt

Interrupt reset height:450


Increment pattern

Incerement pattern height:450


LEDS dance

LEDs dance height:450


w:400

© 2025 LiterallyTheOne