Code for one-time execution in Arduino

I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. That's what the setup function is for.

As such, one-time setup functionality goes in the setup function.

FWIW, if you look in the file that calls the setup and loop functions:

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.

Note:
if (serialEventRun) serialEventRun(); appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function void serialEvent(){} in your code, it will compile out completely and not be present in the produced machine code.


I usually go with Method 2, but end up doing this:

void setup() {
  //do setup stuff

  //do task
  init(); //Do start-up initialization steps
}

void init() {
  // do tasks on startup
}

void loop() {
  //do looping code
}

With the above setup it allows my code to be even more organized.


I would strongly prefer Method 2. If you ever plan to add code to handle input, output, etc, it's easy with Method 2 -- just fill in loop(), but requires reworking/refactoring in Method 1.

Tags:

Programming