Can not set up serial from within constructor, when called outside function

It seems that it is not possible to set up Serial from within a constructor, when the object is initialized outside of a function. With the code below, the Arduino keeps waiting for the serial to be set up, and thus just blinks.

class Foo
{
public:   
   Foo ();
};

Foo::Foo() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  while(!Serial) {
    digitalWrite(13,HIGH);
    delay(200);
    digitalWrite(13,LOW);
    delay(200);
  }
  Serial.println("Foo constructor");
}

Foo foo; // when initialized here, will NOT set up Serial

void setup() {
  // if initialized here, constructor will set up Serial 
  // Foo foo; 
}
void loop() {}

The reason I am playing with this is because I need to make some changes to a library, new-LiquidCrystal. In that process I would like the constructors, LiquidCrystal_I2C to print stuff, just like printing is helpful when debugging. But I guess that is just not possible, when the lcd object is initialized outside a function?

Why is it not possible to set up Serial like this?

It seems that it is not possible to set up Serial from within a constructor,

Correct. The hardware is not ready at that time, AND you have no idea whether your constructor is called before or after the constructor(s) for the HardwareSerial class.

You will have observed that the HardwareSerial constructor does not set up the hardware, either. You must call the begin() method, which you can only do after all the constructors are called and the hardware is ready.

Your class needs a begin() method, too.

By the way, pinMode() doesn't belong in a constructor, either, for the same reasons.

That all helped. Thanks :slight_smile: