The Servo class provides a number of methods that can be used on its objects. I recommend you check out the documentation for the Servo library on the www.arduino.cc Website, but here are the principal ones you should know about:
attach connects a servo object to a specific pin of the Arduino. You can use any pin.
detach removes the servo object, effectively disabling the servo and removing its power.
write specifies where to position the servo. The method accepts several forms of values. A value of 0 to 180 denotes degrees; this positions the shaft of the motor to a corresponding angle. (When used with modified servos, 0 and 180 make the motor turn in one direction or the other; 90 makes the motor stop.) Values from 544 to 2400 are treated as microseconds and position the servo by generating pulses of the specified duration. Typical servo specs are 1000 to 2000 microseconds for a standard 90° to 120° arc.
writeMicroseconds specifically indicates that you wish to use microseconds to control the servo position.
read returns the last specified position of the servo, in degrees.
One technique to try is writing a position to the servo before calling the attach method—attaching the servo is what gives it power When you create a new Servo object, its position is automatically given a default of 90. By setting a position first, then attaching the servo, you can have it start at a position other than 90. For example:
void setup() { myServo.write(180); // Start at 180 degrees instead of 90 myServo.attach(9); }
There’s also no absolute requirement that you use the attach method in the setup() function. You can place it in the loop() function, and use the detach method to remove power to the servo. The following code demonstrates sweeping the servo right and left, while stopping it (actually turning it off) for 4 seconds in between. The action is a bit easier to see when using a servo modified for continuous rotation.
void loop() { myServo.attach(9); // Attach and apply power myServo.write(0) // Position servo delay(delayTime); // Allow transit time myServo.detach(); // Detach and remove power delay(4000); // Wait 4 seconds myServo.attach(9); // Re-attach and apply power myServo.write(180); // Move servo to other end delay(delayTime); // Allow transit time myServo.detach(); // Detach again }
Detaching the servo will prevent it from buzzing or, if using a servo modified for continuous rotation, stop if from slowly “creeping” when you set its position to 0 (stop). Since the servo is not being powered, it also saves battery juice when your Arduino and servos are mounted on a mobile robot.