unwanted servo rotation

Hi guys,

I am currently experimenting with a small 9g servo.

In my project, I simply have a button connected to toggle a variable which turns on and off an LED.

I also have a servo connected.

I want the servo to go to position 180 when the buttonState variable is High I want the servo to move to position 180 with incremental delays (Slower speed). So I used a for loop for this.

However, what I am getting is that the servo is moving to position 180 and then rotating back to 0 and then repeating.

I want to servo to stay at 180 while buttonState is High.

I am new to code so I am probably missing something simple.

I appreciate anyone who may advise.

Thank You.

#include <Servo.h>

//button connected to toggle state variable high/low

int inPin = 2;         // the number of the button input pin
int outPin = 13;       // the number of the button output pin

int buttonState = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

Servo myServo;

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
  myServo.attach(9);
  
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (buttonState == HIGH)
      buttonState = LOW;
    else
      buttonState = HIGH;

    time = millis();    
  }

  digitalWrite(outPin, buttonState);

  previous = reading;

  for (int servoPosition=0; servoPosition <= 180; servoPosition++){
  if (buttonState == HIGH)
  myServo.write(servoPosition);
  delay(10);
  }
}

Your code is not correct, when your button is HIGH then you should add the code for servo and it will look something as shown below.

if(digitalRead(Button) == HIGH)
{
    for(x = 0; x < 180; x++)
    {
        Servo.write(x);
    }
while(digitalRead(Button) == HIGH);
}

In the above code I have first checked the button state and after that I have moved the servo and once servo is moved then I have placed a check that when button is HIGH don’t move forward so now your servo will move to 180 and will remain there. Moreover you should also have a look at [Servo Motor Control using Arduino.](Control Servo Motor with Arduino in Proteus - The Engineering Projects)