Running code out of the main loop?

Hi all,
Another newbie question I'm afraid.

Is this permissible with an Arduino sketch, if so under what circumstances is it used?

void loop
{
// main loop with some code in here

othercode() //At some stage I want out of the main loop to run othercode()
}

void othercode()

{
//run othercode in here
}

When othercode is finished running do I return to where I came from in the main loop?

I've seen something similar in a sketch and was just wanting to understand it's use.

Cheers
Colin

When othercode is finished running do I return to where I came from in the main loop?

Yes, when calling a function from inside the loop, the called function, when done, will return to the statement following where it was called in the loop. In your example where the function was called as the last statement in the loop, the return will be back to the start of the loop function.

Lefty

Great thanks, so is it good coding practice to write my code with functions outside the main loop like this, or is that a decision largely driven by the code itself (hope that makes sense too :relaxed:). I guess I'm trying to ask if there are 2 ways of running my functions - inside the main loop and outside the main loop and which to use when?

It's not really running outside of the main loop, it's just written that way. After all, when done you are then executing the next step in the main loop.
From your point of view, if you copied that 2nd into the main loop without calling it a function, it would still run the same way. Functions just make it easier to generally not have to write the same software over several times when it can be done just once.

so is it good coding practice to write my code with functions outside the main loop like this,

Yes, if the function encapsulates a specific function.

loop () {
   func_to_do_everything();
}

No point in the above, but

loop () {

   key = readKey();
   
   switch (key) {
       case 'a':
       etc etc.
   }
}

Good if the code required to read a key is complex or more than say 10 lines of code because the function does a specific task and is named appropriately. However if the readKey() func was just this

byte readKey() {
   return PINB;
}

Then this is silly use of a function, the code may as well have been in the main loop.

An exception to the above is when you know that one day the code may run with different hardware so even though now it only does a read of PORTB in future the reading of a key may be a mor ecomplex process. In this case it make ssens to isolate this key reading code inside a finction.

I hope that hasn't made it more confusing :slight_smile:


Rob