Garbage on serial output on startup

Hello,

I've been struggling with this for a while now a can't undertstand what I am doing wrong...

I have been testing this on 2 arduinos Mega 2560 and I get the same behavior so I guess it is not a hardware issue.

I have a very simple code :

#include <Arduino.h>

class Box2 {
    public:
        Box2();

};

Box2::Box2() {
    Serial.println("before delay");
    //delay(1);
    Serial.println("Building Box Object");
}

Box2 box = Box2();

void setup() {

    Serial.begin(9600);
    Serial.println("Starting !");

}

void loop() {

    delay(1000);
    Serial.println("Looping...");
}

When starting serial monitor, I get this :

I have garbage when instanciating Box object but then seems to run fine.

If I add delay(1) between the 2 println in Box::Box, the sketch seems to hang after outputing garbage :

If I comment out Box2 box = Box2();, everything is ok.

Is there something I am doing wrong in the class declaration ? in constructor ? anywhere else... ?

Any help will be appreciated :slight_smile:

Jean-Sébastien

The C++ spec does not say exactly when box willl be instantiated but it will be before the setup is called, so your Serial line is not configured

usually you have a begin() method that you call from the setup to complete whatever needs to be done and requires the environment to be set up

class Box2 {
  public:
    void begin();
};

void Box2::begin() {
  Serial.println("before delay");
  delay(1000);
  Serial.println("Building Box Object");
}

Box2 box;

void setup() {

  Serial.begin(115200); // don't go slow ! 9600 is so 20th century :) 
  Serial.println("Starting !");
  box.begin();
}

void loop() {

  delay(1000);
  Serial.println("Looping...");
}

Hello @J-M-L ,

Ahhhhhh... Seems so obvious when you say it !

Yeah... OMG... Am I that old ? :wink:

Thanks a lot for the fast and clear reply.

JS

Don’t Worry - I’m older :slight_smile:

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