Loop exit

How can I exit a Loop the moment a switch pin is high so that the routine proceeds no further, stops in its tracks without continuing to execute the rest of the loop? I am able to stop the loop only after the loop completes one cycle which is too late.

I am able to stop the loop only after the loop completes one cycle which is too late

Are you talking about this loop?

void loop()

How did you stop the loop?

The break command will exit a loop (including loop()). So if you want an interrupt to cause a loop to exit, then in your ISR, set a variable and check for that variable in your loop. If it’s detected, then run the break command. It won’t be real time, but it should be very fast.

byte interruptPin = 0;  // your interrupt pin
volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
byte C = 0;  // this is just the counter var for the while loop

void setup() {
  attachInterrupt(interruptPin, myISR, RISING);  // The interrupt will trigger on a rising state and run myISR()
}

void myISR() {
  ISRRan = 1;
  // do other things in the ISR
}

void loop() {
  while ( C < 10 ) {
    if ( ISRRan ) {
      break;
    }
    //doing something inside the while loop
  C++;
  }
  // do other things outside of the while loop
  ISRRan = 0;  // Reset for whatever reason
}

I am able to stop the loop only after the loop completes one cycle which is too late.

Sorry, just saw this part after reading the post again. I think this is as good as you can get because I don’t think the ISR can directly communicate with the non-ISR code. You may be able to cause a software reset from the ISR, but that’s pretty harsh.

First, learn about interrupts. If you still don't want to use them then read on

This is a matter of polling. What I am about to suggest is not the most efficient implementation, but rather one that is easy to implement.

Here's what you probably have:

while (input != HIGH) //you might also be checking for some other conditions
{

 //do stuff here

}

As you've mentioned earlier, the loop will only stop after a complete cycle, because the conditions are only polled at the start of the cycle.

So why not poll more frequently?

while (input != HIGH) //you might also be checking for some other conditions
{

 //do something here

      if(input == HIGH)
            //suspend the program
            
 //do some more stuff

       if(input == HIGH)
            //suspend the program
            
 //do some other stuff

}

You can see now that within the loop, the conditions are polled twice.

I am not suggesting that check something after every single line of code within the loop, rather identify segments of code that can be run together and poll after those.