Home

How to Control a Servo

You may need to install the Arduino servo library from Tools → Manage Libraries... Type Servo in the search box under LIBRARY MANAGER and press the ENTER key. Then click INSTALL under Servo by Michael Margolis, Arduino.

The Arduino servo library implements servo support as a C++ class named Servo. Since the servo library is an add-on, you must add #include <Servo.h> at the top of your sketch in order to use it. Then you will need to declare a Servo object for each servo output before setup() function, and attach it to an Arduino digital pin with a call to the object's attach() method inside setup() function.

You can set a servo's position with a call to the Servo object's write(angle) method. The allowed values for angle are 0 to 180, which is misleading because the swing angle depends entirely on the physical construction and/or firmware settings (high end digital servos only) of each individual servo. You can buy servos with swing angles ranging from 90° to at least 2520° (seven full turns!). For all servos, obj.write(0); positions the servo to one end of its swing, obj.write(90); positions the servo to its midpoint, and obj.write(180); positions the servo to the other end of its swing.

If the angle value passed to write(angle) is greater than 200, it is treated as a pulse width in microseconds. This may offer more precise servo positioning, depending on the underlying microcontroller timer hardware.

Note: The default pulse width limit values for the attach() method are 544 to 2400 microseconds. Always explicitly pass the limit values 1000 and 2000 microseconds to attach() (as in the example code below) unless you KNOW FOR CERTAIN that your servo can accept a wider range of pulse widths. Analog servos can be destroyed by attempting to position them beyond their physical limits.

// Pull in servo library declarations
#include <Servo.h>

// Declare a Servo object instance variable
Servo outp;

void setup()
{
  // Initialize servo connected to D6, using modern servo timing
  outp.attach(6, 1000, 2000);

  // Move servo to neutral position
  outp.write(90);    // degrees (VERY nominal!)

  // Move servo to neutral position
  outp.write(1500);  // microseconds
}

void loop()
{
}

Home


Questions or comments to phil@munts.net