Variable reset to zero when each serial connection starts

My platform is Arduino Mega 2560.

I wrote a sketch to print the value of a counter to the serial port,
and then use other applications (e.g., Matlab, or the Serial Monitor) to read the value through the serial port.

The counter can be increased correctly.
However, when the next time I connect to the serial port,
the counter will be reset to zero, and I didn’t reset or reboot the Arduino.

Could anyone please show me why the variable will reset to zero,
and how the keep the counter increasing without going back to zero?

Thank you.

The sample code?

void loop()
{
static int counter = 0;

Serial.println( counter );
counter ++;
}

When the Arduino's serial port is opened, the processor is automatically reset.

Disabling auto-reset... http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

Or, you can use the EEPROM to store the value.

Hi Coding Badly,

Got it. Thank you very much for your help!!!