What is the fastest way to implement two modes selected in setup?

Hey, I want to implement two modes in my programming, that can be selected at any time, but only start when the arduino is reseted. i.e. a switch, that is only read in setup. Is there a way to implement the switching between the codes, without having the loop check the an if function everytime it loops?

my proposition would be:

#define buttonPin 5
int mode = 0;

void setup() {
  mode = digitalRead(buttonPin);
  if (mode == 0)
  {
    A();
  }
  else
  {
    B();
  }
}

void A(){
  void loop()
  {
    //routine A
  }
}

void B(){
  void loop()
  {
    //routine B
  }
}

the IDE Outputs:
Compilation error: a function-definition is not allowed here before '{' token

The same error occurs when I define the two void loop functions inside the if:


void setup() {
  mode = digitalRead(buttonPin);
  if (mode == 0)
  {
    void loop()
    {
      //routine A
    }
  }
  else
  {
    void loop()
    {
      //routine B
    }
  }
}

You must remember that loop() is called from main() under the hood. So the compiler MUST find a single instance of a function named loop(). You’ve attempted to create two such instances, and additionally have erroneously placed them within another function.

You must remember that loop() is called repetitively from main() to provide the constant-running loop() we’re all familiar with. You must replace that functionality, so you’ll want a for loop in your implementation, because if you call your loop() replacements from within setup(), setup() must never exit.

You can define two functions, for example void loopa() and void loopb(), each of which is conditionally called from setup(). Anything else that is being done by the code within main() that calls loop() will not happen. You’ll have to do some exploration to find out what that exactly is for your particular processor, because it’ll be quite different in, for example, an ESP32 vs an ATMEGA328.

Use the above as a starting point for your next attempt.

You cannot have 2 void loops()

With while(1) the code will stay in that loop until reset or re power.

Try a function pointer:


void (*runningFunction)() {nullptr};
void functA();
void functB();

void setup() {
  constexpr uint8_t buttonPin {5};
  auto mode = digitalRead(buttonPin);
  if (mode == LOW) {
    runningFunction = functA;
  } else {
    runningFunction = functB;
  }
}

void loop() {
  runningFunction();
}

void functA() {
  //routine A
}

void functB() {
  //routine B
}

so you are saying, that i shoudnt use the normal loop function and just call a function like myFunctionA in the code below?

void setup() 
{
  if (mode == 0)
  {
    myFunctionA();
  }
  else
  {
    myFunctionB();
  }
}
void myFunctionA(){
  while(1)
  {
    //my code here
  }
}

interesting, is this faster than using an if function over and over?

Probably. BTW, if is a flow control statement, not a "function".

You could do that. However, the advantage of the code I posted is that you could still put code that's common to both FunctA() and FunctB() in loop() to run and not have to duplicate it in the individual functions.

Almost but not quite, see post #4 by @gfvalvo . The void loop() MUST still be there. But also note the caveats in post #2 by @camsysca . I am no expert, but I bet there is a lot going on under the hood normally in the void loop() that now will not happen. My choic e would be a simple if or switch in void loop to avoid that last potential issue.
For a completly different approach, depending on board check out the tasking abilities. This allows what you want BUT also brings in a lot more capabilities.

Do you know how many instructions are needed to do an if? If it is a true boolean if then one and they execute at over 100 million per second depending on board used, so how slow/fast is that and what is the overhead of the function pointer?

When I was being paid to code, most $5 million main frames ran at 5 million instructions per second. Many boards used in this forum run at several times that speed.

@pukesmiley

EXCELLENT point and addresses the other excellent point in post #2 by @camsysca

I know you are sure you will never need to change the decision made in setup, but 'what if' that requirement popped up?
It is a standard procedure (my operators could do this) to add/delete/pause tasks in certain systems all through a rather primitive UI which could even be the Serial port. I am fairly certain that could also be done with function pointers (change only)

Ok, thank you everybody. I will try out the function pointer now

Show us the code when you are done, in order for us to tell you if you got the different points raised.

Yes, in the main() function other things than loop() can be / are called.
This might differ per board by the way, look for main.cpp or a similar named file.

This is for AVR, in which main also handles the serialEventRun()

int main(void)
{
	init();

	initVariant();

#if defined(USBCON)
	USBDevice.attach();
#endif
	
	setup();
    
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
        
	return 0;
}

You could add your own (conditional) code in main(), before or after the call to setup() or anywhere in the for() loop. E.g. break out the for() loop to implement exit(), or check IO pins, increment a counter, choose between loop() and loop1() etc.
Please note that portability (and upgrades) will be your new problem :)

Better handle this kind of magic in setup()..

PS,
do not forget pinMode(buttonPin, INPUT_PULLUP);

No surprise, but I think the function pointer technique will also work as long as the function is non looping. Also a simple if or switch in loop works for the OPs requirement. KISS guys.

adding just before that

  pinMode(buttonPin, INPUT_PULLUP);

could be useful depending on how the switch / button is connected.

Remember to make those new functions NON looping so control returns to the normal main loop for reasons most recently discussed in post #15 by @robtillaart

Hello pukesmiley

My recommendation would be:

// https://forum.arduino.cc/t/what-is-the-fastest-way-to-implement-two-taskNmrs-selected-in-setup/1398992
#define ProjectName "What is the fastest way to implement two taskNmrs selected in setup?"
constexpr uint8_t ButtonPin {A0};
void (*setups[])() {
  setup_Tsk_A, setup_Tsk_B
};
void (*loops[])() {
  loop_Tsk_A, loop_Tsk_B
};
uint8_t taskNmr;
//----------------------------------------------------------
void setup_Tsk_A()
{
  Serial.println(__func__);
}
void setup_Tsk_B()
{
  Serial.println(__func__);
}
//----------------------------------------------------------
void loop_Tsk_A()
{
  Serial.println(__func__);
}
void loop_Tsk_B()
{
  Serial.println(__func__);
}
//----------------------------------------------------------
void setup()
{
  Serial.begin(115200);
  Serial.println(ProjectName);
  pinMode (ButtonPin, INPUT_PULLUP);
  taskNmr = digitalRead(ButtonPin)?LOW:HIGH;
  setups[taskNmr]();
}
//----------------------------------------------------------
void loop()
{
  loops[taskNmr]();
  delay(1000);  // for testing only
}
//----------------------------------------------------------

Possibly. But why do you want that?

If you think using if() that way will be slow, it won't. If any of these other suggested techniques are faster, the improvement will be so tiny that you will probably never notice it or be able to measure it.

There is a phrase to describe what you are asking: "Premature Optimisation" :slight_smile: