กลับหน้าหลัก
views
How to Use Arduino Interrupt with attachInterrupt()
Last updated on

How to Use Arduino Interrupt with attachInterrupt()


How to Use Arduino Interrupt with attachInterrupt()

What is an Interrupt

Normally, Arduino runs code inside void loop() continuously from top to bottom, then repeats. But what if something urgent happens that needs immediate attention, like a button press or motion detected by a sensor? This is where interrupt comes in handy.

Think of it like watching TV when someone rings the doorbell. You pause, answer the door, then go back to watching your show. That brief interruption is exactly what Arduino interrupt does.

Arduino interrupt flow diagram

Interrupt Pins by Board

Different Arduino boards have different numbers of external interrupts:

Boardint.0int.1int.2int.3int.4int.5
UNO, Ethernet23----
Mega25602321201918
Leonardo3201-7

This guide focuses on Arduino UNO R3 with its two available interrupt pins.

Arduino Interrupt Code Example

This example monitors pin 3 (interrupt 1) and toggles the LED on pin 13 whenever a rising signal is detected:

const int ledPin = 13;
volatile int ledState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  
  // attachInterrupt(interrupt, function, mode)
  // interrupt: 1 = pin 3 on UNO
  // function: name of ISR to execute
  // mode: RISING, FALLING, or CHANGE
  attachInterrupt(1, blink, RISING);
}

void loop() {
  digitalWrite(ledPin, ledState);
  // other tasks continue here
  Serial.println("Running...");
  delay(500);
}

void blink() {
  Serial.println("Interrupt triggered!");
  ledState = !ledState;
}

Important: Variables used inside an Interrupt Service Routine (ISR) must be declared volatile to prevent the compiler from optimizing them away.

Interrupt detection modes

Interrupt Trigger Modes

ModeDescription
RISINGTriggers when signal goes from LOW to HIGH
FALLINGTriggers when signal goes from HIGH to LOW
CHANGETriggers on any signal transition

Best Practices for Arduino Interrupts

  • Keep ISR functions short and fast - other code waits while ISR runs
  • Avoid using delay() and Serial.println() inside ISR functions
  • Use volatile for all variables shared between ISR and main code
  • For complex communication (like I2C) inside ISR, use flags to handle in loop()

Reference Video

อยากทำโปรเจคแบบนี้?

รับทำโปรเจค Arduino / IoT จบงานไว ส่งงานครบ พร้อมสอน

If you need Arduino project service or urgent IoT development, see full service details on the home page

จ้างทำโปรเจคเลย

ความคิดเห็น

Verified user reviews

รีวิวและความคิดเห็นจากผู้ใช้จริง

ล็อกอินด้วยบัญชีบนเว็บนี้แล้วให้คะแนนหรือคอมเมนต์ได้เลย ระบบเก็บผ่าน Supabase ไม่ต้องใช้ GitHub แล้ว

กำลังโหลดรีวิว...