Exit a loop mid-loop with a button without a 'break'

How do you end a while loop based on the action of a button.
I have a light blinking "SOS" in morse code indefinitely, and would like to turn it off by pressing a button.

This is what I have:

while((digitalRead(off_button) != LOW) //while the button is not pressed
{
//code to make it blink "SOS" one repetition
}

How can I make the "SOS" stop in the middle of the repetition without inserting code to break the loop every other line? As of now it only works if I am holding the button down at the end of a repetition when a new loop iteration is about to begin.

Any thoughts welcome! Thanks

Blink your SOS without using delay, then the button can be checked much more often.

The "blink without delay" solution already mentioned is clearly the best.
If, however, you must keep the delays, you can trigger an interrupt with the button. In the interrupt service routine, you set a state flag which you test in your loop control statement. You can do this because the delay() function does not disable interrupts.

But then the loop isn't exit right away. It will then finish the delay() and the rest of the code until the check of the flag.

So best, don't use a delay(). And skip the while, the loop() is already an infinit loop :wink: Use that :slight_smile: