Servo acting weird because of my code (SOLVED)

I'm making a project in which I'll be able to control a couple of servos using a joy-stick module. I'm starting on the first servo, using the Y-axis of the joystick to control it. When I try it out with this code, the servo jolts a little at the start, and then turns 180 degrees the FIRST time I move the joystick. When I try to repeat this before resetting the Arduino, the servo does nothing. Here's m code:

#include <Servo.h>
Servo myservo;
Servo myservo2;


const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output

void setup() {
    myservo.attach(3); 
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200);     //USE 115200 BAUD
  
}

void loop() {
  Serial.print("Switch:  ");
  Serial.print(digitalRead(SW_pin));
  Serial.print("\n");
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  ServoUpdate1();
  if (analogRead(Y_pin) < 100){
  myservo.write(90);
  delay(1);
  myservo.write(180);
  delay(1);
  myservo.write(270);
  delay(1);
  myservo.write(0);
}
  delay(500);
}

Thanks in advance, you guys are great.

What servo have you got that can go to 270° ? Most servos work between 0 and 180° and many only go to 150° or 170°. If you try to drive a servo past its physical end-stop you will overload it and may damage it.

It's a good idea to command the servo to move to a mid position BEFORE you attach. For example

myServo.write(90);
myServo.attach();

A delay of 1 millisec is not enough time for the servo to move. Start with delay(2000) between moves so you can see what is happening.

...R

delay(1);Even more so, the servo is being sent pulses at 50hz, that is every 20 ms (the library uses a timer for that, btw the examples always put a 20ms delay() after the write) .the pulses vary in length from about 500us to 2000us , so probably it responds to the final myservo.write(0); every time.

The write(270) does nothing. The valid range of angles are 0 - 180. Numbers outside that do nothing unless they are valid for writeMicroseconds(), 544-2400 as standard, in which case the write is translated into a writeMicroseconds.

Any chance of you posting the complete code? We seem to be missing a ServoUpdate1() which sounds like it might be relevant.

Steve

Thank you guys so much! It's working