Saturday, October 13, 2012

Arduino ISR (Interrupt) Code Tutorial

I know a lot people look for something like this, so here is an example of how to debounce a button in an interrupt routine. this allows you to simply use the value in the main loop and not have to worry about the debouncing in the loop wasting time.


//----------------------------------------------------------------------------------------------

volatile long lastDebounceTime = 0;   // the last time the interrupt was triggered
#define debounceDelay 50    // the debounce time in ms; decrease if quick button presses are ignored, increase
                             //if you get noise (multipule button clicks detected by the code when you only pressed it once)

#define BtnPin 0 //digital pin 2, interrupt 0

void setup()
{
  // put your setup code here, to run once:
  attachInterrupt(BtnPin,FireEvent, RISING);
  //this works on a switch that is pulled down to ground and sends V+ to the arduino pin when "closed" (pushed down)
  //See here for the scheme: http://arduino.cc/en/uploads/Tutorial/button_schem.png the resistor is 10k.
}

void loop()
{
  // put your main code here, to run repeatedly:
 
}

void FireEvent() //triggers when the switch is pressed. each time you press the switch,
{                //there are hundreds of little tiny conenctions as you press it down, so the delay filters those out.

  if ((millis() - lastDebounceTime) > debounceDelay) //if current time minus the last trigger time is greater than
  {                                                  //the delay (debounce) time, button is completley closed.
    lastDebounceTime = millis();
   
   //switch was pressed, do stuff like turn off your motor/led etc
  }
}
//------------------------------------------------------------------------------------------------------------






1 comment:

  1. I am using this exact code in combination with a hardware debouncer as described at http://www.ganssle.com/debouncing-pt2.htm When keeping the switch pressed. The interrupt which is RISING is keep getting called. Any ideas on this? Have no idea why it triggers the RISING edge when keeping the button pressed.

    ReplyDelete