Serial.begin() Before setup( ) { }

I have some classes (Some with almost purely static methods) that are instantiated globally before setup.

I've been trying to debug some issues by adding Serial.print's but getting garbage at the serial monitor, even if I try moving Serial.begin to the start of the constructor, of what I believe to be the first class that gets instantiated.

Is there any way to force or wait for serial to be ready before any of my classes get instantiated in the global space? (Short of heap allocating the objects later with new inside setup, after I know for sure that Serial is working)

Global's initialization (and constructor call) happens before main() gets called (and order is not guaranteed)

the arduino main() calls init() which actually disconnects pins 0 and 1 from the USART so that they can be used as normal pins unless you call Serial.begin() in the setup().

➜ may be try to instantiate dynamically in the setup(), after Serial.begin()

Do that.

Yeah I suppose it's only for debugging. Just wanted to check I wasn't missing a trick.

Cheers both!

Call it a hacky workaround... but adding a simple struct with a constructor and instantiating an object of the struct before other global objects seems to have done the trick too!

struct WaitForSerial {
  WaitForSerial() {
    Serial.begin(9600);
    while (!Serial);
  }
};

WaitForSerial WFS; // Create this in the global space before anything else.

// Other variables/objects go below here.

void setup() { /* ... Code ... */ }
void loop() { /* ... Code ... */  }

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.