0

I have a strong urge to replace the framework-provided loop() function with my own like so:

__attribute__((always_inline)) inline void fastLoop()
{
}

void setup()
{
   // Performing setup here...
   Serial.begin(115200);

   // Now looping
   for(;;)
      fastLoop();
}

This way, my loop is inlined and I'm saving quite a few cycles - avoiding not only Arduino housekeeping costs, but also the function call cost which even for a void function has to be at least 6 cycles on AVR (>=2 for RCALL and 4 for RET).

This is the framework code for calling loop() from main():

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

My question is: what does this serialEvent stuff do? What features of the framework will stop working properly with my own loop?

Assuming my loop has observable side effects as required by the C++ standard, of course (otherwise it can be optimized out).

1 Answer 1

1

It depends on which "Arduino" you are running it on.

On an Arduino Uno, for example, then the only thing that won't work is the SerialEvent system. Everything else that matters is interrupts.

Here is main() on the Arduino AVR core:

int main(void)
{
    init();

    initVariant();

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

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

As you can see, loop() is run just the same way as your fastLoop(), just not inline, and adding in a call to serialEventRun() if it has been defined.

If no serial event handlers have been defined, then it won't do anything there anyway.

To save clock cycles you would get more benefit (as long as you don't want to use millis(), delay(), serial communication, etc) from disabling interrupts.

However, on an ESP32 or ESP8266 you will find that your watchdog times out and resets the unit. This is because it relies on code being run regularly to manage the WiFi connection that keeps "kicking the dog". Without that being run (which can be called by calling the yield() function) the watchdog times out.

2
  • I don't see an edit on the question. but your answer looks like you didn't read it to end
    – Juraj
    Commented Jul 8, 2019 at 16:49
  • @Juraj I had to go eat.
    – Majenko
    Commented Jul 8, 2019 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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