# Controlling speed of servo motor

Hi

I have written a code which turns the servo motor 180 to the left then stops when button is pushed. And when button is pushed again it moves 180 to the right then stops. My question is how do i increase the speed of the servo motor

Here is my code retrospect to the question

``````#include <Servo.h>

// Set digital pin numbers:
const int servoPin = 8;  // The number of the Servo pin
const int buttonPin = 9;  // The number of the Pushbutton pin

int buttonState = 0;  // Variable for reading the pushbutton status
int directionState = 0;  // Variable for reading direction of the servo

Servo myservo;  // Create servo object to control a servo

int pos = 0;  // Variable to store the servo position

void setup() {
myservo.attach(8);  // attaches the servo on pin 8 to the servo object
pinMode(buttonPin, INPUT);  // initialize the pushbutton pin as an input

}

void loop() {
// read the state of the pushbutton value:

if (directionState == 0) {
//The button is pushed
if (buttonState == HIGH) {
directionState = 1;// The direction for the servo is clockwise

// goes from 0 degrees to 180 degrees in steps of 1 degree
for (pos = 0; pos < 180; pos = pos + 1)
{
myservo.write(pos);  // tell servo to go to position in variable ‘pos’
delay(15);  // waits 15ms for the servo to reach the position
}

}

} else if (directionState == 1) {
// The button is pushed
if (buttonState == HIGH) {
directionState = 0;  // The direction for the servo is anti-clockwise

// goes from 180 degrees to 0 degrees in steps of 1 degree
for (pos = 180; pos>=1; pos=pos-1)
{
myservo.write(pos);  // tell servo to go to position in variable ‘pos’
delay(15);  // waits 15ms for the servo to reach the position
}

}

}

}
``````

help will be much appreciated

You could take out the delays

Perfect , thank you :)

Of course, once the delays are gone, you may as well get rid of the for loops too.

i have another question , if i wanted to add another line of code to the existing code so that it progresses with another function : In this case i want to add a 2 button click so the servo continuously moves from right to left , how would i go about doing that?

What do you mean by "a two button click"?

sorry i meant to say a press and hold function to start another line of code

Why does it matter what the direction is, if the switch is not pressed?

You need to define what press and hold means, in terms of state of the switch AND time. When you can do that, writing the code is trivial.