0

Background: I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.

My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end. e.g.

switchState = digitalRead(switch);
 if (switchState == HIGH){
 //do my routine which is a function defined outside of the loop
}

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

  • 1
    To not need the large delay at the end you could just store the previous state of the button and only run your code when the current state is HIGH, and the previous state was LOW. That was your code only runs once per button press. I think this is what you meant, right? – Gerben May 21 '17 at 17:38
2

No, an interrupt here would be pointless.

You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.

If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.

1

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

it depends critically on your definition of "go high", ie. if you are looking for a transition to high, or if you are looking for the switch to be high. edge triggererd vs. level triggered.

As is, your existing (level-triggered) logic can be easily implemented via an interrupt, as will an edge triggered logic.

interrupt-driven code is generally more efficient for slow / infrequent inputs: it doesn't waste the cpu's processing power. But it does add a level a complexity that can be difficult to handle for beginners.

As for me, I think it is (practically) impossible to code without the use of interrupts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.