Skip to content
Arduino contents

Lesson 1.8: Servo motor

A servo doesn't spin endlessly: it goes to an angle and stays there, pushing to hold it. It's the actuator in barriers, robot arms and the rudders of model aircraft.

Parts

Libraries

  • Servo — bundled with the IDE

How it works

Inside there's a DC motor, a gearbox, a potentiometer attached to the shaft and a control circuit. The circuit compares the potentiometer's position with the one you ask for and drives the motor until they match.

The position is set by a pulse repeated every 20 ms (50 Hz): about 1 ms is one end, 1.5 ms the centre and 2 ms the other end. The Servo library generates those pulses and lets you talk in degrees.

On the Uno, the Servo library uses timer 1, so while a servo is attached analogWrite() stops working on pins 9 and 10.

Specifications

Travel
about 180°
Torque
1.8 kg·cm
Speed
0.1 s per 60°
Supply
4.8–6 V

Wiring

ComponentConnects toNote
Servo, brown wireGND
Servo, red wire5V
Servo, orange wire (signal)Pin 9

Code

// Sweeps the servo from 0 to 180 degrees and back.
#include <Servo.h>

const int SERVO_PIN = 9;
Servo servo;

void setup() {
  servo.attach(SERVO_PIN);
}

void loop() {
  for (int angle = 0; angle <= 180; angle++) {
    servo.write(angle);
    delay(15); // time to reach each degree
  }

  for (int angle = 180; angle >= 0; angle--) {
    servo.write(angle);
    delay(15);
  }
}

What the code does

  • Servo servo; creates the object and attach() ties it to a pin. The Uno can drive up to 12 servos.
  • write(angle) sends the angle in degrees; the library turns it into the pulse width.
  • Each delay(15) gives the servo time to reach the next degree: a full sweep takes about 2.7 s.

Step by step

  1. Connect the servo with three wires following the table.
  2. Upload the code.
  3. Fit one of the horns on the shaft to see the movement better.

Result

The servo turns slowly to one end, goes back to the other and repeats endlessly.

If it doesn't work

  • If the servo jitters or the board resets, it's drawing more current than USB can supply: power it separately and join the GNDs.
  • If it buzzes at the ends, it's hitting its stops: narrow the sweep, for example from 10 to 170 degrees.
  • If it doesn't move, check the wire order: orange is the signal.