Control a servo motor

Sweep a servo motor from 0 to 180 degrees, then set its angle by typing a number in the Serial Monitor.
  • Level:Beginner
  • Duration: 35 min
  • Ages 10+
  • Platform: Arduino

What you'll need

Control a servo motor – EEMENTOR STEM lesson

A servo motor turns to an exact angle and holds it there. Servos steer model cars, move robot arms and open little gates. In this lesson you make one sweep back and forth, then control it yourself.

What you'll learn

  • How servo motors are controlled
  • How to use a library (Servo.h)
  • How to read numbers typed into the Serial Monitor

What you need

  • UNO R3 board and USB cable
  • Small servo motor (SG90 type)
  • 3 jumper wires

Wiring

The servo has three wires. The colours are usually brown (or black), red and orange (or yellow).

Breadboard wiring diagram: Control a servo motor
Breadboard view. Check each connection against the wiring table below.
Servo wire UNO pin
Brown / black (GND) GND
Red (power) 5V
Orange / yellow (signal) 9

Part 1: Sweep

#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(9);
}

void loop() {
  for (int angle = 0; angle <= 180; angle++) {
    myServo.write(angle);
    delay(15);
  }
  for (int angle = 180; angle >= 0; angle--) {
    myServo.write(angle);
    delay(15);
  }
}

Part 2: Choose the angle yourself

#include <Servo.h>

Servo myServo;

void setup() {
  Serial.begin(9600);
  myServo.attach(9);
  Serial.println("Type an angle from 0 to 180 and press Enter");
}

void loop() {
  if (Serial.available() > 0) {
    int angle = Serial.parseInt();
    while (Serial.available() > 0) Serial.read(); // clear the rest of the line
    angle = constrain(angle, 0, 180);
    myServo.write(angle);
    Serial.print("Moved to ");
    Serial.println(angle);
  }
}

How it works

The Servo library sends a pulse to the signal wire about 50 times per second. The length of each pulse, roughly 1 to 2 milliseconds, tells the servo which angle to hold. constrain() keeps the value between 0 and 180, so a typo can't push the servo past its limits.

Try this next

  • Combine this with lesson 2: point the servo at 0° when something is far away and at 90° when it's close, like an automatic gate.
  • Tape a paper arrow to the servo horn to make a dial that shows the distance.

Troubleshooting

  • The board resets or the servo jitters: servos draw bursts of current. Use a good USB port, or power the servo from a separate 5 V supply with its GND connected to the UNO's GND.
  • Servo doesn't move: check that the signal wire is on pin 9.

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

UNO R3 Starter Kit | Arduino IDE Compatible | Free Tutorials $48.00

Shop the kit