Simple Interrupt

On my Arduino Mega, I'm trying to create a very simple Interrupt. Basically every time a button is pressed I want the interrupt to be triggered, and increment a counter. My code is quite simple..

volatile unsigned long counter;

void buttonPulse() {

counter++; }

// constants won't change. They're used here to // set pin numbers: const int buttonPin = 20; // the number of the pushbutton pin const int IRQ = 3; // According to the web page on a Mega, Pin 20 is IRQ 3

void setup() { Serial.begin(9600); counter = 0; attachInterrupt(IRQ,buttonPulse,RISING);

Serial.println("Enter to continue"); while (!Serial.available()); Serial.flush(); }

void loop(){ delay(200); Serial.print("Counter=");Serial.println(counter); }

I have the button wired with 5v on one leg, and the other leg connected to Pin 20 (which should be IRQ 3 on a Mega.

My interrupt never triggers when i press the button. :(


What says the pin isn’t already high?

You should "configure" the pin a little bit... It will also help to connect the button to ground.. Read a little bit about pull-up and pull-down...

yes.. i;m realizing that something is not right with my circuit. I'm no EE, but can code well, when I run a simple button press sketch, with nothing connected, the pin reads high (though occasionally it reads low) Pressing the button does not change a thing in this simple test. Again with my simple button press sketch, if I write HIGH to the input (which I believe is supposed to enable the internal pullup resistor), i still get nothing changing when I press the button. Do I need a pull down resistor to force the line low, so that when I press the button, it goes high?

On my simple sketch I make the pin an output pin, wrote LOW to it, then changed the pin mode to Input, and now the button seems to work correctly;

When you say "configure the pin a little bit" what do you mean. I've tried writing HIGH to it after configuring it to be an input pin, which as far as I can tell should enable the internal pullup resistor. I changed the interrupt to trigger on CHANGE, which should mean that the button becomes low, and changes the state.

I changed my circuit to not use the +5v output on the board, powering the switch with 4 AA bateries, and now with CHANGE as the trigger, things seem to work better.

(1) You have to use a pull-up or pull-down. Please understand this. (2) If you do not want to use an external resistor, there is only the pull-up solution. (3) Hence the button must be connected to ground, what is called "active low" by us nit-wits. (4) So to catch this with an interrupt, you have to look for a falling edge..

Yes, I think this might work..

And then the mighty deboucing kicks in, or the mechanical vibration of the switch will trigger alot of interrupts every time that you press the button.

Why not? We don't know what the program is assumed to do. Maybe it's a "bounce-counter"?