Servo unwanted sweeping

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);
  }
}

Hi, A servo will usually go to the position you command as fast as it can.

You need something like the accelservo library to modify the servo acceleration:

http://www.airspayce.com/mikem/arduino/AccelStepper/

Have a look at how the servo is controlled in Several Things at a Time. Note that it is not using FOR

I think your problem is that your FOR always starts at 0 and I think you want to move from whatever the latest position might be.

...R

This line looks similar to the sweep example in the library.

for (int servoPosition=0; servoPosition <= 180; servoPosition++){

Try looking at the pot example and modify that.

The servo sweeps with every iteration of loop() in your sketch. Add a condition to skip the sweep as long as the servo should stand still.

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

Depending on what your overall intention was, maybe…

    time = millis();    
  } // <--- ...this brace...
  delay(10);
  }
 } // ...was intended to be here?
}