Overview
A hobby servo contains a motor, a gearbox and a position sensor. It holds the angle set by
a pulse repeated every 20 ms: about 1 ms means one end, 1.5 ms the middle and 2 ms the
other end. The Servo library generates these pulses for you; you just call write(angle).
You will need
- Arduino Uno R3
- Micro servo such as SG90
- Jumper wires
Wiring
| Uno pin | Connects to | Notes |
|---|---|---|
| 9 | Signal (orange, yellow or white) | |
| 5V | V+ (red) | Small servo, no load only |
| GND | GND (brown or black) |
Diagram
The sketch
#include <Servo.h>
Servo arm;
const int SERVO_PIN = 9;
void setup() {
arm.attach(SERVO_PIN);
}
void loop() {
for (int angle = 0; angle <= 180; angle++) {
arm.write(angle);
delay(15);
}
for (int angle = 180; angle >= 0; angle--) {
arm.write(angle);
delay(15);
}
}How the code works
Moving 1° every 15 ms gives a sweep of about 2.7 seconds. The library's default pulse range
(544–2400 µs) can push some servos against their internal stops at 0° or 180°; if yours buzzes at the
ends, limit the range, for example arm.attach(SERVO_PIN, 1000, 2000). Use
arm.writeMicroseconds() for finer control.
On the Uno, attaching any servo disables analogWrite() on pins 9 and 10.
What you should observe
- The horn sweeps slowly from one end to the other and back.
- If the board resets or USB disconnects mid-sweep, the servo is drawing too much current: see the next article.