I have a simple program that basically initializes the Serial Monitor then displays a simple, incrementing variable. The variable is initialized to 0 at startup. The strange behavior is how the IDE reacts
when I launch the Serial Monitor. Here is the code:
int x = 0;
void setup() {
delay(1000);
Serial.begin(9600);
Serial.println("Setup End");
}
void loop() {
Serial.println("Loop Start");
int y = 0;
while(1)
{
Serial.print(x++);
Serial.print("-");
Serial.println(y++);
delay(500);
}
}
When I RUN the code and select the SERIAL MONITOR to view the results, the two text outputs "Setup End" and "Loop Start" do not display. The monitor opens with the values of "x" and "y" displayed. The values displayed do not start with 0 as expected but instead displays the counter with values of 5 or more. If I close the SERIAL MONITOR and then select it again, I expected to see the program restart and display values from 0.... HOWEVER, what I get is counter values that appear to have been increasing while the SERIAL MONITOR was off. My past experience with the SERIAL MONITOR has been that when I open the SERIAL MONITOR, it resets the code and executes it from the beginning. See attached screen shot. If I close the SERIAL MONITOR and reopen, I expected to see x and y values starting at 0 but they don't. They will appear with values grater than what you see in the screen shot.
No reset when you open the serial port. 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.
Leonardo/Micro will reset on:
power on
press on reset button
open serial connection at 1200 baud and closing again
To add to that, there is a difference in behaviour when doing a power cycle; it will skip the boot loader.
Your code is also missing a while(!Serial); to wait for the Serial monitor to be opened by the user. So the Arduino happily sends data to the lower level routine which will discard the data as there is no connection established yet. Eventually, when the connection is established, the lower level routine will pass the data that it receives to the PC (and hence the counting that you see in serial monitor does not start from zero).
PS
Your code can never initialise the Serial Monitor !! Not on an Uno and not on a Micro.
PPS
In future, please indicate in your post which board you're using. It's very relevant in this case.
Yep, my bad.... I knew I should have mentioned it was a Micro... but forgot.
Good points and sounds like that is my issue. Only recently started using
a Micro... THANNK YOU