I can't get while(!Serial) to work in the setup. I'm using IDE 1.0.5 with a Leonardo.
int i = 0;
void setup() {
Serial.begin(9600);
while (!Serial){
;
}
//delay(10000);
Serial.println("test");
}
void loop(){
Serial.println(i);
i = i + 1;
delay(1000);
}
When I open the serial monitor I would expect:
test
0
1
etc
I get:
65
66
ect
It doesn't seem to be waiting for the serial monitor to open connection. If I use the delay before Serial.println("test"); I can open the serial monitor fast enough to see test, 0, 1 ect.
The while(Serial) loop is NOT waiting for you to open the Serial Monitor. It is waiting for the USB to Serial chip to report that it us ready. That chip gets ready pretty quick.
Why does that affect the counter? I thought that while(!Serial) should end as soon as serial is ready, no?
Edit: I just tested your code, it is working here. Starting at 0.
Edit2: Think before I post is the keyword. My board restarts whenever I open serial monitor. Your board doesn't I guess.
PaulS:
The while(Serial) loop is NOT waiting for you to open the Serial Monitor. It is waiting for the USB to Serial chip to report that it us ready. That chip gets ready pretty quick.
I don't have a Leonardo, but my understanding from other people's comments here and supported by the documentation for the board is that on the Leonardo the Serial operator bool() returns true when the virtual serial port at the far end of the USB/serial connection has been opened i.e. when the serial monitor has been opened.
Guide to the Arduino Leonardo and Micro:
Unlike the Arduino Uno, the Leonardo and Micro won't restart your sketch when you open a serial port on the computer. That means you won't see serial data that's already been sent to the computer by the board, including, for example, most data sent in the setup() function.
This change means that if you're using any Serial print(), println() or write() statments in your setup, they won't show up when you open the serial monitor. To work around this, you can check to see if the serial port is open like so:
// while the serial stream is not open, do nothing:
while (!Serial) ;