0

I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the void loop() function with an exit(0) to terminate the program analogous to break keyword in C language. Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the void loop() function.

4
  • If you return from the loop() function, you immediately end the execution of the current iteration. The loop() function will then start again, as its always looping (therefor the naming). loop() is just a function like any other. It just gets called over and over in an infinite loop. – chrisl Apr 9 at 23:26
  • Using "return;" as if it were a normal function seemed to work. I thought at first that return would do the same thing as exit(0). Thank you so much @chrisl. – shyam Apr 9 at 23:31
  • I think anexit(0) will just lead into an infinite loop,which is doing nothing. On a microcontroller there must run a code at anytime. It cannot give the control back to an OS. – chrisl Apr 9 at 23:41
  • yes, I have heard using exit(0) is a bad Arduino programming practice. – shyam Apr 11 at 10:08
0

In the loop() function, return will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling loop() again.

Another way to accomplish the same thing is to write everything in your setup() function, including whatever kind of loop construct you want, and use break; and continue; statements as you're used to:

void setup(){
   // pinMode() & digitalWrite() calls
   // Initialize the Serial port if you need to
   // Any other one-time setup
   //
   // Everything happens here:
   for( .... ){
      // loop contents here
      if( whatever ){
         continue;
      }
      else if( something_else ){
         break;
      }
   }
}

// This just stalls forever when setup() ends:
void loop(){
   ;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.