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.
2 Answers 2
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.
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.
-
1putting 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 programjsotola– jsotola2023年04月10日 15:18:01 +00:00Commented 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– 6v6gt2023年04月12日 02:48:42 +00:00Commented Apr 12, 2023 at 2:48
Explore related questions
See similar questions with these tags.
return
... there is nothing to return toloop()
returns tomain()
(from where it was called, inside an infinite loop) after every iteration, whether or not you write areturn;
statement. The only case of such a function not returning one that contains an infinite loop to prevent it.