I've read that apparently you shouldn't use delays in an interrupt, but I've found for the simple light game I'm working on at the minute they seem to do the job. I have noticed that the length of the delays in an interrupt seems to be shorter then that of one outside an interrupt though, and I have no idea why this might be. Does anyone know why this might be happening, and if there's a better option then using delays?
Also, I've currently got a while loop with a for loop inside of it. Is there any way I can get the function to break out of the while loop with an interrupt, without it trying to finish the for loop first?
I've done lots of realtime programming, and the use of the Arduino delay() together with timer interrupts seems to sometimes work, and often not. Many times the programming problems don't appear to be related to the timing components, but then when I rearrange things to get rid of the Delay() function, things straighten out.
So I think the long and short of it is, many times, it will work. Sometimes, things go funny on you. Best to just develop the habit of avoiding it. If you need a delay, build your own clock out of one of the timers. That way you have complete control of it.
A very simple way to create a (non super-accurate !) delay in a sketch (that uses interrupts) is "keep the processor busy" for a while...
e.g. a line like this :
for(float f=0;f<83000;f++){}
83000 gives a delay of about one second ...
Of course if an interrupt occurs while processing this line, the "delay" will take longer, but in some cases this might be even an advantage ...
There should NEVER be a delay() or a wait of any kind inside an Interrupt Service Routine (ISR). ISRs should be designed to complete as quickly as possible. 100 microseconds would be very long for an ISR.
The demo Several Things at a Time illustrates how to use millis() to manage timing without blocking.
If you need to exit both the for() loop and the containing while() loop then you need to set a variable in the for() loop which will cause the while() loop to exit.
while(searching_for_something) {
boolean for_loop_found_the_thing = false;
for(some_loop_condition) {
if(some_truth_condition) {
for_loop_found_the_thing = true;
break; //leave the for() loop here
}
}
if(for_loop_found_the_thing) break; //leave the while() loop here
Do more processing here.
}
If you don't need to have any processing between the for() loop and the end of the while, then just set searching_for_something to be false or use: