Search code examples
arduinoesp32

ESP32 (Arduino Core): "while(true)" loop in setup function


just a short question actually but I could not find any information on that: Is it ok to not use Arduinos loop function, and rather have a while(true) loop executing in the setup function?

I'm asking because I like to have class that deals with WiFi configuration. It reads WiFi connection data from preferences and if it cannot connect (due to lack of preferences or because the configured AP is not reachable) it should open an access point, wait for configuration (via webserver) and then reboot.

But I don't want the execution pointer to reach the actual loop when WiFi connection must be configured. The actual loop is only for normal operation. Thus, I created the while(true) loop in that WiFi configuration class. It seems to work, but are there possibly any consequences that I should be aware of? Or is basically ok to do it this way?

As a note: I do use delay() calls (or yield() calls) in that while(true) loop.

Thank you!


Solution

  • Your code. You can do whatever you want. Waiting for connections in setup() is absolutely ok and quite common practice.

    As you can see in Arduino's main() implementation: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/main.cpp

    int main(void)
    {
        init();
    
        initVariant();
    
    #if defined(USBCON)
        USBDevice.attach();
    #endif
    
        setup();
    
        for (;;) {
            loop();
            if (serialEventRun) serialEventRun();
        }
    
        return 0;
    }
    

    The only thing to consider is that you cannot use SerialEvent

    https://www.arduino.cc/en/Tutorial/SerialEvent

    SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs