Servo resets to 0 after serial input

Hello!
I'm new to using arduinos and trying to move a servo to certain degrees fron serial inputs. I want the servo to stay in said position until it gets a new input but I have no idea of how to do this. Currently the servo returns to 0 degrees after a short stop at the inputted degree value, it seems like the variable "angle" is resetting to 0 after each loop. I'm thankfull for any advice!

My code currently look like this:

#include <Servo.h>  // include the servo library

Servo myServo;  // create a servo object
int angle;  // create a variable to store the angle

void setup() {
  myServo.attach(9);  // attach the servo to pin 9
  Serial.begin(9600);
}

void loop() {
  // write the current angle
  Serial.println(angle);
  // read the angle from the serial port
  if (Serial.available() > 0) {
    angle = Serial.parseInt();
    // move the servo to the specified angle
    myServo.write(angle);
  }
  
  delay(500);
}

Change the line-ending on the serial monitor to "none"

1 Like

If whatever is sitting in the input buffer doesn't look like a number, this will return zero.

1 Like

Look at the serial input basics tutorial for more robust ways to input serial data.

1 Like

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