Controlling a servo motor with an Arduino

Servo motors are motors that can be used to rotate parts of machines with precision. Small servo motors can be directly connected to an Arduino microcontroller board to control the position of the shaft which is usually fitted with a gear. A servo motor uses feedback to determine the position of the shaft and precisely control its movement. Different shaped arms can be attached to the shaft to control different types of objects.

servo

Servo motos can be used to:

  • move objects
  • rotate objects
  • move legs, arms or hands of robots
  • move sensors

They can be used in small applications such as controlling the rudder of a radio-controlled model aircraft, to large robots and in-line manufacturing.

Servo motors have the following three wires:

  • Ground (usually brown/black)
  • 5V power (usually red)
  • PWM (pulse width modulation) wire (usually orange)

Wiring guide

The brown ground wire is connected to GND on the Arduino, the middle red power wire is connected to 5V on the Arduino, and the orange PWM wire is connected to a PWM pin on the Arduino (a number with a ~ next to it), eg. pin ~9. The servo motor can be connected directly to the Arduino (you may need male-to-male jumper wires) or via a breadboard.

servoarduino

The code

The code below is used to rotate the servo motor from 0 to 180 degrees, and then from 180 degrees back to 0 degrees. Note: Most small Arduino servo motors can rotate up to 180 degrees.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

void setup() {
  myservo.attach(9);  // attaches the servo motor on pin 9 to the servo object
}

void loop() {
  // use a loop to move from 0 degrees to 180 degrees in 5 degree steps
  for (pos = 0; pos <= 180; pos += 5) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  // use a loop to move from 180 degrees to 0 degrees in 5 degree steps
  for (pos = 180; pos >= 0; pos -= 5) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}