Cancel the delay

I want to cancel the delay with a press of a button. How can I achive that? Here is my code

#include <Esplora.h>
void setup() { }
void loop() {
Serial.begin(9600);
int mic = Esplora.readMicrophone();
if (mic > 500){
int flash_delay = 10;
delay(flash_delay);
delay(flash_delay);
for (int i = 300; i < 1000; i+=10) {
Esplora.tone(i);
Esplora.writeRGB(0, 0, 255);
delay(5);
}
Esplora.noTone();
Esplora.writeRGB(0, 0, 0);
}

if (Esplora.readButton(1) == PRESSED) {
int flash_delay = 10;
delay(flash_delay);
delay(flash_delay);
for (int i = 300; i < 1000; i+=10) {
Esplora.tone(i);
Esplora.writeRGB(0, 0, 255);
delay(5);
}
Esplora.noTone();
Esplora.writeRGB(0, 0, 0);
}

if (Esplora.readButton(2) == PRESSED) {
Esplora.noTone();
Esplora.writeRGB(0, 0, 0);
delay(100000000000);
}

if (Esplora.readButton(3) == PRESSED) {
// code to stop delay
}

else {
Esplora.noTone();
Esplora.writeRGB(255, 0, 0);
}

}

You can't cancel delay(), which is why we recommend to use millis() for timing, as discussed here: https://www.baldengineer.com/blink-without-delay-explained.html

Please use code tags when posting code.

delay(100000000000);[/quote]

3000 years? That's quite an ambitous delay.

And 100000000000 doesn't fit into 16 bit integer, neither does 100000000000L fit into a 32 bit long.

If you call delay you are absolutely categorically stuck in the delay till it completes, end of story.

Basically don't use delay. Except perhaps in a very simple sketch where there's nothing else to do.

Your code should be reacting to a series of events, and loop() just checks for them one after another and handles any that arise. A timeout is one kind of event. Incoming serial is another, a change to a pin's state is another, etc etc.

Perhaps you need to explicitly represent states? Google "state machine" for more detail.

Note if you really do want a delay that can cancel, write a function to do it:

void delay_till_condition (bool (*condition)(void))
{
  while (! condition())
  {}
}

You can pass in an arbitrary condition testing function to it, such as

bool button_pressed()
{
  return digitalRead (BUTTON) == LOW ;
}

void loop()
{
  delay_till_condition (button_pressed) ;
}

The functions delay() and delayMicroseconds() block the Arduino until they complete.
Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

...R

@Beazor

Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Please READ THIS POST to help you get the best out of the forum.

Bob.