Go Down

Topic: Setting Up an Interrupt using switches (Read 328 times) previous topic - next topic

PaulS

Quote
Once a bumper is triggered, I want it to do a set of certain actions, then continue on the main code once the interrupt has been completed. Is there a better way of doing this?

Yes. Polling the bumpers is a much easier choice. An interrupt is like a doorbell ringing, with a politician on the doorstep. You can't wait to get rid of the doorbell ringer. You do not perform a bunch of actions in the ISR, like inviting the politician in, making coffee, etc. You set a flag, noting that the interrupt happened.

Then, later (in loop()), you see that the interrupt happened (because the flag is set), and you deal with that fact then.

Of course, this means that you can not have delay() anywhere in your code (and shouldn't anyway). A state machine is what you are trying to develop.

joshuabardwell


Then, later (in loop()), you see that the interrupt happened (because the flag is set), and you deal with that fact then.


Here's a code snippet that does this:

Code: [Select]

volatile boolean triggered = false;

void setup()
{
  attachInterrupt(0, interruptHandler, CHANGE);
}

void loop()
{
  if (triggered)
  {
    // respond to interrupt occurring here
   
    triggered = false; // reset the interrupt
  }
}

void interruptHandler()
{
  triggered = true;
}


You may want to add some additional logic in whether you trigger in response to the interrupt, and under what circumstances you decide to reset the "triggered" flag, but this is the gist of it. Put as little logic as possible in your ISR and leave most of the logic in the main loop. That way the ISR returns as fast as possible.

Keeping logic outside of your ISR is also useful because debugging an ISR is harder, because you can't use Serial.print() from within an ISR. So if you intend to debug an ISR, you can only do it by lighting an LED or maybe writing to an LCD screen, if your project has one.

Go Up