Are you sure you need to exit at ANY time wherever the execution pointer is? Normally, you could just check the button press at the end of the while
and for
loops and call return
when it is pressed.
Sometimes we think our program has to do something and break out of execution, but upon careful examination, we conclude that it can finish one loop interation and then quit.
Could you tell us what's done inside the loops, so we can make sure what's needed?
Edit: As I suspected, the problem with your program is that your delay intervals are too long, e.g. delay(1000)
and delay(500)
, and you can't check for button presses while the program is waiting.
To fix that, create the following function, that will replace your calls to delay:
// waits for the specified miliseconds
// or return (almost) immediately if button is pressed
// return value indicates whether button was pressed or not
boolean waitOrButtonPressed(int miliseconds) {
for (int i = 0; i < miliseconds / 10; i++) {
if (readButtons(5)) == 5)
return true;
delay(10);
}
return false;
}
Then, inside your for
loop, replace your calls to delay(1000)
by the following code:
if (waitOrButtonPressed(1000)) return;
The function I created will make your program wait almost like delay()
, but will return true
if a button was pressed during that time. If that happens, the if
statement above will exit loop()
which will be called again by the Arduino generated code.
Remember to keep the miliseconds to wait when you replace your calls to delay()
to keep your program waiting behavior unchanged.
Edit 2: Ramblings
Cases like this remind me of the movie Tron, in which the main character is dragged into a computer, where time passes much slowlier than in real life. So, like in the movie, 1000 miliseconds (1s) is a LOT OF TIME for the MCU. You can do a whole lot more than waiting in that time. Try and break up the long Waits and do useful stuff with your MCU cycles.
Also, learn how to use interrupts, like others mentioned in their comments and answers. It's just another (a bit more complicated) way of doing stuff while you wait. In your case, interrupts could be use to detect the button press without the need to check it everytime everywhere. Here's a place to start learning about interrupts with Arduino.
Best Answer
You have un paired or extra curly brackets.
Fixed: