Can't get interrupt working

I have some existing code that works and now I want to be able to make something happen when I press a button. I’ve attached a 12k pullup resistor between 3V3 and D0, then a momentary normally open pushbutton between D0 and GND.

I get no response when I click the button (it should be blinking my onboard led).

Relevant portions of my code are below. Thanks!

int button = D0;
void calibrate(void);  // saw this in the documentation, not sure it's required

void setup()
{
    attachInterrupt(button, calibrate, CHANGE);
...
}
void calibrate() {
    blinkLed(4);  // calls a function that blinks on-board LED
}

So when you push the button, you may get DOZENS of interrupts or more, unless you are debouncing it.

I’m betting there is something in here we won’t like either!

maybe post some of the irrelevant bits of your program, it may be easier to to help you.

1 Like

I think you should try to debounce your button, since that might mess things up. Then, you should try getting the function call out of your interrupt. Interrupts should be kept as short as possible. Rather set a flag which gets checked in the main loop.


@BulldogLowell beat me to it, but I’m posting this anyway, since I worked SO hard on it :cry:

1 Like

thanks, forgot about debouncing!

as for getting the function call out of the interrupt: my loop has a multi-minute delay() call in it (this is a system that check a sensor every so often). What is the design pattern for best handling an interrupt for such code? such a thing is hard to google for.

something like this:

int button = D0;
volatile bool buttonPressed = false;

void calibrate(void);  // saw this in the documentation, not sure it's required

void setup()
{
    attachInterrupt(button, calibrate, CHANGE);
...
}

void loop(void)
{
  if (buttonPressed)
  {
    blinkLed(4);
    buttonPressed = false;
  }
}

void calibrate(void) 
{
    static unsigned long lastPressTime = 0;
    if(millis() - lastPressedTime > 50) // debounce time
    {
      buttonPressed = true;
      lastPressedTime = millis();
    }
}
1 Like

Well, get that out of there, delays are kinda aweful ;(
Rather, use a millis() implementation, since that wont block anything, or better yet, use software timers!

This is awesome, thanks.

The last (I think!) question: currently because I have a delay() in my loop that lasts for a few minutes, how would I arrange the code so that the interrupt gets detected more or less immediately?

Oh sorry I hadn’t seen your remarks below your code re timers. Will investigate those!

1 Like

the interrupt gets detected immediately (that’s sorta the point)

get rid of the blocking code in your loop() function!

you may not even need a fancy-schmancy software timer!

1 Like