Interrupts

Hi,
I am having troubles using hardware interrupt over Arduino Uno.
The interrupt is activated when pin2 is negated.
When I wire pin2 to the ground There something happens in the monitor but not the expected result (it writes some garbage to the screen).
Can you find problems with my code?

thanks

The code:

#include <avr/interrupt.h>
 
void setup() {
   Serial.begin(9600); 
   digitalWrite(2, HIGH);    // Enable pullup resistor
   sei();                           // Enable global interrupts
   EIMSK |= (1 << INT0);     // Enable external interrupt INT0
   EICRA |= (1 << ISC01);    // Trigger INT0 on falling edge

}
void loop(){
 Serial.println("program");
 delay(1000);
}

ISR(EXT_INT0_vect)
{
  Serial.println("interrupt");
}

Don't print from interrupt. Printing is an interrupt driven activity.

Instead, set a flag in the ISR. In your loop(), check for that flag to be true. When true, call serial.print and set the flag back to false.

Also when I do the following subroutine I get garbage to the monitor:

ISR(EXT_INT0_vect)
{
  delay(5000);
 }

why?

Delay won't work. It is also interrupt driven.

Where can I find reading material about this subject?

Do as little as possible in an isr. That means just increment or set a flag and then deal with the event in your loop. find out more info by googling it or look in the tutorials section of this website.

amitash: Where can I find reading material about this subject?

http://www.gammon.com.au/interrupts

New program.
Getting only “program2” to the monitor.
After connecting pin2 to gnd it jumps immediatly print “program2” again (without the delay)
What can be wrong ?

#include <avr/interrupt.h>
 int flag = 0;
void setup() {
   Serial.begin(9600); 
   digitalWrite(2, HIGH);    // Enable pullup resistor
   sei();                    // Enable global interrupts
   EIMSK |= (1 << INT0);     // Enable external interrupt INT0
   EICRA |= (1 << ISC01);    // Trigger INT0 on falling edge

}
void loop(){
  Serial.println(flag);
  if(flag)
  {
 Serial.println("program1");
 
  }
  else
  {
     Serial.println("program2");
  }
delay(1000);  
}

ISR(EXT_INT0_vect)
{
  flag = 1;
   
}

Please edit your posts, select the code, and put it between [code][/code] tags.

You can do that by hitting the # button above the posting area.

amitash: What can be wrong ?

Did you read the link about interrupts? Scroll down to the part about volatile variables.

Thanks.

Also, once flag becomes 1, it keeps that value until you reset the Arduino. Is that really what you want?

Since the flag variable only needs to hold 0 or 1, a 2 byte type seems overkill, doesn't it?