Serial.print not working in "setup" section of sketch

Hi,
I'm fairly new to Arduino, so maybe my issue is very simple.
When I use serial.print() to return messages and values to the serial monitor, I'm having trouble getting it to work in the "setup" section. It seems to work only in the "loop" section.

For example in the following code:

char letters[] = "hello";
int x = 1;

void setup() {
  Serial.begin(9600);
  delay (5000);
  Serial.println("Starting");
  Serial.print("The string is: ");
  Serial.print(letters);
}

void loop() {
  delay (5000);
  if (x == 1) {
    if (!strcmp(letters, "hello")) {
      Serial.println("matching");
    } else {
      Serial.println("not matching");
    }
    x++;
  }
}

I added a delay after the serial port initialization in case the issue was that it was not ready yet. But it seems that even the delay does not take place in the setup. The "starting" and "The string is hello" messages do not appear on the serial monitor. I had to resort to a dummy condition for the code in the loop section to make it run only once... If I don't have the delay at the beginning of the loop section, by the time I switch the serial port back to the right com port (it always switches to another port after uploading) and opening the monitor, the code has run and I don't get the message. This tells me that the 5s delay in the setup is not taking place.

Is there a solution to this? How can I get message on the serial monitor to execute in the setup?

Thanks,
Ben

You didn't say which board you're using or which host.

I'm using the Arduino Nano 33 BLE Sense and developing on IDE version 1.8.13.

And your console is open at 9600 bauds ?

Have you tried a simple sketch. (Console at 115200)

void setup() {
  Serial.begin(115200); // no need to go slow
  while(!Serial);
  Serial.println("Hello World");
}

void loop() {}
1 Like

Thanks J-M-L!
That works perfectly. It makes it wait until I open the monitor, then I get the messages from setup and from the loop.

Thanks,
Ben

:slight_smile:

Have fun!

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