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.