0

With the source code below, I'm getting what I think to be strange behaviour with the serial port output.

void setup() {
 Serial.begin(9600);
}
int c = 0; 
void loop() {
 Serial.println(c++);
}

Presumably what this will do is starting printing incrementing numbers, one on each line, starting from 0. However, my serial monitor only starts printing these numbers after the 3000 mark. I found this behaviour only after discovered in another sketch that I was losing data at the beginning.

Is this normal Arduino behaviour? Or a serial monitor problem? Or something else?

asked Mar 5, 2016 at 0:30
2
  • Is it consistent? Does it always begin at 3000? And does it continue as expected (3001,3002,...) after that? Commented Mar 5, 2016 at 0:36
  • There are many Arduino models. It helps considerably to state in the question which one you are using. Commented Mar 5, 2016 at 6:26

1 Answer 1

2

Is this a Leonardo or Yun? If it is, you have to wait until the Serial object says the USB connection is really ready:

void setup() {
 Serial.begin(9600);
 while (!Serial) {
 ; // wait for serial port to connect. Needed for native USB
}

Read this.

Because you did't wait, your loop is able to execute 3000 times before Serial actually sends something back to the PC.

answered Mar 5, 2016 at 1:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.