Arduino interrupts

Hardware interrupts
On Arduino Uno there are only 2 pins that can handle interrupts (2 and 3) by default.
Interrupts has to be quick in execution. Methods like delay(), Serial, millis() can not be used with interrupts.

Interrupts project on tinkercad

Variables used inside the interrupt need to be global and volatile.

In order to add interrupt use attachInterrupt(digitalPinToInterrupt(pin), ISRmethod, mode)

There are few modes to trigger the interrupt:
RISING: when the pin transits from LOW to HIGH.
FALLING: when the pin transits from HIGH to LOW.
CHANGE: when the pin transits from LOW to HIGH or HIGH to LOW

const byte buttonPin = 2;
volatile bool state = false;

void setup() {
   pinMode(13, OUTPUT);
   pinMode(2, INPUT_PULLUP);
   attachInterrupt(digitalPinToInterrupt(buttonPin), checkSwitch, FALLING);
} 

void loop() { } 

void checkSwitch() { 
   if(digitalRead(buttonPin)==false)
   {
      state = !state;
      digitalWrite(13, state);
   }
}

Włączanie diod Led w kolejności z użyciem przerwań

volatile int counter = 0;

void setup()
{
  DDRD = B00111000;
  attachInterrupt(digitalPinToInterrupt(2), turnOutput, RISING);
}

void turnOutput()
{
  PORTD = B00000000;
  if(counter == 3){
    counter = 0;
    return;
  }
  counter++;
  digitalWrite(counter+2, HIGH);
}

void loop(){}

Scroll to Top