0

I'm working on a little midi hardware project and I'm using attachInterrupt() to assign a callback function to an interrupt pin.

Nothing gets done in the loop function, so it looks like this:

void loop() { return; }

So far this seems to work out, but I'm wondering if this is a bad practice? I tried adding a short delay() call in there instead but I couldn't really measure if it performed better or worse.

3
  • no need for return ... there is nothing to return to
    – jsotola
    Apr 10, 2023 at 15:15
  • loop() returns to main() (from where it was called, inside an infinite loop) after every iteration, whether or not you write a return; statement. The only case of such a function not returning one that contains an infinite loop to prevent it.
    – JRobert
    Apr 10, 2023 at 21:25
  • If you are using just one ISR to check a pin, this boils down to the question, which alternative has more overhead: a loop polling the pin, or the interrupt service entry and exit. You need to measure or look into the assembly code. Apr 11, 2023 at 7:48

2 Answers 2

1

There is no particular reason to worry about doing nothing in loop - the processor has to be doing something - you don't need to give it extra work.

Plus, there is an implied return at the end of functions, you don't need to add your own.

The bigger issue is that interrupt handlers should be short, so that you don't miss another interrupt while you are doing something lengthy in the first interrupt.

0

I think I can answer my own question.

I realized that I can keep my state change and debouncing logic in the interrupt routine and move everything else to the loop function, which seems cleaner.

edit: well not necessarily cleaner. I agree with @jsotola, ISR should only do the bare minimum.

In the end I figured not even using an ISR in the first place was even better for my use case.

2
  • 1
    putting too much code into an ISR is just asking for trouble ... especially the debounce code, it hangs the program for too long if it is inside a non-looping code block ... put the debounce code inside loop() so that the interval between keybounces can be measured without pausing the program
    – jsotola
    Apr 10, 2023 at 15:18
  • Debounce code in an ISR can be OK if works by rejecting events (say button presses) which occur within say 50ms of the last accepted event because this can be coded without blocking. But, yes, in principle, an ISR should be very lightweight and quick to execute.
    – 6v6gt
    Apr 12, 2023 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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