Bypass serial monitor interference with running program

Whenever I open or close the serial monitor to see values, it resets the whole program. So for this very simple servo program I have, whenever I open the SM, the servo jumps back to position 0. Same thing happens when I close the SM. Is there a line of code to get past this? I just want to open the SM whenever and have the program run continuously.

#include <Servo.h>

Servo servo1;
int pos = 0;

void setup(){
 servo1.attach(9);         //connect the servo to digital pin 9 (PWM pin)
 Serial.begin(9600);
}

void loop(){
 for(pos=0; pos<180; pos+=1){      //will rotate servo from 0 to 180 degrees
  servo1.write(pos);                 //write function tells servo to go to whatever position
  Serial.println(pos);
  delay(10);                         //wait for servo to reach desired position
 } 
 for(pos=180; pos>0; pos-=1){     //roates servo from 180 to 0 degrees
  servo1.write(pos);
  Serial.println(pos);
  delay(10); 
 }
}

Whenever I open or close the serial monitor to see values, it resets the whole program.

Yes, it does.

Same thing happens when I close the SM. Is there a line of code to get past this?

No.

I just want to open the SM whenever and have the program run continuously.

There are ways to physically alter your Arduino to prevent this. But, in your case there is a super simple solution. Don't keep opening and closing the serial monitor.

Why are you, anyway?

On some of the Arduino boards there is a jumper that you can cut to disable auto-reset. This has been discussed before. Search for disable auto reset.

Ok so there's no way to do it with software. I guess one physical way is to connect a 10uF between the reset pin and ground. There's also another option which involves cutting the RESET-EN trace on the board. But with either these options, when uploading new code, you have to press the reset button. I could alter the code so that it'll only run when I open the SM.

Then it won't be much good if you don't have a serial connection, eh? It has to be tethered to a computer.

Besides, the code doesn't know if you have anything listening on the serial port unless you wait for something to be typed.

Shoving the capacitor in and out doesn't sound too much of a hardship, once you have the code debugged.

On one of my Arduinos I have cut the reset link and replaced it with a sub miniture slider switch.