Every time you open the serial port, the Arduino resets. Every time you close the serial port, the Arduino resets.