Sub topic 5
Moving a Servo with the Servo Library
This chapter covers how the Servo library turns angles and pulse widths into motion. It assumes you can upload sketches with the Arduino IDE and write basic C++ (setup, loop, variables, functions). It also assumes you know what voltage, current, and ground are, and that you have read the earlier chapters on external power with a common ground and on how a hobby servo reads its position command.
What the library does for you
A hobby servo expects a pulse about every 20 ms. The pulse width, usually 1000 to 2000 µs, sets the target position. You could generate that pulse yourself with digitalWrite and delayMicroseconds, but your sketch would then have no time for anything else.
The Servo library handles this for you. It uses a hardware timer to generate the pulses in the background, so loop() stays free. On an Arduino Uno, Timer1 does this work. That has two side effects:
- On boards based on the ATmega328P (Uno, Nano, Pro Mini), using the library disables
analogWrite()on pins 9 and 10, because Timer1 drives their PWM. - The library supports many servos at once (12 on a Uno), but all of them share the same timer.
The following diagram shows the path from your code to the servo.
Wiring recap
Before writing code, check the wiring. A small micro servo such as the SG90 can draw several hundred milliamps while moving and more when stalled. Power it from an external 5 V supply, not from the Arduino pin.
- Connect the servo's red wire to the external 5 V supply.
- Connect the servo's brown or black wire to the supply ground.
- Connect the supply ground to the Arduino GND, so the signal has a shared reference.
- Connect the servo's signal wire (orange or yellow) to a digital pin, such as pin 9.
For a single SG90 doing light work, the Uno's 5 V pin often works over USB. Treat that as a bench shortcut. It is the main source of the resets covered in a later chapter.
The core calls
The library gives you a small set of functions. You will use these four most.
| Function | Purpose |
|---|---|
| `attach(pin)` | Starts sending pulses on the pin. |
| `attach(pin, min, max)` | Same, but sets the pulse widths (in µs) that map to 0° and 180°. |
| `write(angle)` | Sets the target position in degrees, 0 to 180. |
| `writeMicroseconds(us)` | Sets the pulse width directly. |
| `read()` | Returns the last angle you commanded. |
| `attached()` | Returns true if the object is currently sending pulses. |
| `detach()` | Stops the pulses, so the servo goes limp. |
A first sweep
This sketch moves the servo back and forth. It stays a little inside the end stops, at 10° and 170°, so the gears are not pushed against their limits.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
void setup() {
myServo.attach(SERVO_PIN);
}
void loop() {
for (int angle = 10; angle <= 170; angle++) {
myServo.write(angle);
delay(15);
}
for (int angle = 170; angle >= 10; angle--) {
myServo.write(angle);
delay(15);
}
}The delay(15) gives the servo time to reach each new angle. A hobby servo typically turns about 60° in 0.1 to 0.2 s with no load, so one degree takes roughly 2 to 3 ms. A 15 ms pause makes the sweep slow and smooth, but it also blocks the sketch. The next chapter shows how to avoid that.
write() versus writeMicroseconds()
write(angle) is a convenience. Internally it converts the angle to a pulse width with a linear map. With the default settings, 0° is 544 µs and 180° is 2400 µs. Those defaults are wider than what many servos accept, which is why some servos buzz or strain at the ends.
writeMicroseconds() skips the conversion. It gives you finer resolution, since 1° is about 10 µs and you can command any value in between. It is also the better choice when you know the exact pulse range your servo supports.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
void setup() {
myServo.attach(SERVO_PIN);
}
void loop() {
myServo.writeMicroseconds(1000); // one end of travel
delay(1000);
myServo.writeMicroseconds(1500); // center
delay(1000);
myServo.writeMicroseconds(2000); // other end of travel
delay(1000);
}Many servos use 1000 µs, 1500 µs, and 2000 µs as the end, center, and end positions. Others reach further, to 500 or 2500 µs. Check your datasheet. If there is none, test in small steps and stop when the servo hums without moving.
Matching the library to your servo
You can tell attach() which pulse widths mean 0° and 180°. Then write() uses a range that fits your servo.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
const int PULSE_MIN_US = 600;
const int PULSE_MAX_US = 2400;
void setup() {
myServo.attach(SERVO_PIN, PULSE_MIN_US, PULSE_MAX_US);
}
void loop() {
myServo.write(0);
delay(1000);
myServo.write(90);
delay(1000);
myServo.write(180);
delay(1000);
}Calibrating this way means that an angle in your code matches the angle you see on the horn, and it keeps the servo off its mechanical stops.
Behavior you need to know
The first command and the first move
When you call attach(), the library starts sending pulses. A servo that has just powered up has no memory of its position, so it moves to the first position it receives. If you attach without writing first, the servo may jump to a default position (often 90°) and draw a surge of current.
To avoid a jump, set a position right after attach():
void setup() {
myServo.write(90);
myServo.attach(SERVO_PIN);
}Calling write() before attach() stores the angle, and the first pulse sent after attach() uses it. This is the usual way to start from a chosen position.
write() does not wait
write() returns immediately. The servo needs time to arrive, and the library gives no feedback about whether it did. The hobby servo has no signal wire that reports position. Calling read() returns the last angle you commanded, not the real shaft position.
If the shaft is blocked or overloaded, it may never reach the target, and your sketch will not know. When you need to know the real position, you need a servo with feedback or an added sensor.
Angle limits
write() accepts values from 0 to 180. A value below 0 is clamped to 0 and a value above 180 is clamped to 180. In the library, a value of 544 or greater is treated as a pulse width in microseconds, not as an angle. This is a legacy behavior that can hide bugs. Use writeMicroseconds() when you mean microseconds.
Holding torque, buzzing, and detach
A servo that holds a position keeps drawing current and correcting. This is useful, because it resists outside force. It also means a servo that holds a load all day heats up and wears. Some cheap servos buzz or twitch while holding, because of noise on the signal line or because the commanded angle sits just beside the position where the servo's control loop settles.
If you do not need the servo to hold, call detach() after the move:
myServo.write(90);
delay(500); // allow time to arrive
myServo.detach(); // stop pulses, servo goes limpThe shaft can then be turned by hand, or pushed by the load. Call attach() again before the next move. If you detach too early, the servo stops partway.
Several servos
Create one Servo object per servo, and attach each to its own pin.
#include <Servo.h>
Servo pan;
Servo tilt;
void setup() {
pan.attach(9);
tilt.attach(10);
pan.write(90);
tilt.write(90);
}
void loop() {
pan.write(60);
tilt.write(120);
delay(1000);
pan.write(120);
tilt.write(60);
delay(1000);
}Every servo adds to the current draw, and servos that move at the same moment draw their peaks together. Size the external supply for the sum of the stall currents, not the average. Two servos starting together can pull enough to sag a weak supply, which shows up as a reset or a twitch.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Servo jitters or twitches | Noisy supply or a missing common ground | Add a shared ground and a capacitor across the servo supply. |
| Arduino resets when the servo moves | Servo current drops the 5 V rail | Use a separate supply for the servo. |
| Servo hums at one end and does not move | Pulse range goes past the mechanical stop | Narrow the range with `attach(pin, min, max)`. |
| `analogWrite()` stops working on pin 9 or 10 | The library uses Timer1 on the Uno | Use a different PWM pin, such as 3, 5, or 6. |
| Servo jumps at startup | First pulse commands a default angle | Call `write()` with the wanted angle before `attach()`. |
| Servo never moves | Signal wire on the wrong pin, or no power | Check the pin number in `attach()` and the supply. |
Exercises
Exercise
A sketch calls myServo.write(90) and then calls myServo.attach(9) in setup(). Why does this help compared with calling attach() first and write() afterward?
Show answer
write() stores the angle before any pulses go out. The first pulse sent after attach() already carries the 90° command. If attach() runs first, the servo may receive a default pulse and jump to that position before moving to 90°.
Exercise
Your servo hums and gets warm when you command 0° and 180°, but works fine from 20° to 160°. Which call do you change, and how?
Show answer
Use attach(pin, min, max) with a narrower pulse range, such as 700 to 2300 µs, or restrict the angles in your code. The default 544 to 2400 µs range goes past what this servo can reach, so it pushes against the mechanical stop.
Exercise
You call myServo.read() right after myServo.write(120) and get 120, even though a stuck gear prevents the shaft from moving. Why is that value misleading?
Show answer
read() returns the last angle that was commanded, not a measurement. A standard hobby servo has no position output, so the library cannot know the real shaft angle.