Saturday, November 12, 2011

Arduino Interrupt based LED with Toggle Button

I have been quit for sometime in my blog due to some work I had at work place. Got the time to work on Arduino Interrupts today and managed to put a small sketch on Arduino based Interrupts. Interrupts are a really powerful concept in hardware as well as in software. Specially in hardware, Interrupt eliminates polling saving precious processing cycles.

An interrupt is a Sporadic event which occurs asynchronously. For instance while reading a socket for data we can either Read that socket Periodically to see whether there is any data to be read or we can attach an ISR (Interrupt Service Routine) for that socket. Whenever there is data available in the socket buffer the ISR will be called asynchronously and the main program will be stopped executing. When the ISR is finished executing the main program will execute from where it stopped. This is called Context Switching.

Arduino UNO has two pins for External Interrupt handing INT0 (attached to pin 2) and INT1 (attached to pin 3). What I have tried to accomplish is without periodically reading pin 2 for a High value using Processing Cycles. Whenever there is FALLING (High to Low) in pin 2 a predefined ISR to be called which basically checks the state and does the opposite.

The circuit sketch looks as the following 



The Arduino Sketch for the program is as below. I have used INT0 with pin 2 for interrupt signal. As you can see the loop method doesn't do any polling on the value of pin 2. And I have used pin 10 for LED Output.

int pin = 10;
volatile int state = LOW;

void setup()
{
  pinMode(pin, OUTPUT);
  digitalWrite(2, HIGH);
  attachInterrupt(0, toggle, FALLING); // Attaching the ISR to INT0
}

void loop()
{
  // Does Nothing
}

// Interrupt Service Routine
void toggle()
{
  if(state == LOW) {
    state = HIGH;
  } else {
    state = LOW; 
  }
  digitalWrite(pin, state);
}

No comments: