Interrupt/button & bounce

I’m trying interrupts and i’ve written this code:

int bt = D2;
void press(void);
int buttonState=1;

void setup() {
    Serial.begin(9600);
    while(!Serial.available()) SPARK_WLAN_Loop();
    Serial.println("Interrupt Test");
    pinMode(bt, INPUT_PULLDOWN);
    attachInterrupt(D2, press, FALLING);
}

void loop() {

}

void press()
{
    Serial.println("Key Pressed");
}

I’ve bounce problems and after some keypress the core crash (red led)

Some help?
Thanks


I’ve edited your post to properly format the code. Please check out this post, so you know how to do this yourself in the future. Thanks in advance! ~Jordy

@blondie63, any reason for interrupts? You can also use ClickButton (in the web IDE libraries) which does not use interrupts. Instead, you call it in loop() to update the status of the buttons. Cool thing about that library is you can detect short and long presses. You can actually get 6 functions out of a single button (short or long single, double or triple clicks).

2 Likes

you want the interrupt function to be VERY SHORT (keep the Serial.print( )s out) and debounce the interrupt.

int bt = D2;
void press(void);
int buttonState=1;
volatile bool flag = false;

void setup() 
{
    Serial.begin(9600);
    while(!Serial.available()) SPARK_WLAN_Loop();
    Serial.println("Interrupt Test");
    pinMode(bt, INPUT_PULLDOWN);
    attachInterrupt(D2, press, FALLING);
}

void loop() 
{
  if (flag == true)
  {
      Serial.println("Key Pressed");
      flag = false;
  }
}

void press()
{
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();
  if (interrupt_time - last_interrupt_time > 50)  // debounce time = 50milliseconds
  {
    flag = true;
  }
  last_interrupt_time = interrupt_time;
}
1 Like

I could be wrong but I feel like you probably want to put that last_interrupt_time definition somewhere else. Also, idk if it should be static but i’m in a rush and haven’t really thought about it

last_interrupt_time is local variable, but has to survive the change of scope…

I’ll accept:

static volatile unsigned long last_interrupt_time = 0;

as an improvement, but I am not really that knowledgable about Spark’s stack…

Not sure how your button is connected, but INPUT_PULLDOWN and FALLING might be wrong. If you connect a button between a pin and ground, use INPUT_PULLUP to raise the voltage when the circuit is open, then closing the circuit will pull it to ground giving you a FALLING edge interrupt.