Servo Motor

In this project, you'll learn how to connect and control a servo motor with the Arduino. A servo motor can be used to control the head or arm movements of a robot.

A standard servo motor is capable of rotating only half a circle (from 0 degree to 180 degree) in increments of one degree.

The Servo.h system library contains all of the functions for controlling the servo motor.

Parts needed:
  • Arduino
  • Servo motor
  • Wires
Software stuff you'll learn:
Servo motor     
1 Making the connections

The servo motor has three connection wires: brown, red and orange.
  • Connect the brown wire to GND.
  • Connect the red wire to 5V.
  • Connect the orange wire to pin 9.
Servo motor connections
2 Create a new program by selecting File from the menu
  • then select Examples
  • then select Basic
  • then select Bare Minimum
Type in the code on the right.

The #include <Servo.h> tells the computer to include the Servo.h library code.

The Servo command from the Servo.h library declares a variable called myservo.


The attach command tells the computer that the servo motor is connected to pin 9.



The write command tells the servo motor to turn to the specified degree.
// need this for the servo motor
#include <Servo.h>
Servo myservo;

void setup() {
  myservo.attach(9);  // the servo motor is connected to pin 9
}

void loop() {
  myservo.write(0);   // turn the motor to 0 degree
  delay(1000);
  myservo.write(180); // turn the motor to 180 degree
  delay(1000);
}
3 Run the program and you should see the servo motor first turn to one side and then to the other side.