Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Lesson-09 Interrupts

Introduction

Imagine you are a student in a classroom trying to study while the teacher is explaining something important. Suddenly, the fire alarm goes off, causing a loud noise that interrupts your study session.

Similarly, in a microcontroller, interrupts can be thought of as signals that “interrupt” the normal flow of the program when a certain event occurs. Just like the fire alarm interrupts your studying, interrupts can be triggered by external events such as a button press or a sensor reading.

Instead of constantly checking for these events in the main program loop, interrupts allow the microcontroller to temporarily pause what it’s doing and immediately respond to the event, just like how you immediately stop studying and evacuate the classroom when the fire alarm goes off.

This allows microcontrollers to be more efficient and responsive to external events, making them ideal for tasks that require real-time responsiveness or handling multiple tasks at once.

Types of Interrupts

There are two types of interrupts −

  • Hardware Interrupts − They occur in response to an external event, such as an external interrupt pin going high or low.
  • Software Interrupts − They occur in response to an instruction sent in software. The only type of interrupt that the “Arduino language” supports is the attachInterrupt() function.

In this section we will only cover Hardware interrupt.

Hardware Interrupt

Hardware interrupts in Arduino Uno are triggered by external events such as a button press, sensor reading, or other hardware events. These interrupts can be used to pause the normal flow of the program and execute a specific function in response to the external event.

Here’s an example code for setting up and using a hardware interrupt on Arduino Uno:

// Define the pin for the hardware interrupt
const int interruptPin = 2;

// Define a variable to hold the state of the interrupt
volatile int interruptState = LOW;

// Define the interrupt service routine (ISR) function
void handleInterrupt() {
  interruptState = HIGH;
}

void setup() {
  // Set the interrupt pin as an input
  pinMode(interruptPin, INPUT);

  // Attach the interrupt to the interrupt pin and specify the ISR function
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);

  // Initialize the serial communication
  Serial.begin(9600);
}

void loop() {
  // Check the state of the interrupt and print a message
  if (interruptState == HIGH) {
    Serial.println("Interrupt triggered!");
    interruptState = LOW; // Reset the interrupt state
  }

  // Other code here
}

    Leave a Reply

    Your email address will not be published.

    Need Help?