Servos not working with serial

Hi. I connected 2 servos to my Nano and I am controlling it with the serial monitor. Here is the code:

#include <Servo.h>
Servo servo1;
Servo servo2;
int val1;
int val2;
void setup() {
// put your setup code here, to run once
servo1.attach(9);
servo2.attach(10);
Serial.begin(57600);
}

void loop() {
// put your main code here, to run repeatedly:
Serial.println("Enter your values.");
while(Serial.available() == 0){}
val1 = Serial.parseInt();
val2 = Serial.parseInt();
servo1.write(val1);
servo2.write(val2);
Serial.print(val1);
Serial.print(", ");
Serial.println(val2);
delay(1000);
}

However the servos are sometimes unresponsive.
I know this is a problem with the serial monitor rather than the servos because the servos sometimes work and sometimes don't.
And when I tried with the serial monitor on Arduino Cloud Editor, the serial monitor showed random characters like [ _ ! "
Please help because I don't know what to do.

while (Serial.available() == 0) {}
   val1 = Serial.parseInt();
   val2 = Serial.parseInt();

So, if there is at least 1 byte available read 2 bytes. Does that sound like good practice?
Try:



#include <Servo.h>
Servo servo1;
Servo servo2;
int val1;
int val2;

void setup()
{
   // put your setup code here, to run once
   servo1.attach(9);
   servo2.attach(10);
   Serial.begin(57600);
   Serial.println("Enter your values with a space between (ex. 123 456.");
}

void loop()
{
   // put your main code here, to run repeatedly:

   if (Serial.available() >= 2)
   {
      val1 = Serial.parseInt();
      val2 = Serial.parseInt();
      servo1.write(val1);
      servo2.write(val2);
      Serial.print(val1);
      Serial.print(", ");
      Serial.println(val2);
   }
   delay(1000);
}

Set the line endings in serial monitor to "No line ending"

Or better yet, read the serial input basics tutorial for robust and non-blocking ways to read serial data (parseInt() is blocking).

See Arduino Software Solutions for various ways to read from Serial both blocking and non-blocking with their pros and cons.