Serial Monitor printing output repeatedly

Hi everyone,
I'm a beginner at Arduino and have faced a problem using a servo motor with the Uno R3.

The servo is powered by the 5V pin. My sketch outputs a prompt to the Serial Monitor, then it waits for input, reads an integer value from the Serial Monitor, and calls the servo object's write() function so it can go to the angle entered.

My problem:
After inputting an angle in the Serial Monitor, the servo goes to that angle but then goes to the 0 position again, without any input.

#include <Servo.h>

int pinServo = 9; //connected to servo motor
int pos = 0;

Servo servo;

void setup() {
  Serial.begin(9600);
  servo.attach(pinServo);
}

void loop() {
  Serial.println("Enter the angle to rotate to: ");
  while (Serial.available() == 0) {
  }
  pos = Serial.parseInt();

  Serial.println(pos);    //for debugging
  Serial.println();

  servo.write(pos);
}

This is the Serial Monitor output, when I input 150 and then 90 (I did not input the 0s):

Enter the angle to rotate to: 
150


Enter the angle to rotate to: 
0


Enter the angle to rotate to: 
90


Enter the angle to rotate to: 
0

I've looked into it a lot but can't find the solution. I'd appreciate it if anyone can help.
Thank you for your time.

Have you got the Line ending setting of the Serial monitor set something other than "No line ending" ? If so, then extra characters are being added to your input

atoi() that String.toInt() and Serial.parseInt(); use is very poor at rejecting invalid input, like "\n" or "a"
It just returns 0.

See my Arduino Software Solutions for a simple but much more robust replacement that ignores invalid numbers.
readStringUntil_nonBlocking.ino reads in data from your IDE serial connection until newline found (set newline in the IDE monitor)
ArduinoStringToInt.ino takes that String and converts it to an integer, it will complain if you don't give it an integer

A complete example sketch for reading ints from the IDE monitor, with line ending set to newline is here
ReadToInt_String.ino

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.