Return to end (or top) of void loop() from inside function

I want to return to top of the void loop() function if something happens in a function(or fails to happen).

If connection fails I want to sleep, and when awakening start void loop() from the top again. “return “ will take me out of the current function but only take me to the place where I called the function. I could add code to skip through my 900 lines of code to the end of loop, but is there a simpler way to just restart the loop() or go to the end of loop() so that it would restart? I’ve seen several examples using return out of the function but they do not have hundreds of lines of code after the function that need to be avoided before restarting loop().

I could use goto a label at the top or end of loop(), but then I’d probably get a lot of grief :slight_smile: Is there a better approach? (update, anyway I find that I can’t goto a label outside the function)

I used to use System.reset(RESET_NO_WAIT); to totally restart the program, but now I don’t want to lose incrementing global variables and the system time set in void setup().

On the other hand maybe I’m thinking about this all wrong :frowning:

john

Usually the best technique is to restructure your code as a finite state machine. It's bad practice to block the loop from returning for any period of time. When using a finite state machine, instead of blocking the loop and nesting multiple functions inside each other that are called from loop, you only are ever one level deep so returning will exit the loop and start over again easily.

There's no good way to exit multiple nested functions. You need to return an error code from each of them, which cause them to eventually exit loop and run it again from the beginning.

If you block loop it will affect the operation of Particle function and Particle variable because they are dispatched between calls to loop. This is one of the reasons you should return from loop as often as possible.

shoot, you, @rickkas7, are going to make me clean up my code :wink:
Well I guess it’s about time, after 6 years of junking my code together that mostly worked but was really hard to debug. It became evident how hard it was to debug when I made the move from Electron to Boron. At your prompting, I have convert my solar powered, cold weather, very remote water sensor code to a finite state machine. Now might be a good time to thank all those that I stole solar power ideas and code from over the years, like you @rickkas7 and @RWB , @Rftop and particularly @chipmc for his kind inspiration making solar based monitoring work.

My Boron code now seems to be working as a finite state machine using switch(state) as demonstrated here: finite state machine . I'll post the code on github after some final cleanup and post a link to it here.

4 Likes