Servo Motor + push button + 2 positions , Question RE motor speed

Brand new, light programming in the past but my first foray with C# and arduino, trying to make a simple servo that is controlled by a biased push button that when pressed once will take the angle to 90 and then when pressed again will return back to the original angle. I have it figured mostly out to accomplish this simple task but the speed is very fast. I tried breaking the movement into pieces but that didn’t seem to do anything and messing with the delays has no effect. Code is provided below and any instruction would be oh so greatly appreciated.

Thanks in advance!


#include <Servo.h>
int button = 5; //button pin, connect to ground to move servo
int press = 0;
Servo servo;
boolean toggle = true;

void setup()
pinMode(button, INPUT); //arduino monitor pin state
servo.attach(7); //pin for servo control signal
digitalWrite(5, HIGH); //enable pullups to make pin high

void loop()
press = digitalRead(button);
if (press == LOW)
toggle = !toggle;

toggle = !toggle;
delay(300); //delay for debounce

link for type of servo I am using
Servo Model

Edit: went back to original code as it was easier to read and added link to servo type

Firstly, have a look at the StateChangeDetection example in the IDE to see how to detect when the button becomes pressed rather than when it is pressed.

When it becomes pressed move the servo. To move it slowly in small steps you can use a for loop as in the Servo Sweep example as long as the program is not expected to do anything else but move the servo during the sweep, ie no reading of inputs.

If the program is expected to do other things during the sweep then you need to use millis() for timing. See Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

If you just want to slow down the servo movements the simple way is to use the VarSpeedServo library instead of Servo. That takes an extra "speed" parameter on the write().


How would you walk one mile in different amounts of time? To get to the end quickly, you take large steps with minimal pauses between steps. To get the end slowly, you take shorter steps and pause longer between steps. The shorter the step, and the longer the pause, the slower you go. The longer the step, and the shorter the pause, the faster you go.

The speed of the servo can be adjusted using exactly the same approach.

You are writing a value to the servo and it moves there as fast as it can.
As PaulS suggests, take small steps with a small delay between them.
Look at the servo sweep tutorial for an example.

This is what VarSpeedServo does behind the scenes, which is another good solution.